diff --git a/.gitignore b/.gitignore index eb8ee274..d65a34da 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ build/ db.sqlite metrics.sqlite .key/ -logs \ No newline at end of file +logs +.jwt_secret \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..be3f7b28 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index c16dbbb8..831e35be 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,17 @@ "Pub" is a [Nostr](https://nostr.info)-native account system designed to make running Lightning infrastructure for your friends/family/customers easier than previously thought possible. -It may come as a surprise that the biggest hurdle to more Uncle Jim nodes hasn't been with Bitcoin/Lightning node management itself, since even in bad patterns like mobile nodes, that is easily automated. +It may come as a surprise that the biggest hurdle to more Uncle Jim nodes hasn't been with Bitcoin/Lightning node management itself, as we've seen liquidity easily automated even in unreliable environments like mobile nodes. -It's the legacy baggage of traditional web infrastructure, things like IP4, reverse proxies, DNS, Firewalls and SSL certificates, all of which require a personal configuration that is a hurdle for most. The slow and unreliable nature of things like Tor have proven to be dead-ends, and Bolt12 being a re-implementation of Tor is destined for the same fate. +It's the legacy baggage of traditional Client-Server web infrastructure, things like IP4, Reverse Proxies, DNS, Firewalls and SSL certificates, all of which require a personal configuration that is a hurdle for most. -Pub solves these network challenges with a Full RPC that is Nostr-native. Being Nostr-native eliminates the complexity of legacy server configuration by using completely commoditized and trustless Nostr relays. Additionally, some optional services are integrated for backward compatibility with LNURL and Lightning Address. +Tor as a workaround has proven too slow and unreliable, and a dead-end for clearnet-web usecases. Bxlt12, being a re-implementation of Tor, appears destined for the same fate. -By solving the networking and programability hurdles, Pub's provide a 3rd Lightning Layer that enables node-runners and Uncle Jims to more easily bring their personal network into Bitcoin's permissionless economy. In doing so, Pub can keep the Lightning Network decentralized, with custodial scaling free of fiat rails, large banks, and other forms of high-time-preference shitcoinery. +Pub solves these challenges with a P2P-like design that is also web-friendly, by implementing a full RPC that is Nostr-native. Being Nostr-native eliminates the complexity of configuring your node like a server by using commodity Nostr relays. These relays, unlike LNURL proxies, are trustless by nature of Nostr's own encryption spec (NIP44). + +Additionally, support for optional services are integrated into Pub for operators seeking backward compatibility with legacy LNURLs and Lightning Addresses. + +By solving the networking and programability hurdles, Pub provides Lightning with a 3rd Layer that enables node-runners and Uncle Jims to more easily bring their personal network into Bitcoin's permissionless economy. In doing so, Pub runners can keep the Lightning Network decentralized, with custodial scaling that is free of fiat rails, large banks, and other forms of high-time-preference shitcoinery. #### Features: @@ -27,21 +31,30 @@ By solving the networking and programability hurdles, Pub's provide a 3rd Lightn ![Accounts](https://github.com/shocknet/Lightning.Pub/raw/master/accounting_layers.png) +- Connecting via ShockWallet is as easy as pasting an nprofile +- Or use a link to share your nprofile with friends and family + + Connect Wallet Invite Guests + + #### Planned -- [ ] Management Dashboard is actively being integrated into [ShockWallet](https://github.com/shocknet/wallet2) -- [ ] Nostr native "offers" +- [ ] A management dashboard is actively being integrated into [ShockWallet](https://github.com/shocknet/wallet2) +- [ ] Nostr native "offers" (successor to LNURL-Pay, Lightning Address, Bxlt12) - [ ] Automated Channels - [ ] Bootstrap Peering (Passive "LSP") - [ ] Event Notifications -- [ ] Submarine Swaps +- [ ] Swap integration - [ ] High-Availabilty / Clustering Dashboard Wireframe: -Pub Dashboard + Pub Dashboard > [!IMPORTANT] -> ShockWallet and Lightning.Pub are free software. If you would like to see continued development, please show your [**support**](https://github.com/sponsors/shocknet) 😊 +> ShockWallet and Lightning.Pub are free software. If you would like to see continued development, please show your [**support**](https://github.com/sponsors/shocknet) 😊
+ +License +
> [!WARNING] > While this software has been used in a high-profile production environment for over a year, it should still be considered bleeding edge. Special care has been taken to mitigate the risk of drainage attacks, which is a common risk to all Lightning API's. An integrated Watchdog service will terminate spends if it detects a discrepency between LND and the database, for this reason **IT IS NOT RECOMMENDED TO USE PUB ALONGSIDE OTHER ACCOUNT SYSTEMS**. While we give the utmost care and attention to security, **the internet is an adversarial environment and SECURITY/RELIABILITY ARE NOT GUARANTEED- USE AT YOUR OWN RISK**. @@ -58,7 +71,7 @@ Coming Soon #### Notes: * Use of a reverse proxy is only required if you wish to serve LNURLs -* The service defaults to port `8080` +* The service defaults to port `1776` * Requires [Node.js](https://nodejs.org) >=18.x * Commands for your specific OS may differ slightly, Ubuntu/Debian used for example diff --git a/env.example b/env.example index 9c01f0d9..1210cce9 100644 --- a/env.example +++ b/env.example @@ -12,10 +12,11 @@ #DB #DATABASE_FILE=db.sqlite #METRICS_DATABASE_FILE=metrics.sqlite +#LOGS_DIR=logs #LOCALHOST #ADMIN_TOKEN= -#PORT=8080 +#PORT=1776 #JWT_SECRET= #LIGHTNING @@ -67,6 +68,7 @@ #MOCK_LND=false #ALLOW_BALANCE_MIGRATION=false #MIGRATE_DB=false +#LOG_LEVEL=DEBUG #METRICS #RECORD_PERFORMANCE=true diff --git a/pub_dash_concept.jpg b/pub_dash_concept.jpg deleted file mode 100644 index 958ff70f..00000000 Binary files a/pub_dash_concept.jpg and /dev/null differ diff --git a/src/auth.ts b/src/auth.ts index e98e1652..6d7bf07f 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -3,13 +3,11 @@ import path from 'path'; import { ServerOptions } from "../proto/autogenerated/ts/express_server"; import { AdminContext, MetricsContext } from "../proto/autogenerated/ts/types"; import Main from './services/main' -import { getLogger } from './services/helpers/logger.js' - +import { ERROR, getLogger } from './services/helpers/logger.js' const serverOptions = (mainHandler: Main): ServerOptions => { const log = getLogger({}) return { - logger: { log, error: err => log("ERROR", err) }, - staticFiles: path.resolve('static'), + logger: { log, error: err => log(ERROR, err) }, AdminAuthGuard: adminAuth, MetricsAuthGuard: metricsAuth, AppAuthGuard: async (authHeader) => { return { app_id: mainHandler.applicationManager.DecodeAppToken(stripBearer(authHeader)) } }, diff --git a/src/index.ts b/src/index.ts index 231d573a..41cbb3cc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,6 +21,7 @@ const start = async () => { const nostrSettings = LoadNosrtSettingsFromEnv() const { Send } = nostrMiddleware(serverMethods, mainHandler, { ...nostrSettings, apps }) mainHandler.attachNostrSend(Send) + mainHandler.StartBeacons() const Server = NewServer(serverMethods, serverOptions(mainHandler)) Server.Listen(mainSettings.servicePort) } diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index d4cb4eef..f7c2a3e9 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -3,7 +3,7 @@ import Nostr from "./services/nostr/index.js" import { NostrSend, NostrSettings } from "./services/nostr/handler.js" import * as Types from '../proto/autogenerated/ts/types.js' import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js'; -import { getLogger } from "./services/helpers/logger.js"; +import { ERROR, getLogger } from "./services/helpers/logger.js"; export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings): { Stop: () => void, Send: NostrSend } => { const log = getLogger({}) @@ -14,7 +14,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett return { user_id: nostrUser.user.user_id, app_user_id: nostrUser.identifier, app_id: appId || "" } }, metricsCallback: metrics => mainHandler.settings.recordPerformance ? mainHandler.metricsManager.AddMetrics(metrics) : null, - logger: { log: console.log, error: err => log("ERROR", err) } + logger: { log: console.log, error: err => log(ERROR, err) } }) const nostr = new Nostr(nostrSettings, event => { let j: NostrRequest @@ -22,7 +22,11 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett j = JSON.parse(event.content) log("nostr event", j.rpcName || 'no rpc name') } catch { - log("ERROR", "invalid json event received", event.content) + log(ERROR, "invalid json event received", event.content) + return + } + if (j.authIdentifier !== event.pub) { + log(ERROR, "authIdentifier does not match", j.authIdentifier || "--", event.pub) return } nostrTransport({ ...j, appId: event.appId }, res => { diff --git a/src/services/helpers/functionQueue.ts b/src/services/helpers/functionQueue.ts index 5d3b5f21..00170e2c 100644 --- a/src/services/helpers/functionQueue.ts +++ b/src/services/helpers/functionQueue.ts @@ -7,7 +7,7 @@ export default class FunctionQueue { running: boolean = false f: () => Promise constructor(name: string, f: () => Promise) { - this.log = getLogger({ appName: name }) + this.log = getLogger({ component: name }) this.f = f } diff --git a/src/services/helpers/logger.ts b/src/services/helpers/logger.ts index a28cc0da..c7a42584 100644 --- a/src/services/helpers/logger.ts +++ b/src/services/helpers/logger.ts @@ -1,37 +1,74 @@ import fs from 'fs' -type LoggerParams = { appName?: string, userId?: string } -export type PubLogger = (...message: (string | number | object)[]) => void +export const DEBUG = Symbol("DEBUG") +export const ERROR = Symbol("ERROR") +export const WARN = Symbol("WARN") +type LoggerParams = { appName?: string, userId?: string, component?: string } +export type PubLogger = (...message: (string | number | object | symbol)[]) => void type Writer = (message: string) => void +const logsDir = process.env.LOGS_DIR || "logs" +const logLevel = process.env.LOG_LEVEL || "DEBUG" try { - fs.mkdirSync("logs") + fs.mkdirSync(logsDir) } catch { } +if (logLevel !== "DEBUG" && logLevel !== "WARN" && logLevel !== "ERROR") { + throw new Error("Invalid log level " + logLevel + " must be one of (DEBUG, WARN, ERROR)") +} const z = (n: number) => n < 10 ? `0${n}` : `${n}` const openWriter = (fileName: string): Writer => { - const logStream = fs.createWriteStream(`logs/${fileName}`, { flags: 'a' }); + const now = new Date() + const date = `${now.getFullYear()}-${z(now.getMonth() + 1)}-${z(now.getDate())}` + const logStream = fs.createWriteStream(`${logsDir}/${fileName}_${date}.log`, { flags: 'a' }); return (message) => { logStream.write(message + "\n") } } const rootWriter = openWriter("ROOT.log") -if (!fs.existsSync("logs/apps")) { - fs.mkdirSync("logs/apps", { recursive: true }); +if (!fs.existsSync(`${logsDir}/apps`)) { + fs.mkdirSync(`${logsDir}/apps`, { recursive: true }); } -if (!fs.existsSync("logs/users")) { - fs.mkdirSync("logs/users", { recursive: true }); +if (!fs.existsSync(`${logsDir}/users`)) { + fs.mkdirSync(`${logsDir}/users`, { recursive: true }); +} +if (!fs.existsSync(`${logsDir}/components`)) { + fs.mkdirSync(`${logsDir}/components`, { recursive: true }); } export const getLogger = (params: LoggerParams): PubLogger => { const writers: Writer[] = [] if (params.appName) { - writers.push(openWriter(`apps/${params.appName}.log`)) + writers.push(openWriter(`apps/${params.appName}`)) } if (params.userId) { - writers.push(openWriter(`users/${params.userId}.log`)) + writers.push(openWriter(`users/${params.userId}`)) + } + if (params.component) { + writers.push(openWriter(`components/${params.component}`)) } if (writers.length === 0) { writers.push(rootWriter) } return (...message) => { + switch (message[0]) { + case DEBUG: + if (logLevel !== "DEBUG") { + return + } + message[0] = "DEBUG" + break; + case WARN: + if (logLevel === "ERROR") { + return + } + message[0] = "WARN" + break; + case ERROR: + message[0] = "ERROR" + break; + default: + if (logLevel !== "DEBUG") { + return + } + } const now = new Date() const timestamp = `${now.getFullYear()}-${z(now.getMonth() + 1)}-${z(now.getDate())} ${z(now.getHours())}:${z(now.getMinutes())}:${z(now.getSeconds())}` const toLog = [timestamp] @@ -41,6 +78,12 @@ export const getLogger = (params: LoggerParams): PubLogger => { } toLog.push(params.appName) } + if (params.component) { + if (disabledComponents.includes(params.component)) { + return + } + toLog.push(params.component) + } if (params.userId) { toLog.push(params.userId) } @@ -50,7 +93,13 @@ export const getLogger = (params: LoggerParams): PubLogger => { writers.forEach(w => w(final)) } } -const disabledApps: string[] = [] -export const disableLoggers = (appNamesToDisable: string[]) => { +let disabledApps: string[] = [] +let disabledComponents: string[] = [] +export const resetDisabledLoggers = () => { + disabledApps = [] + disabledComponents = [] +} +export const disableLoggers = (appNamesToDisable: string[], componentsToDisable: string[]) => { disabledApps.push(...appNamesToDisable) + disabledComponents.push(...componentsToDisable) } \ No newline at end of file diff --git a/src/services/lnd/index.ts b/src/services/lnd/index.ts index 9b15a922..765db0e6 100644 --- a/src/services/lnd/index.ts +++ b/src/services/lnd/index.ts @@ -1,11 +1,11 @@ -import { EnvMustBeNonEmptyString, EnvMustBeInteger, EnvCanBeBoolean } from '../helpers/envParser.js' +import { EnvMustBeNonEmptyString, EnvMustBeInteger, EnvCanBeBoolean, EnvCanBeInteger } from '../helpers/envParser.js' import { LndSettings } from './settings.js' export const LoadLndSettingsFromEnv = (): LndSettings => { - const lndAddr = EnvMustBeNonEmptyString("LND_ADDRESS") - const lndCertPath = EnvMustBeNonEmptyString("LND_CERT_PATH") - const lndMacaroonPath = EnvMustBeNonEmptyString("LND_MACAROON_PATH") - const feeRateLimit = EnvMustBeInteger("OUTBOUND_MAX_FEE_BPS") / 10000 - const feeFixedLimit = EnvMustBeInteger("OUTBOUND_MAX_FEE_EXTRA_SATS") + const lndAddr = process.env.LND_ADDRESS || "127.0.0.1:10009" + const lndCertPath = process.env.LND_CERT_PATH || "~/.lnd/tls.cert" + const lndMacaroonPath = process.env.LND_MACAROON_PATH || "~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon" + const feeRateLimit = EnvCanBeInteger("OUTBOUND_MAX_FEE_BPS", 60) / 10000 + const feeFixedLimit = EnvCanBeInteger("OUTBOUND_MAX_FEE_EXTRA_SATS", 100) const mockLnd = EnvCanBeBoolean("MOCK_LND") return { mainNode: { lndAddr, lndCertPath, lndMacaroonPath }, feeRateLimit, feeFixedLimit, mockLnd } } diff --git a/src/services/lnd/lnd.ts b/src/services/lnd/lnd.ts index 655653af..44129bae 100644 --- a/src/services/lnd/lnd.ts +++ b/src/services/lnd/lnd.ts @@ -32,7 +32,7 @@ export default class { invoicePaidCb: InvoicePaidCb newBlockCb: NewBlockCb htlcCb: HtlcCb - log = getLogger({ appName: 'lndManager' }) + log = getLogger({ component: 'lndManager' }) outgoingOpsLocked = false constructor(settings: LndSettings, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb, newBlockCb: NewBlockCb, htlcCb: HtlcCb) { this.settings = settings @@ -298,7 +298,7 @@ export default class { return case Payment_PaymentStatus.SUCCEEDED: this.log("invoice payment succeded", Number(payment.valueSat)) - res({ feeSat: Number(payment.feeSat), valueSat: Number(payment.valueSat), paymentPreimage: payment.paymentPreimage }) + res({ feeSat: Math.ceil(Number(payment.feeMsat) / 1000), valueSat: Number(payment.valueSat), paymentPreimage: payment.paymentPreimage }) } }) }) diff --git a/src/services/main/applicationManager.ts b/src/services/main/applicationManager.ts index 0f2f6c82..15498d08 100644 --- a/src/services/main/applicationManager.ts +++ b/src/services/main/applicationManager.ts @@ -5,8 +5,9 @@ import { MainSettings } from './settings.js' import PaymentManager from './paymentManager.js' import { InboundOptionals, defaultInvoiceExpiry } from '../storage/paymentStorage.js' import { ApplicationUser } from '../storage/entity/ApplicationUser.js' -import { getLogger } from '../helpers/logger.js' +import { PubLogger, getLogger } from '../helpers/logger.js' import crypto from 'crypto' +import { Application } from '../storage/entity/Application.js' const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds @@ -19,11 +20,18 @@ export default class { settings: MainSettings paymentManager: PaymentManager nPubLinkingTokens = new Map(); - linkingTokenInterval: NodeJS.Timeout + linkingTokenInterval: NodeJS.Timeout | null = null + serviceBeaconInterval: NodeJS.Timeout | null = null + log: PubLogger constructor(storage: Storage, settings: MainSettings, paymentManager: PaymentManager) { + this.log = getLogger({ component: "ApplicationManager" }) this.storage = storage this.settings = settings this.paymentManager = paymentManager + this.StartLinkingTokenInterval() + } + + StartLinkingTokenInterval() { this.linkingTokenInterval = setInterval(() => { const now = Date.now(); for (let [token, data] of this.nPubLinkingTokens) { @@ -36,8 +44,27 @@ export default class { } }, 60 * 1000); // 1 minute } + + async StartAppsServiceBeacon(publishBeacon: (app: Application) => void) { + this.serviceBeaconInterval = setInterval(async () => { + try { + const apps = await this.storage.applicationStorage.GetApplications() + apps.forEach(app => { + publishBeacon(app) + }) + } catch (e) { + this.log("error in beacon", (e as any).message) + } + }, 60 * 1000) + } + Stop() { - clearInterval(this.linkingTokenInterval) + if (this.linkingTokenInterval) { + clearInterval(this.linkingTokenInterval) + } + if (this.serviceBeaconInterval) { + clearInterval(this.serviceBeaconInterval) + } } SignAppToken(appId: string): string { return jwt.sign({ appId }, this.settings.jwtSecret); diff --git a/src/services/main/index.ts b/src/services/main/index.ts index ef33a17c..96e456c6 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -7,7 +7,7 @@ import PaymentManager, { PendingTx } from './paymentManager.js' import { MainSettings } from './settings.js' import LND from "../lnd/lnd.js" import { AddressPaidCb, HtlcCb, InvoicePaidCb, NewBlockCb } from "../lnd/settings.js" -import { getLogger, PubLogger } from "../helpers/logger.js" +import { ERROR, getLogger, PubLogger } from "../helpers/logger.js" import AppUserManager from "./appUserManager.js" import { Application } from '../storage/entity/Application.js' import { UserReceivingInvoice } from '../storage/entity/UserReceivingInvoice.js' @@ -23,7 +23,7 @@ type UserOperationsSub = { newIncomingTx: (operation: Types.UserOperation) => void newOutgoingTx: (operation: Types.UserOperation) => void } - +const appTag = "Lightning.Pub" export default class { storage: Storage lnd: LND @@ -36,7 +36,6 @@ export default class { paymentSubs: Record void) | null> = {} metricsManager: MetricsManager nostrSend: NostrSend = () => { getLogger({})("nostr send not initialized yet") } - constructor(settings: MainSettings, storage: Storage) { this.settings = settings this.storage = storage @@ -56,6 +55,12 @@ export default class { this.paymentManager.Stop() } + StartBeacons() { + this.applicationManager.StartAppsServiceBeacon(app => { + this.UpdateBeacon(app, { type: 'service', name: app.name }) + }) + } + attachNostrSend(f: NostrSend) { this.nostrSend = f } @@ -77,7 +82,7 @@ export default class { await this.metricsManager.NewBlockCb(height, balanceEvents) confirmed = await this.paymentManager.CheckNewlyConfirmedTxs(height) } catch (err: any) { - log("failed to check transactions after new block", err.message || err) + log(ERROR, "failed to check transactions after new block", err.message || err) return } await Promise.all(confirmed.map(async c => { @@ -91,7 +96,7 @@ export default class { this.storage.StartTransaction(async tx => { const { user_address: userAddress, paid_amount: amount, service_fee: serviceFee, serial_id: serialId, tx_hash } = c.tx if (!userAddress.linkedApplication) { - log("ERROR", "an address was paid, that has no linked application") + log(ERROR, "an address was paid, that has no linked application") return } const updateResult = await this.storage.paymentStorage.UpdateAddressReceivingTransaction(serialId, { confs: c.confs }, tx) @@ -108,7 +113,6 @@ export default class { const op = { amount, paidAtUnix: Date.now() / 1000, inbound: true, type: Types.UserOperationType.INCOMING_TX, identifier: userAddress.address, operationId, network_fee: 0, service_fee: serviceFee, confirmed: true, tx_hash: c.tx.tx_hash, internal: c.tx.internal } this.sendOperationToNostr(userAddress.linkedApplication!, userAddress.user.user_id, op) }) - } })) } @@ -120,7 +124,7 @@ export default class { if (!userAddress) { return } let log = getLogger({}) if (!userAddress.linkedApplication) { - log("ERROR", "an address was paid, that has no linked application") + log(ERROR, "an address was paid, that has no linked application") return } log = getLogger({ appName: userAddress.linkedApplication.name }) @@ -145,7 +149,7 @@ export default class { const op = { amount, paidAtUnix: Date.now() / 1000, inbound: true, type: Types.UserOperationType.INCOMING_TX, identifier: userAddress.address, operationId, network_fee: 0, service_fee: fee, confirmed: internal, tx_hash: txOutput.hash, internal: false } this.sendOperationToNostr(userAddress.linkedApplication, userAddress.user.user_id, op) } catch { - + log(ERROR, "cannot process address paid transaction, already registered") } }) } @@ -158,7 +162,7 @@ export default class { if (userInvoice.paid_at_unix > 0 && internal) { log("cannot pay internally, invoice already paid"); return } if (userInvoice.paid_at_unix > 0 && !internal && userInvoice.paidByLnd) { log("invoice already paid by lnd"); return } if (!userInvoice.linkedApplication) { - log("ERROR", "an invoice was paid, that has no linked application") + log(ERROR, "an invoice was paid, that has no linked application") return } log = getLogger({ appName: userInvoice.linkedApplication.name }) @@ -181,7 +185,7 @@ export default class { this.createZapReceipt(log, userInvoice) log("paid invoice processed successfully") } catch (err: any) { - log("ERROR", "cannot process paid invoice", err.message || "") + log(ERROR, "cannot process paid invoice", err.message || "") } }) } @@ -193,7 +197,7 @@ export default class { try { await fetch(url + "&ok=true") } catch (err: any) { - log("error sending paid callback for invoice", err.message || "") + log(ERROR, "error sending paid callback for invoice", err.message || "") } } @@ -207,10 +211,26 @@ export default class { this.nostrSend(app.app_id, { type: 'content', content: JSON.stringify(message), pub: user.nostr_public_key }) } + async UpdateBeacon(app: Application, content: { type: 'service', name: string }) { + if (!app.nostr_public_key) { + getLogger({ appName: app.name })("cannot update beacon, public key not set") + return + } + const tags = [["d", appTag]] + const event: UnsignedEvent = { + content: JSON.stringify(content), + created_at: Math.floor(Date.now() / 1000), + kind: 30078, + pubkey: app.nostr_public_key, + tags, + } + this.nostrSend(app.app_id, { type: 'event', event }) + } + async createZapReceipt(log: PubLogger, invoice: UserReceivingInvoice) { const zapInfo = invoice.zap_info if (!zapInfo || !invoice.linkedApplication || !invoice.linkedApplication.nostr_public_key) { - log("no zap info linked to payment") + log(ERROR, "no zap info linked to payment") return } const tags = [["p", zapInfo.pub], ["bolt11", invoice.invoice], ["description", zapInfo.description]] diff --git a/src/services/main/paymentManager.ts b/src/services/main/paymentManager.ts index 729b22a5..d8d40d06 100644 --- a/src/services/main/paymentManager.ts +++ b/src/services/main/paymentManager.ts @@ -45,7 +45,7 @@ export default class { lnd: LND addressPaidCb: AddressPaidCb invoicePaidCb: InvoicePaidCb - log = getLogger({ appName: "PaymentManager" }) + log = getLogger({ component: "PaymentManager" }) watchDog: Watchdog constructor(storage: Storage, lnd: LND, settings: MainSettings, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb) { this.storage = storage diff --git a/src/services/main/sanityChecker.ts b/src/services/main/sanityChecker.ts index 73d94d6f..bdad7154 100644 --- a/src/services/main/sanityChecker.ts +++ b/src/services/main/sanityChecker.ts @@ -20,7 +20,7 @@ export default class SanityChecker { incrementSources: Record = {} decrementSources: Record = {} decrementEvents: Record = {} - log = getLogger({ appName: "SanityChecker" }) + log = getLogger({ component: "SanityChecker" }) users: Record = {} constructor(storage: Storage, lnd: LND) { this.storage = storage diff --git a/src/services/main/settings.ts b/src/services/main/settings.ts index 0a02d632..ee213415 100644 --- a/src/services/main/settings.ts +++ b/src/services/main/settings.ts @@ -2,7 +2,10 @@ import { LoadStorageSettingsFromEnv, StorageSettings } from '../storage/index.js import { LndSettings, NodeSettings } from '../lnd/settings.js' import { LoadWatchdogSettingsFromEnv, WatchdogSettings } from './watchdog.js' import { LoadLndSettingsFromEnv } from '../lnd/index.js' -import { EnvMustBeInteger, EnvMustBeNonEmptyString } from '../helpers/envParser.js' +import { EnvCanBeInteger, EnvMustBeInteger, EnvMustBeNonEmptyString } from '../helpers/envParser.js' +import { getLogger } from '../helpers/logger.js' +import fs from 'fs' +import crypto from 'crypto'; export type MainSettings = { storageSettings: StorageSettings, lndSettings: LndSettings, @@ -33,17 +36,17 @@ export const LoadMainSettingsFromEnv = (): MainSettings => { watchDogSettings: LoadWatchdogSettingsFromEnv(), lndSettings: LoadLndSettingsFromEnv(), storageSettings: LoadStorageSettingsFromEnv(), - jwtSecret: EnvMustBeNonEmptyString("JWT_SECRET"), - incomingTxFee: EnvMustBeInteger("INCOMING_CHAIN_FEE_ROOT_BPS") / 10000, - outgoingTxFee: EnvMustBeInteger("OUTGOING_CHAIN_FEE_ROOT_BPS") / 10000, - incomingAppInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_ROOT_BPS") / 10000, - outgoingAppInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_ROOT_BPS") / 10000, - incomingAppUserInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_USER_BPS") / 10000, - outgoingAppUserInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_USER_BPS") / 10000, - userToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_USER_BPS") / 10000, - appToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_ROOT_BPS") / 10000, - serviceUrl: process.env.SERVICE_URL || `http://localhost:${EnvMustBeInteger("PORT")}`, - servicePort: EnvMustBeInteger("PORT"), + jwtSecret: loadJwtSecret(), + incomingTxFee: EnvCanBeInteger("INCOMING_CHAIN_FEE_ROOT_BPS", 0) / 10000, + outgoingTxFee: EnvCanBeInteger("OUTGOING_CHAIN_FEE_ROOT_BPS", 60) / 10000, + incomingAppInvoiceFee: EnvCanBeInteger("INCOMING_INVOICE_FEE_ROOT_BPS", 0) / 10000, + outgoingAppInvoiceFee: EnvCanBeInteger("OUTGOING_INVOICE_FEE_ROOT_BPS", 60) / 10000, + incomingAppUserInvoiceFee: EnvCanBeInteger("INCOMING_INVOICE_FEE_USER_BPS", 0) / 10000, + outgoingAppUserInvoiceFee: EnvCanBeInteger("OUTGOING_INVOICE_FEE_USER_BPS", 0) / 10000, + userToUserFee: EnvCanBeInteger("TX_FEE_INTERNAL_USER_BPS", 0) / 10000, + appToUserFee: EnvCanBeInteger("TX_FEE_INTERNAL_ROOT_BPS", 0) / 10000, + serviceUrl: process.env.SERVICE_URL || `http://localhost:${EnvCanBeInteger("PORT", 1776)}`, + servicePort: EnvCanBeInteger("PORT", 1776), recordPerformance: process.env.RECORD_PERFORMANCE === 'true' || false, skipSanityCheck: process.env.SKIP_SANITY_CHECK === 'true' || false, disableExternalPayments: process.env.DISABLE_EXTERNAL_PAYMENTS === 'true' || false @@ -81,4 +84,22 @@ export const LoadTestSettingsFromEnv = (): TestSettings => { pass: EnvMustBeNonEmptyString("BITCOIN_CORE_PASS") } } +} + +export const loadJwtSecret = (): string => { + const secret = process.env["JWT_SECRET"] + const log = getLogger({}) + if (secret) { + return secret + } + log("JWT_SECRET not set in env, checking .jwt_secret file") + try { + const fileContent = fs.readFileSync(".jwt_secret", "utf-8") + return fileContent.trim() + } catch (e) { + log(".jwt_secret file not found, generating random secret") + const secret = crypto.randomBytes(32).toString('hex') + fs.writeFileSync(".jwt_secret", secret) + return secret + } } \ No newline at end of file diff --git a/src/services/main/watchdog.ts b/src/services/main/watchdog.ts index 693504ad..257e2614 100644 --- a/src/services/main/watchdog.ts +++ b/src/services/main/watchdog.ts @@ -23,14 +23,14 @@ export class Watchdog { settings: WatchdogSettings; storage: Storage; latestCheckStart = 0 - log = getLogger({ appName: "watchdog" }) + log = getLogger({ component: "watchdog" }) ready = false interval: NodeJS.Timer; constructor(settings: WatchdogSettings, lnd: LND, storage: Storage) { this.lnd = lnd; this.settings = settings; this.storage = storage; - this.queue = new FunctionQueue("watchdog::queue", () => this.StartCheck()) + this.queue = new FunctionQueue("watchdog_queue", () => this.StartCheck()) } Stop() { @@ -73,11 +73,10 @@ export class Watchdog { const walletBalance = await this.lnd.GetWalletBalance() this.log(Number(walletBalance.confirmedBalance), "sats in chain wallet") const channelsBalance = await this.lnd.GetChannelBalance() - getLogger({ appName: "debugLndBalancev3" })({ w: walletBalance, c: channelsBalance, u: usersTotal, f: this.accumulatedHtlcFees }) - - const localChannelsBalance = Number(channelsBalance.localBalance?.sat || 0) - const unsettledLocalBalance = Number(channelsBalance.unsettledLocalBalance?.sat || 0) - return Number(walletBalance.confirmedBalance) + localChannelsBalance + unsettledLocalBalance + getLogger({ component: "debugLndBalancev3" })({ w: walletBalance, c: channelsBalance, u: usersTotal, f: this.accumulatedHtlcFees }) + const totalLightningBalanceMsats = (channelsBalance.localBalance?.msat || 0n) + (channelsBalance.unsettledLocalBalance?.msat || 0n) + const totalLightningBalance = Math.ceil(Number(totalLightningBalanceMsats) / 1000) + return Number(walletBalance.confirmedBalance) + totalLightningBalance } checkBalanceUpdate = (deltaLnd: number, deltaUsers: number) => { diff --git a/src/services/metrics/htlcTracker.ts b/src/services/metrics/htlcTracker.ts index c95ef0ca..0bd99fe9 100644 --- a/src/services/metrics/htlcTracker.ts +++ b/src/services/metrics/htlcTracker.ts @@ -16,9 +16,9 @@ export default class HtlcTracker { constructor(storage: Storage) { this.storage = storage } - log = getLogger({ appName: 'htlcTracker' }) + log = getLogger({ component: 'htlcTracker' }) onHtlcEvent = async (htlc: HtlcEvent) => { - getLogger({ appName: 'debugHtlcs' })(htlc) + getLogger({ component: 'debugHtlcs' })(htlc) const htlcEvent = htlc.event if (htlcEvent.oneofKind === 'subscribedEvent') { this.log("htlc subscribed") diff --git a/src/services/nostr/handler.ts b/src/services/nostr/handler.ts index e7e65e51..9e213400 100644 --- a/src/services/nostr/handler.ts +++ b/src/services/nostr/handler.ts @@ -1,7 +1,7 @@ //import { SimplePool, Sub, Event, UnsignedEvent, getEventHash, signEvent } from 'nostr-tools' import { SimplePool, Sub, Event, UnsignedEvent, getEventHash, finishEvent, relayInit } from './tools/index.js' import { encryptData, decryptData, getSharedSecret, decodePayload, encodePayload } from './nip44.js' -import { getLogger } from '../helpers/logger.js' +import { ERROR, getLogger } from '../helpers/logger.js' import { encodeNprofile } from '../../custom-nip19.js' const handledEvents: string[] = [] // TODO: - big memory leak here, add TTL type AppInfo = { appId: string, publicKey: string, privateKey: string, name: string } @@ -56,13 +56,13 @@ process.on("message", (message: ChildProcessRequest) => { sendToNostr(message.appId, message.data, message.relays) break default: - getLogger({ appName: "nostrMiddleware" })("ERROR", "unknown nostr request", message) + getLogger({ component: "nostrMiddleware" })(ERROR, "unknown nostr request", message) break } }) const initSubprocessHandler = (settings: NostrSettings) => { if (subProcessHandler) { - getLogger({ appName: "nostrMiddleware" })("ERROR", "nostr settings ignored since handler already exists") + getLogger({ component: "nostrMiddleware" })(ERROR, "nostr settings ignored since handler already exists") return } subProcessHandler = new Handler(settings, event => { @@ -74,7 +74,7 @@ const initSubprocessHandler = (settings: NostrSettings) => { } const sendToNostr: NostrSend = (appId, data, relays) => { if (!subProcessHandler) { - getLogger({ appName: "nostrMiddleware" })("ERROR", "nostr was not initialized") + getLogger({ component: "nostrMiddleware" })(ERROR, "nostr was not initialized") return } subProcessHandler.Send(appId, data, relays) @@ -87,7 +87,7 @@ export default class Handler { subs: Sub[] = [] apps: Record = {} eventCallback: (event: NostrEvent) => void - log = getLogger({ appName: "nostrMiddleware" }) + log = getLogger({ component: "nostrMiddleware" }) constructor(settings: NostrSettings, eventCallback: (event: NostrEvent) => void) { this.settings = settings this.log( diff --git a/src/services/storage/db.ts b/src/services/storage/db.ts index dbba9363..be18d448 100644 --- a/src/services/storage/db.ts +++ b/src/services/storage/db.ts @@ -26,9 +26,9 @@ export type DbSettings = { } export const LoadDbSettingsFromEnv = (): DbSettings => { return { - databaseFile: EnvMustBeNonEmptyString("DATABASE_FILE"), + databaseFile: process.env.DATABASE_FILE || "db.sqlite", migrate: process.env.MIGRATE_DB === 'true' || false, - metricsDatabaseFile: EnvMustBeNonEmptyString("METRICS_DATABASE_FILE") + metricsDatabaseFile: process.env.METRICS_DATABASE_FILE || "metrics.sqlite" } } diff --git a/src/services/storage/eventsLog.ts b/src/services/storage/eventsLog.ts index 6983bcd3..4df1ee0e 100644 --- a/src/services/storage/eventsLog.ts +++ b/src/services/storage/eventsLog.ts @@ -23,7 +23,7 @@ const columns = ["timestampMs", "userId", "appUserId", "appId", "balance", "type type StringerWrite = (chunk: any, cb: (error: Error | null | undefined) => void) => boolean export default class EventsLogManager { eventLogPath: string - log = getLogger({ appName: "EventsLogManager" }) + log = getLogger({ component: "EventsLogManager" }) stringerWrite: StringerWrite constructor(eventLogPath: string) { this.eventLogPath = eventLogPath diff --git a/src/services/storage/transactionsQueue.ts b/src/services/storage/transactionsQueue.ts index 8a1894b2..48e090e8 100644 --- a/src/services/storage/transactionsQueue.ts +++ b/src/services/storage/transactionsQueue.ts @@ -15,7 +15,7 @@ export default class { log: PubLogger constructor(name: string, DB: DataSource | EntityManager) { this.DB = DB - this.log = getLogger({ appName: name }) + this.log = getLogger({ component: name }) } PushToQueue(op: TxOperation) { diff --git a/src/services/storage/userStorage.ts b/src/services/storage/userStorage.ts index 8c1d5b2d..74f0296c 100644 --- a/src/services/storage/userStorage.ts +++ b/src/services/storage/userStorage.ts @@ -94,10 +94,10 @@ export default class { user_id: userId, }, "balance_sats", increment) if (!res.affected) { - getLogger({ userId: userId, appName: "balanceUpdates" })("user unaffected by increment") + getLogger({ userId: userId, component: "balanceUpdates" })("user unaffected by increment") throw new Error("unaffected balance increment for " + userId) // TODO: fix logs doxing } - getLogger({ userId: userId, appName: "balanceUpdates" })("incremented balance from", user.balance_sats, "sats, by", increment, "sats") + getLogger({ userId: userId, component: "balanceUpdates" })("incremented balance from", user.balance_sats, "sats, by", increment, "sats") this.eventsLog.LogEvent({ type: 'balance_increment', userId, appId: "", appUserId: "", balance: user.balance_sats, data: reason, amount: increment }) } async DecrementUserBalance(userId: string, decrement: number, reason: string, entityManager?: DataSource | EntityManager) { @@ -116,17 +116,17 @@ export default class { async DecrementUserBalanceInTx(userId: string, decrement: number, reason: string, dbTx: DataSource | EntityManager) { const user = await this.GetUser(userId, dbTx) if (!user || user.balance_sats < decrement) { - getLogger({ userId: userId, appName: "balanceUpdates" })("not enough balance to decrement") + getLogger({ userId: userId, component: "balanceUpdates" })("not enough balance to decrement") throw new Error("not enough balance to decrement") } const res = await dbTx.getRepository(User).decrement({ user_id: userId, }, "balance_sats", decrement) if (!res.affected) { - getLogger({ userId: userId, appName: "balanceUpdates" })("user unaffected by decrement") + getLogger({ userId: userId, component: "balanceUpdates" })("user unaffected by decrement") throw new Error("unaffected balance decrement for " + userId) // TODO: fix logs doxing } - getLogger({ userId: userId, appName: "balanceUpdates" })("decremented balance from", user.balance_sats, "sats, by", decrement, "sats") + getLogger({ userId: userId, component: "balanceUpdates" })("decremented balance from", user.balance_sats, "sats, by", decrement, "sats") this.eventsLog.LogEvent({ type: 'balance_decrement', userId, appId: "", appUserId: "", balance: user.balance_sats, data: reason, amount: decrement }) } diff --git a/src/tests/spamExternalPayments.spec.ts b/src/tests/spamExternalPayments.spec.ts index a7e935c9..6e080469 100644 --- a/src/tests/spamExternalPayments.spec.ts +++ b/src/tests/spamExternalPayments.spec.ts @@ -4,7 +4,7 @@ import { Describe, expect, expectThrowsAsync, runSanityCheck, safelySetUserBalan export const ignore = false export default async (T: TestBase) => { - disableLoggers(["EventsLogManager", "htlcTracker", "watchdog"]) + disableLoggers([], ["EventsLogManager", "htlcTracker", "watchdog"]) await safelySetUserBalance(T, T.user1, 2000) await testSpamExternalPayment(T) await runSanityCheck(T) diff --git a/src/tests/spamMixedPayments.spec.ts b/src/tests/spamMixedPayments.spec.ts index b271369f..0abf4594 100644 --- a/src/tests/spamMixedPayments.spec.ts +++ b/src/tests/spamMixedPayments.spec.ts @@ -5,7 +5,7 @@ import * as Types from '../../proto/autogenerated/ts/types.js' export const ignore = false export default async (T: TestBase) => { - disableLoggers(["EventsLogManager", "htlcTracker", "watchdog"]) + disableLoggers([], ["EventsLogManager", "htlcTracker", "watchdog"]) await safelySetUserBalance(T, T.user1, 2000) await testSpamExternalPayment(T) await runSanityCheck(T) diff --git a/src/tests/testBase.ts b/src/tests/testBase.ts index 236de4c7..246aceb6 100644 --- a/src/tests/testBase.ts +++ b/src/tests/testBase.ts @@ -9,6 +9,7 @@ import chaiString from 'chai-string' import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js' import SanityChecker from '../services/main/sanityChecker.js' import LND from '../services/lnd/lnd.js' +import { resetDisabledLoggers } from '../services/helpers/logger.js' chai.use(chaiString) export const expect = chai.expect export type Describe = (message: string, failure?: boolean) => void @@ -69,6 +70,7 @@ export const teardown = async (T: TestBase) => { T.externalAccessToMainLnd.Stop() T.externalAccessToOtherLnd.Stop() T.externalAccessToThirdLnd.Stop() + resetDisabledLoggers() console.log("teardown") } diff --git a/src/tests/userPayment.spec.ts b/src/tests/userPayment.spec.ts new file mode 100644 index 00000000..12afbe83 --- /dev/null +++ b/src/tests/userPayment.spec.ts @@ -0,0 +1,18 @@ +import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js' +import { runSanityCheck, safelySetUserBalance, TestBase } from './testBase.js' +export const ignore = false +export const dev = false + +export default async (T: TestBase) => { + await safelySetUserBalance(T, T.user1, 2000) + await testSuccessfulUserPaymentToExternalNode(T) + await testSuccessfulUserPaymentToExternalNode(T) + await runSanityCheck(T) +} + +const testSuccessfulUserPaymentToExternalNode = async (T: TestBase) => { + T.d("starting testSuccessfulUserPaymentToExternalNode") + const invoice = await T.externalAccessToOtherLnd.NewInvoice(500, "test", defaultInvoiceExpiry) + const payment = await T.main.appUserManager.PayInvoice({ app_id: T.user1.appId, user_id: T.user1.userId, app_user_id: T.user1.appUserIdentifier }, { invoice: invoice.payRequest, amount: 0 }) + T.d("paid 500 sats invoice from user1 to external node") +} \ No newline at end of file