commit f9c3e9c4acc8160a73260d3ccabfc14c31e33923 Author: Codex Date: Mon Apr 27 10:39:14 2026 +0800 Initial ComfyUI Account Manager release diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..d5c5e52 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,26 @@ +name: Publish to Comfy registry +on: + workflow_dispatch: + push: + branches: + - main + - master + paths: + - "pyproject.toml" + +permissions: + issues: write + +jobs: + publish-node: + name: Publish Custom Node to registry + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'magicwang1111' }} + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Publish Custom Node + uses: Comfy-Org/publish-node-action@v1 + with: + ## Add your own personal access token to your Github Repository secrets and reference it here. + personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c6d210 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.py[cod] +*.log +users_db.json +whitelist.txt +blacklist.txt +.env diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0234fdc --- /dev/null +++ b/README.md @@ -0,0 +1,87 @@ +# ComfyUI Account Manager + +ComfyUI Account Manager adds login, admin-managed user registration, API token generation, IP filtering, and per-account asset isolation to ComfyUI through a custom node extension. + +## Features + +- Admin-first setup with managed user registration. +- JWT cookie or bearer-token authentication for ComfyUI routes. +- Per-account input, temp, output, queue, and history isolation. +- Per-account image/video asset visibility for generated outputs and uploaded assets. +- Admin accounts can inspect all account assets, including legacy public assets. +- Optional IP allow/deny lists, login timeout protection, HTTPS enforcement, and ComfyUI Manager admin-only access. + +## Install + +```bash +cd ComfyUI/custom_nodes +git clone https://github.com/magicwang1111/ComfyUI-Account-Manager +cd ComfyUI-Account-Manager +pip install -r requirements.txt +``` + +Restart ComfyUI, open the Web UI, and register the first account. The first registered account becomes the administrator. + +## Configuration + +Edit `config.json` before starting ComfyUI. + +```json +{ + "secret_key_env": "SECRET_KEY", + "users_db": "users_db.json", + "access_token_expiration_hours": 12, + "max_access_token_expiration_hours": 8760, + "log": "account_manager.log", + "log_levels": ["INFO"], + "whitelist": "whitelist.txt", + "blacklist": "blacklist.txt", + "blacklist_after_attempts": 0, + "free_memory_on_logout": false, + "force_https": false, + "separate_users": true, + "manager_admin_only": false +} +``` + +`separate_users` enables account-specific inputs, outputs, queue history, and asset visibility. The older misspelled `seperate_users` key is still accepted for compatibility, but new installs should use `separate_users`. + +## API Access + +Authenticated API calls can include either: + +- `Authorization: Bearer ` +- a cookie named `jwt_token` + +### Register + +`POST /register` + +```json +{ + "new_user_username": "your_username", + "new_user_password": "your_password", + "username": "admin_username", + "password": "admin_password" +} +``` + +### Login + +`POST /login` + +```json +{ + "username": "your_username", + "password": "your_password" +} +``` + +The login response includes `user_settings_id`, which is used by the frontend to bind ComfyUI requests to the authenticated account. + +## Notes + +- Ordinary users only see assets generated or uploaded under their own account. +- Administrators can view all users' assets and legacy public assets. +- Existing public assets are not migrated automatically. +- This extension improves access isolation for shared ComfyUI installs, but it is not a substitute for a full security review of your deployment. diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..ca91c10 --- /dev/null +++ b/__init__.py @@ -0,0 +1,6 @@ +from .nodes import * +from .account_manager import * + +WEB_DIRECTORY = "./web" + +__all__ = ["NODE_CLASS_MAPPINGS", "WEB_DIRECTORY"] diff --git a/account-manager-web/assets/icon.ico b/account-manager-web/assets/icon.ico new file mode 100644 index 0000000..091b60c Binary files /dev/null and b/account-manager-web/assets/icon.ico differ diff --git a/account-manager-web/assets/logo_transparent.png b/account-manager-web/assets/logo_transparent.png new file mode 100644 index 0000000..faa24ef Binary files /dev/null and b/account-manager-web/assets/logo_transparent.png differ diff --git a/account-manager-web/css/styles.css b/account-manager-web/css/styles.css new file mode 100644 index 0000000..a2935a3 --- /dev/null +++ b/account-manager-web/css/styles.css @@ -0,0 +1,386 @@ +html, +body, +div, +span, +applet, +object, +iframe, +h1, +h2, +h3, +h4, +h5, +h6, +p, +blockquote, +pre, +a, +abbr, +acronym, +address, +big, +cite, +code, +del, +dfn, +em, +img, +ins, +kbd, +q, +s, +samp, +small, +strike, +strong, +sub, +sup, +tt, +var, +b, +u, +i, +center, +dl, +dt, +dd, +ol, +ul, +li, +fieldset, +form, +label, +legend, +table, +caption, +tbody, +tfoot, +thead, +tr, +th, +td, +article, +aside, +canvas, +details, +embed, +figure, +figcaption, +footer, +header, +hgroup, +menu, +nav, +output, +ruby, +section, +summary, +time, +mark, +audio, +video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} + +/* HTML5 display-role reset for older browsers */ +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section { + display: block; +} + +body { + line-height: 1; +} + +ol, +ul { + list-style: none; +} + +blockquote, +q { + quotes: none; +} + +blockquote:before, +blockquote:after, +q:before, +q:after { + content: ''; + content: none; +} + +table { + border-collapse: collapse; + border-spacing: 0; +} + +body { + font-family: Arial, sans-serif; + background-color: #202020; + margin: 0; + padding: 0; + display: flex; + justify-content: center; + align-items: center; + width: 100vw; + min-height: 100vh; + overflow-x: hidden; +} + +.container { + background-color: #18181b; + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; + padding: 2.5rem; + margin: 2.5rem auto; + border: 1px solid #3f3f46; + border-radius: 0.5rem; + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); + width: auto; + color: #ffffff; +} + +.logo { + max-width: 128px; + max-height: 128px; + width: 100%; + height: 100%; + margin-bottom: 1rem; +} + +.title { + text-align: center; + font-size: 2rem; + font-weight: 700; +} + +.title.login, +.title.generate { + margin-bottom: 1.5rem +} + +.subtitle { + text-align: left; + font-size: 1rem; + font-weight: 700; + margin-top: 1.5rem; +} + +.divider { + display: flex; + width: 100%; + position: relative; + align-items: center; + margin: 1rem 0 1.5rem 0; +} + +.divider::after { + position: absolute; + display: block; + top: 50%; + left: 0; + width: 100%; + content: ""; + border-top: 1px solid #3f3f46; +} + +.divider.vertical { + rotate: 180deg; + margin: 1.5rem 1.5rem 0.5rem 1.5rem; +} + +.divider.vertical::after { + rotate: 180deg; + width: 0; + height: 100%; + top: 0; + left: 50%; + border-left: 1px solid #3f3f46; +} + +.form-fields { + display: flex; +} + +.form-field { + width: 100%; + margin-bottom: 1rem; +} + +label { + display: block; + margin-bottom: 0.5rem; + font-size: 14px; +} + +input { + background-color: #09090b; + color: #ffffff; + width: 250px; + padding: 0.5rem; + font-size: 1rem; + border: 1px solid #3f3f46; + border-radius: 0.25rem; + transition: 0.2s; + outline: None; +} + +input:enabled:hover { + border-color: #52525b; +} + +input:enabled:focus { + border-color: #60a5fa; +} + +input:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +input.error { + border-color: #ef4444; +} + +.btn { + width: 100%; + padding: 0.5rem; + background-color: #60a5fa; + border: 1px solid #60a5fa; + color: #18181b; + border-radius: 0.25rem; + cursor: pointer; + font-size: 0.875rem; + transition: 0.2s; +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn:not(:disabled):hover { + background-color: #92c5fd; + border: 1px solid #92c5fd; +} + +.btn:active { + background-color: #bae6fd !important; + border: 1px solid #bae6fd !important; +} + +a { + background-color: #1e3a8a; + color: #60a5fa; + text-decoration: none; + padding: 0.25rem 0.75rem; + border-radius: 0.25rem; + transition: 0.2s; +} + +a:hover { + color: #bfdbfe; +} + +a:active { + background-color: #1e40af !important; +} + +.toast-container { + position: fixed; + top: 15px; + right: 55px; + z-index: 9999; + display: flex; + flex-direction: column; + gap: 10px; + width: 300px; +} + +.toast-container .toast { + width: 100%; + height: auto; + border-radius: 0.5rem; + padding: 20px; + max-width: 400px; + text-align: left; + word-wrap: break-word; + transition: opacity 1s; + min-width: 150px; + opacity: 0; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); +} + +.toast-container .toast.show { + opacity: 1; +} + +.toast-container .toast.hide { + opacity: 0; +} + +.toast-container .toast.success { + background-color: #22c55e35; + color: #22c55e; + border: 1px solid #22c55e; +} + +.toast-container .toast.info { + background-color: #3b83f635; + color: #3b82f6; + border: 1px solid #3b82f6; +} + +.toast-container .toast.error { + background-color: #ef444435; + color: #ef4444; + border: 1px solid #ef4444; +} + + +@media (max-width: 780px) { + .form-fields { + display: block; + } + + .title { + margin-bottom: 1.5rem + } + + .subtitle { + margin-top: 0; + } +} + +@media (max-width: 420px) { + body { + background: #18181b; + } + + .container { + width: 100%; + height: 100%; + border-radius: 0; + border: none; + margin: 0; + padding: 0 2rem; + min-height: 100vh; + } +} \ No newline at end of file diff --git a/account-manager-web/generate_token.html b/account-manager-web/generate_token.html new file mode 100644 index 0000000..7cd0cd1 --- /dev/null +++ b/account-manager-web/generate_token.html @@ -0,0 +1,41 @@ + + + + + + + ComfyUI Account Manager - Generate API Token + + + + + + + +
+ +

Generate Token

+
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+
+ + + + diff --git a/account-manager-web/js/auth.js b/account-manager-web/js/auth.js new file mode 100644 index 0000000..a839f14 --- /dev/null +++ b/account-manager-web/js/auth.js @@ -0,0 +1,377 @@ +let failedAttempts = 0; +let timeoutEndTime = null; + +Object.defineProperty(String.prototype, 'capitalize', { + value: function() { + return this.charAt(0).toUpperCase() + this.slice(1); + }, + enumerable: false +}); + +if (window.location.pathname === "/register") { + document.addEventListener("DOMContentLoaded", () => { + const adminFields = document.getElementById("admin-fields"); + const registerLink = document.getElementById("register-link"); + const verticalDivider = document.getElementById("vertical-divider"); + const isAdminUser = document.body.dataset.adminUser === "true"; + + adminFields.style.display = isAdminUser ? "none" : "block"; + registerLink.style.display = isAdminUser ? "none" : "block"; + verticalDivider.style.display = isAdminUser ? "none" : "block"; + }); +} + +function addToast(message, type) { + const toasts = document.getElementById("toasts"); + const toast = document.createElement("div"); + + toast.classList.add("toast", "hide", type); + toast.textContent = message; + + toasts.appendChild(toast); + + setTimeout(() => { + toast.classList.replace("hide", "show"); + }, 500); + + setTimeout(() => { + toast.classList.replace("show", "hide"); + }, 4500); + + setTimeout(() => { + toast.remove(); + }, 5500); +} + +function validateRegisterForm() { + const usernameField = document.getElementById("new_user_username"); + const passwordField = document.getElementById("new_user_password"); + const newUsername = usernameField.value; + const newPassword = passwordField.value; + + usernameField.classList.remove("error"); + passwordField.classList.remove("error"); + + if (/[^a-zA-Z0-9_]/.test(newUsername) || /\s/.test(newUsername)) { + addToast( + "Username can only contain letters, numbers, and underscores", + "error" + ); + usernameField.classList.add("error"); + return false; + } + + if (!newUsername.trim() || newUsername.trim().length < 3) { + addToast("Username must be at least 3 characters", "error"); + usernameField.classList.add("error"); + return false; + } + + if (!newPassword.trim() || /\s/.test(newPassword)) { + addToast("Password cannot contain spaces", "error"); + passwordField.classList.add("error"); + return false; + } + + if ( + newPassword.trim().length < 8 || + !/\d/.test(newPassword) || + !/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>?/`~]/.test(newPassword) + ) { + addToast( + "Password must be at least 8 characters, include a number, and a special character", + "error" + ); + passwordField.classList.add("error"); + return false; + } + + return true; +} + +function validateGenerateForm() { + const usernameField = document.getElementById("username"); + const passwordField = document.getElementById("password"); + const expireField = document.getElementById("expire_hours"); + const expire_hours = expireField.value; + + usernameField.classList.remove("error"); + passwordField.classList.remove("error"); + expireField.classList.remove("error"); + + if (/[^0-9]/.test(expire_hours) || /\s/.test(expire_hours)) { + addToast( + "Expiration can only contain numbers", + "error" + ); + expireField.classList.add("error"); + return false; + } + + return true; +} + +function disableForm(duration, action) { + const form = document.getElementById(`${action}-form`); + const button = form.querySelector("button[type='submit']"); + button.disabled = true; + + // const fields = form.querySelectorAll("input, button"); + // fields.forEach((field) => (field.disabled = true)); + + let remainingTime = duration; + + if (remainingTime > 0) { + const countdownInterval = setInterval(() => { + const minutes = Math.floor(remainingTime / 60); + const seconds = remainingTime % 60; + const remainingTimeMessage = + remainingTime > 60 ? `${minutes}min ${seconds}s` : `${remainingTime}s`; + + button.textContent = `Wait ${remainingTimeMessage}`; + remainingTime--; + + if (remainingTime <= 0) { + clearInterval(countdownInterval); + button.disabled = false; + button.textContent = action.capitalize(); + // fields.forEach((field) => (field.disabled = false)); + } + }, 1000); + } else { + button.disabled = false; + button.textContent = action.capitalize(); + } +} + +function loadTimeoutFromStorage(action) { + const savedFailedAttempts = + parseInt(localStorage.getItem("failedAttempts"), 10) || 0; + const savedLockoutEndTime = + parseInt(localStorage.getItem("timeoutEndTime"), 10) || null; + + failedAttempts = savedFailedAttempts; + timeoutEndTime = savedLockoutEndTime; + + const currentTime = Date.now(); + const remainingTime = Math.round( + timeoutEndTime ? Math.max(0, (timeoutEndTime - currentTime) / 1000) : 0 + ); + + if (remainingTime !== 0) { + disableForm(remainingTime, action); + } +} + +function setTimeoutFromServer( + serverFailedAttempts, + serverRemainingSeconds, + action +) { + const currentTime = Date.now(); + + localStorage.setItem("failedAttempts", serverFailedAttempts); + localStorage.setItem( + "timeoutEndTime", + currentTime + serverRemainingSeconds * 1000 + ); + + loadTimeoutFromStorage(action); +} + +function updateFailedAttempts(responseStatus, result, action) { + if (![200, 400, 401, 403].includes(responseStatus)) { + return; + } + + if (result.failed_attempts && result.remaining_seconds) { + setTimeoutFromServer( + result.failed_attempts, + result.remaining_seconds, + action + ); + return; + } + + if (responseStatus === 200) { + localStorage.removeItem("failedAttempts"); + localStorage.removeItem("timeoutEndTime"); + failedAttempts = 0; + timeoutEndTime = null; + } + + if (![200, 400].includes(responseStatus)) { + failedAttempts++; + } + + localStorage.setItem("failedAttempts", failedAttempts); + + let timeoutDuration = 0; + if (failedAttempts >= 9) { + timeoutDuration = 300; + } else if (failedAttempts >= 6) { + timeoutDuration = 90; + } else if (failedAttempts >= 3) { + timeoutDuration = 60; + } + + const currentTime = Date.now(); + timeoutEndTime = currentTime + timeoutDuration * 1000; + localStorage.setItem("timeoutEndTime", timeoutEndTime); + + disableForm(timeoutDuration, action); +} + +function isTimedOut() { + const currentTime = Date.now(); + if (timeoutEndTime && currentTime < timeoutEndTime) { + const remainingTimeInSeconds = Math.round( + (timeoutEndTime - currentTime) / 1000 + ); + const minutes = Math.floor(remainingTimeInSeconds / 60); + const seconds = remainingTimeInSeconds % 60; + const remainingTimeMessage = + remainingTimeInSeconds > 60 + ? `${minutes} minute${minutes > 1 ? "s" : ""} and ${seconds} second${ + seconds > 1 ? "s" : "" + }` + : `${remainingTimeInSeconds} second${ + remainingTimeInSeconds > 1 ? "s" : "" + }`; + + addToast( + `Too many failed attempts. Please wait ${remainingTimeMessage}`, + "error" + ); + return true; + } + return false; +} + +async function login(event) { + event.preventDefault(); + + if (!isTimedOut()) { + const button = event.submitter; + const form = document.getElementById("login-form"); + const formData = new FormData(form); + const usernameField = document.getElementById("username"); + const passwordField = document.getElementById("password"); + + try { + usernameField.classList.remove("error"); + passwordField.classList.remove("error"); + button.disabled = true; + button.textContent = "Sending..."; + + const response = await fetch("/login", { + method: "POST", + body: formData, + }); + + const result = await response.json(); + + if (response.ok) { + localStorage.setItem("Comfy.userId", result.user_settings_id); + addToast(result.message, "success"); + window.location.href = "/"; + } else { + usernameField.classList.add("error"); + passwordField.classList.add("error"); + addToast(result.error || result.message || "Login failed", "error"); + } + updateFailedAttempts(response.status, result, "login"); + } catch (error) { + addToast("An error occurred: " + error.message, "error"); + button.disabled = false; + button.textContent = "Login"; + } + } +} + +async function register(event) { + event.preventDefault(); + + if (validateRegisterForm() && !isTimedOut()) { + const button = event.submitter; + const form = document.getElementById("register-form"); + const formData = new FormData(form); + + try { + button.disabled = true; + button.textContent = "Sending..."; + + const response = await fetch("/register", { + method: "POST", + body: formData, + }); + + const result = await response.json(); + + if (response.ok) { + addToast(result.message, "success"); + updateFailedAttempts(response.status, result, "register"); + + const isAdminUser = document.body.dataset.adminUser === "true"; + if (isAdminUser) { + window.location.href = "/login"; + } + + form.reset(); + } else { + addToast( + result.error || result.message || "Registration failed", + "error" + ); + } + updateFailedAttempts(response.status, result, "register"); + } catch (error) { + addToast("An error occurred: " + error.message, "error"); + button.disabled = false; + button.textContent = "Register"; + } + } +} + +async function generate(event) { + event.preventDefault(); + + if (validateGenerateForm() && !isTimedOut()) { + const button = event.submitter; + const form = document.getElementById("generate-form"); + const formData = new FormData(form); + + try { + button.disabled = true; + button.textContent = "Sending..."; + + const response = await fetch("/generate_token", { + method: "POST", + body: formData, + }); + + const result = await response.json(); + + if (response.ok) { + addToast(result.message, "success"); + updateFailedAttempts(response.status, result, "generate"); + + form.reset(); + + alert("API Token:\n"+result.jwt_token+"\n\nPlease copy this token and store it in a safe place. You will not be able to retrieve it again."); + } else { + addToast( + result.error || result.message || "Generation failed", + "error" + ); + } + updateFailedAttempts(response.status, result, "generate"); + } catch (error) { + addToast("An error occurred: " + error.message, "error"); + button.disabled = false; + button.textContent = "Generate"; + } + } +} + +loadTimeoutFromStorage(window.location.pathname.replace("/", "").split("_")[0]) diff --git a/account-manager-web/login.html b/account-manager-web/login.html new file mode 100644 index 0000000..e41aa88 --- /dev/null +++ b/account-manager-web/login.html @@ -0,0 +1,40 @@ + + + + + + + ComfyUI Account Manager - Login + + + + + + + +
+ +

Login

+
+
+ + +
+
+ + +
+ + + +
+
+
+ + + + diff --git a/account-manager-web/register.html b/account-manager-web/register.html new file mode 100644 index 0000000..7fed7dd --- /dev/null +++ b/account-manager-web/register.html @@ -0,0 +1,56 @@ + + + + + + + ComfyUI Account Manager - Register + + + + + + + +
+ +

Register

+
+
+
+

Admin Authentication

+ +
+ + +
+
+ + +
+
+ +
+

New User

+ +
+ + +
+
+ + +
+
+
+ + +
+
+
+ + + + diff --git a/account_manager.py b/account_manager.py new file mode 100644 index 0000000..aaff431 --- /dev/null +++ b/account_manager.py @@ -0,0 +1,307 @@ +import os +import jwt +import uuid +from aiohttp import web + +from server import PromptServer + +from .utils import * + +instance = PromptServer.instance +app = instance.app +routes = instance.routes + +logger = Logger(LOG_FILE, LOG_LEVELS) +sanitizer = Sanitizer() +ip_filter = IPFilter(WHITELIST, BLACKLIST) +timeout = Timeout(ip_filter, BLACKLIST_AFTER_ATTEMPTS) +users_db = UsersDB(USERS_FILE) +access_control = AccessControl(users_db, instance) +jwt_auth = JWTAuth( + users_db, access_control, logger, SECRET_KEY, TOKEN_EXPIRE_MINUTES, TOKEN_ALGORITHM +) +access_control.sync_comfy_users() + + +@routes.get("/register") +async def get_register(request: web.Request) -> web.Response: + with open(os.path.join(HTML_DIR, "register.html"), "r") as f: + html_content = f.read() + + if not users_db.load_users(): + html_content = html_content.replace("{{ X-Admin-User }}", "true") + html_content = html_content.replace("{{ X-Admin-User }}", "false") + + return web.Response(body=html_content, content_type="text/html") + + +@routes.post("/register") +async def post_register(request: web.Request) -> web.Response: + sanitized_data = request.get("_sanitized_data", {}) + ip = get_ip(request) + new_user_username = sanitized_data.get("new_user_username") + new_user_password = sanitized_data.get("new_user_password") + username = sanitized_data.get("username") + password = sanitized_data.get("password") + + username_valid, username_invalid_message = validate_username(new_user_username) + if not username_valid: + return web.json_response({"error": username_invalid_message}, status=400) + + password_valid, password_invalid_message = validate_password(new_user_password) + if not password_valid: + return web.json_response({"error": password_invalid_message}, status=400) + + admin_user = users_db.get_admin_user() + admin_user_id = None + + if admin_user[0] and (not new_user_username or not new_user_password): + return web.json_response( + {"error": "Missing new user registration details"}, status=400 + ) + + if admin_user[0]: + if not username or not password: + return web.json_response( + {"error": "Missing admin user authentication details"}, status=400 + ) + + admin_user_id = admin_user[0] + + if admin_user_id is not None: + if not ( + users_db.get_user(username)[0] == admin_user_id + and users_db.check_username_password(username, password) + ): + logger.registration_attempt( + ip, username, password, new_user_username, new_user_password + ) + timeout.add_failed_attempt(ip) + return web.json_response( + {"message": "Invalid username or password"}, status=403 + ) + + if None not in users_db.get_user(new_user_username): + return web.json_response({"error": "Username already exists"}, status=400) + + new_user_id = str(uuid.uuid4()) + users_db.add_user( + new_user_id, + new_user_username, + new_user_password, + not bool(admin_user_id), + ) + access_control.sync_comfy_users() + + logger.registration_success( + ip, new_user_username, username if admin_user_id is not None else None + ) + timeout.remove_failed_attempts(ip) + return web.json_response({"message": "User registered successfully"}) + + +@routes.get("/login") +async def get_login(request: web.Request) -> web.Response: + if not users_db.load_users(): + return web.HTTPFound("/register") + + token = jwt_auth.get_token_from_request(request) + if token: + return web.HTTPFound("/logout") + return web.FileResponse(os.path.join(HTML_DIR, "login.html")) + + +@routes.post("/login") +async def post_login(request: web.Request) -> web.Response: + sanitized_data = request.get("_sanitized_data", {}) + ip = get_ip(request) + username = sanitized_data.get("username") + password = sanitized_data.get("password") + + if not username or not password: + return web.json_response( + {"error": "Missing login credentials (username and password)"}, status=400 + ) + + if users_db.check_username_password(username, password): + timeout.remove_failed_attempts(ip) + + user_id, _ = users_db.get_user(username) + token = jwt_auth.create_access_token({"id": user_id, "username": username}) + response = web.json_response( + { + "message": "Login successful", + "jwt_token": token, + "user_settings_id": user_id, + } + ) + secure_flag = request.headers.get("X-Forwarded-Proto", "http") == "https" + response.set_cookie( + "jwt_token", token, httponly=True, secure=secure_flag, samesite="Strict" + ) + logger.login_success(ip, username) + return response + + logger.login_attempt(ip, username, password) + timeout.add_failed_attempt(ip) + return web.json_response({"error": "Invalid username or password"}, status=401) + + +@routes.get("/generate_token") +async def get_generate_token(request: web.Request) -> web.Response: + if not users_db.load_users(): + return web.HTTPFound("/register") + + token = jwt_auth.get_token_from_request(request) + if token: + return web.HTTPFound("/logout") + return web.FileResponse(os.path.join(HTML_DIR, "generate_token.html")) + + +@routes.post("/generate_token") +async def post_generate_token(request: web.Request) -> web.Response: + sanitized_data = request.get("_sanitized_data", {}) + ip = get_ip(request) + username = sanitized_data.get("username") + password = sanitized_data.get("password") + + try: + expire_hours = int( + sanitized_data.get("expire_hours", TOKEN_EXPIRE_MINUTES / 60) + ) + + except ValueError: + return web.json_response( + {"error": "Expiration hours must be a number"}, + status=400, + ) + + if expire_hours > MAX_TOKEN_EXPIRE_MINUTES / 60: + return web.json_response( + { + "error": f"Expiration hours must be smaller than {MAX_TOKEN_EXPIRE_MINUTES / 60}" + }, + status=400, + ) + + if not username or not password: + return web.json_response( + {"error": "Missing login credentials (username and password)"}, status=400 + ) + + if users_db.check_username_password(username, password): + timeout.remove_failed_attempts(ip) + + user_id, _ = users_db.get_user(username) + token = jwt_auth.create_access_token( + {"id": user_id, "username": username}, expire_minutes=(expire_hours * 60) + ) + response = web.json_response( + { + "message": "JWT Token successfully generated", + "jwt_token": token, + } + ) + secure_flag = request.headers.get("X-Forwarded-Proto", "http") == "https" + response.set_cookie( + "jwt_token", token, httponly=True, secure=secure_flag, samesite="Strict" + ) + + logger.generate_success(ip, username, expire_hours) + + return response + + logger.generate_attempt(ip, username, password, expire_hours) + timeout.add_failed_attempt(ip) + return web.json_response({"error": "Invalid username or password"}, status=401) + + +@routes.get("/logout") +async def get_logout(request: web.Request) -> web.Response: + ip = get_ip(request) + free_memory = request.query.get("free_memory", "false").lower() == "true" + unload_models = request.query.get("unload_models", "false").lower() == "true" + + token = jwt_auth.get_token_from_request(request) + if token and FREE_MEMORY_ON_LOGOUT: + try: + username = jwt_auth.decode_access_token(token).get("username") + if free_memory or unload_models: + if hasattr(instance, "post_free"): + json_data = { + "unload_models": unload_models, + "free_memory": free_memory, + } + mock_request = web.Request( + app=app, + method="POST", + path="/free", + headers={}, + match_info={}, + payload=None, + ) + mock_request._post = json_data + await instance.post_free(mock_request) + logger.memory_free(ip, username, free_memory, unload_models) + + logger.logout(ip, username) + except jwt.ExpiredSignatureError: + pass + except jwt.InvalidTokenError: + pass + except Exception as e: + logger.error(f"Unexpected error during logout: {e}") + + response = web.HTTPFound("/login") + response.del_cookie("jwt_token", path="/") + + return response + + +app.add_routes( + [ + web.static("/account-manager/css", CSS_DIR), + web.static("/account-manager/js", JS_DIR), + web.static("/account-manager/assets", ASSETS_DIR), + ] +) + +if FORCE_HTTPS: + app.middlewares.append(create_https_middleware(MATCH_HEADERS)) + +app.middlewares.append(ip_filter.create_ip_filter_middleware()) +app.middlewares.append(sanitizer.create_sanitizer_middleware()) +app.middlewares.append( + timeout.create_time_out_middleware( + limited=("/login", "/register", "/generate_token") + ) +) +app.middlewares.append( + jwt_auth.create_jwt_middleware( + public=("/login", "/logout", "/register", "/generate_token"), + public_prefixes=("/account-manager"), + ) +) + +if SEPERATE_USERS: + access_control.patch_comfy_user_manager() + access_control.patch_assets() + app.middlewares.append(access_control.create_view_access_control_middleware()) + app.middlewares.append(access_control.create_folder_access_control_middleware()) + + access_control.patch_folder_paths() + access_control.patch_prompt_queue() + +if MANAGER_ADMIN_ONLY: + app.middlewares.append( + access_control.create_manager_access_control_middleware( + manager_directory="/extensions/comfyui-manager", + manager_routes=( + "api/customnode", + "api/snapshot", + "/api/manager", + "api/comfyui_manager", + "api/externalmodel", + ), + ) + ) diff --git a/config.json b/config.json new file mode 100644 index 0000000..ba2bfb6 --- /dev/null +++ b/config.json @@ -0,0 +1,15 @@ +{ + "secret_key_env": "SECRET_KEY", + "users_db": "users_db.json", + "access_token_expiration_hours": 12, + "max_access_token_expiration_hours": 8760, + "log": "account_manager.log", + "log_levels": ["INFO"], + "whitelist": "whitelist.txt", + "blacklist": "blacklist.txt", + "blacklist_after_attempts": 0, + "free_memory_on_logout": false, + "force_https": false, + "separate_users": true, + "manager_admin_only": false +} diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..21ead82 Binary files /dev/null and b/icon.png differ diff --git a/nodes.py b/nodes.py new file mode 100644 index 0000000..aa76a1c --- /dev/null +++ b/nodes.py @@ -0,0 +1 @@ +NODE_CLASS_MAPPINGS = {} \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..021eabd --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "comfyui-account-manager" +description = "ComfyUI extension for account login, multi-user registration, and per-account asset isolation." +version = "3.0.0" +license = {file = "LICENSE"} +dependencies = ["aiohttp", "PyJWT", "bcrypt", "bleach"] + +[project.urls] +Repository = "https://github.com/magicwang1111/ComfyUI-Account-Manager" +# Used by Comfy Registry https://comfyregistry.org + +[tool.comfy] +PublisherId = "magicwang1111" +DisplayName = "ComfyUI-Account-Manager" +Icon = "https://raw.githubusercontent.com/magicwang1111/ComfyUI-Account-Manager/refs/heads/main/icon.png" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..61abb6d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +aiohttp +PyJWT +bcrypt +bleach \ No newline at end of file diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..50e2b46 --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1,12 @@ +from .config import * +from .validate import * + +from .logger import Logger +from .users_db import UsersDB + +from .force_https import create_https_middleware +from .ip_filter import IPFilter, get_ip +from .sanitizer import Sanitizer +from .timeout import Timeout +from .jwt_auth import JWTAuth +from .access_control import AccessControl \ No newline at end of file diff --git a/utils/access_control.py b/utils/access_control.py new file mode 100644 index 0000000..3ad7fc0 --- /dev/null +++ b/utils/access_control.py @@ -0,0 +1,594 @@ +import os +import sys +import heapq +import copy +import contextvars +import mimetypes +from aiohttp import web +from typing import Optional + +import folder_paths +from server import PromptServer +from execution import PromptQueue, MAXIMUM_HISTORY_SIZE + +from .users_db import UsersDB + + +class AccessControl: + def __init__(self, users_db: UsersDB, server: PromptServer): + self.users_db = users_db + self.server = server + + self._current_user = contextvars.ContextVar("user_id", default=None) + self.__current_user_id = None + + self.__get_output_directory = folder_paths.get_output_directory + self.__get_temp_directory = folder_paths.get_temp_directory + self.__get_input_directory = folder_paths.get_input_directory + self.__get_save_image_path = folder_paths.get_save_image_path + + self.__prompt_queue = self.server.prompt_queue + self.__prompt_queue_put = self.__prompt_queue.put + self.__prompt_queue_get_flags = self.__prompt_queue.get_flags + self.__user_manager_get_request_user_id = getattr( + self.server.user_manager, "get_request_user_id", None + ) + + @property + def folder_paths(self) -> tuple: + return ( + self.__get_output_directory(), + self.__get_temp_directory(), + self.__get_input_directory(), + ) + + def set_current_user_id(self, user_id: str, set_fallback: bool = False) -> None: + """Set the current authenticated user.""" + self._current_user.set(user_id) + + if set_fallback: + self.__current_user_id = user_id + + def get_current_user_id(self) -> str: + """Retrieve the active user, falling back to the latest prompt submitter.""" + if self._current_user.get(): + return self._current_user.get() + + return self.__current_user_id + + def get_context_user_id(self) -> str: + """Retrieve only the current request/execution context user.""" + return self._current_user.get() + + def is_admin_user(self, user_id: str) -> bool: + if not user_id: + return False + _, user = self.users_db.get_user(user_id=user_id) + return bool(user and user.get("admin")) + + def _can_access_owner(self, owner_id: str, current_user_id: str = None) -> bool: + current_user_id = current_user_id or self.get_current_user_id() + if self.is_admin_user(current_user_id): + return True + return bool(owner_id and owner_id == current_user_id) + + def _with_user_prefix(self, filename_prefix: str) -> str: + user_id = self.get_current_user_id() + if not user_id or not filename_prefix: + return filename_prefix + + normalized = os.path.normpath(str(filename_prefix)).replace("\\", "/") + if normalized == user_id or normalized.startswith(f"{user_id}/"): + return filename_prefix + + return f"{user_id}/{filename_prefix}" + + def get_user_output_directory(self) -> str: + """Get the user-specific output directory.""" + return os.path.join( + self.__get_output_directory(), + self.get_current_user_id() or "public", + ) + + def get_user_temp_directory(self) -> str: + """Get the user-specific temp directory.""" + return os.path.join( + self.__get_temp_directory(), + self.get_current_user_id() or "public", + ) + + def get_user_input_directory(self) -> str: + """Get the user-specific input directory.""" + input_directory = os.path.join( + self.__get_input_directory(), + self.get_current_user_id() or "public", + ) + + os.makedirs(input_directory, exist_ok=True) + + return input_directory + + def add_user_specific_folder_paths(self, json_data) -> None: + """Add user-specific output prefixes to prompt JSON data.""" + if isinstance(json_data, dict): + for key, value in json_data.items(): + if key == "filename_prefix" and isinstance(value, str): + json_data[key] = self._with_user_prefix(value) + else: + self.add_user_specific_folder_paths(value) + elif isinstance(json_data, list): + for item in json_data: + self.add_user_specific_folder_paths(item) + + return json_data + + def get_user_save_image_path( + self, + filename_prefix: str, + output_dir: str, + image_width=0, + image_height=0, + ) -> tuple[str, str, int, str, str]: + """Ensure standard ComfyUI save helpers write under the current user.""" + return self.__get_save_image_path( + self._with_user_prefix(filename_prefix), + output_dir, + image_width, + image_height, + ) + + def patch_folder_paths(self) -> None: + """Patch folder paths and save helpers with user-specific behavior.""" + folder_paths.get_temp_directory = self.get_user_temp_directory + folder_paths.get_input_directory = self.get_user_input_directory + folder_paths.get_save_image_path = self.get_user_save_image_path + + self.server.add_on_prompt_handler(self.add_user_specific_folder_paths) + + def sync_comfy_users(self) -> None: + """Mirror account-manager users into ComfyUI's in-memory user map.""" + user_manager = getattr(self.server, "user_manager", None) + if not user_manager or not hasattr(user_manager, "users"): + return + + for user_id, user in self.users_db.load_users().items(): + username = user.get("username") or user_id + user_manager.users[user_id] = username + + def patch_comfy_user_manager(self) -> None: + """Let ComfyUI APIs resolve authenticated account-manager users.""" + user_manager = getattr(self.server, "user_manager", None) + if not user_manager or self.__user_manager_get_request_user_id is None: + return + + def get_request_user_id(request): + user_id = request.get("user_id") + if user_id and user_id in self.users_db.load_users(): + return user_id + + header_user_id = request.headers.get("comfy-user") + if header_user_id and header_user_id in self.users_db.load_users(): + return header_user_id + + return self.__user_manager_get_request_user_id(request) + + user_manager.get_request_user_id = get_request_user_id + self.sync_comfy_users() + + def create_view_access_control_middleware(self) -> web.middleware: + """Guard /view and /api/view output access by top-level user folder.""" + + @web.middleware + async def view_access_control_middleware( + request: web.Request, handler + ) -> web.Response: + if request.path not in ("/view", "/api/view"): + return await handler(request) + + view_type = request.rel_url.query.get("type", "output") + if view_type != "output": + return await handler(request) + + user_id = request.get("user_id") + if self.is_admin_user(user_id): + return await handler(request) + + subfolder = request.rel_url.query.get("subfolder", "") + owner_id = os.path.normpath(subfolder).replace("\\", "/").split("/", 1)[0] + + if owner_id and owner_id == user_id: + return await handler(request) + + return web.HTTPForbidden(reason="You do not have access to this output.") + + return view_access_control_middleware + + def create_folder_access_control_middleware( + self, folder_paths: tuple = () + ) -> web.middleware: + """Create middleware for direct folder access control.""" + + folder_paths = folder_paths or self.folder_paths + + @web.middleware + async def folder_access_control_middleware( + request: web.Request, handler + ) -> web.Response: + if not request.path.startswith(folder_paths): + return await handler(request) + + current_user_id = request.get("user_id") + + try: + path_parts = request.path.strip("/").split("/") + folder_user_id = path_parts[1] + except Exception: + return web.HTTPNotFound(reason="Folder not found.") + + if not self._can_access_owner(folder_user_id, current_user_id): + return web.HTTPForbidden( + reason="You do not have access to this folder." + ) + + return await handler(request) + + return folder_access_control_middleware + + def _wrap_queue_item(self, item): + if isinstance(item, tuple) and len(item) >= 7: + return item + return item + (self.get_current_user_id(),) + + @staticmethod + def _unwrap_queue_item(item): + if isinstance(item, tuple) and len(item) >= 7: + return item[:6] + return item + + @staticmethod + def _queue_item_user_id(item): + if isinstance(item, tuple) and len(item) >= 7: + return item[6] + return None + + def _visible_queue_items(self, items): + current_user_id = self.get_current_user_id() + visible = [] + for item in items: + owner_id = self._queue_item_user_id(item) + if self._can_access_owner(owner_id, current_user_id): + visible.append(self._unwrap_queue_item(item)) + return visible + + def user_queue_put(self, item): + """Put an item in the user-specific queue.""" + wrapped_item = self._wrap_queue_item(item) + with self.__prompt_queue.mutex: + heapq.heappush(self.__prompt_queue.queue, wrapped_item) + self.server.queue_updated() + self.__prompt_queue.not_empty.notify() + + def user_queue_get(self, timeout=None): + """Get an item from the user-specific queue.""" + user_queue = self.__prompt_queue.queue + with self.__prompt_queue.not_empty: + while len(user_queue) == 0: + self.__prompt_queue.not_empty.wait(timeout=timeout) + if timeout is not None and len(user_queue) == 0: + return None + + item = heapq.heappop(user_queue) + user_id = self._queue_item_user_id(item) + self.set_current_user_id(user_id, True) + + i = self.__prompt_queue.task_counter + self.__prompt_queue.currently_running[i] = copy.deepcopy(item) + self.__prompt_queue.task_counter += 1 + self.server.queue_updated() + return (self._unwrap_queue_item(item), i) + + def user_queue_task_done( + self, + item_id, + history_result, + status: Optional["PromptQueue.ExecutionStatus"], + process_item=None, + ): + """Mark a user-specific queue task as done.""" + with self.__prompt_queue.mutex: + wrapped_prompt = self.__prompt_queue.currently_running.pop(item_id) + prompt = self._unwrap_queue_item(wrapped_prompt) + user_id = self._queue_item_user_id(wrapped_prompt) + + if len(self.__prompt_queue.history) > MAXIMUM_HISTORY_SIZE: + self.__prompt_queue.history.pop(next(iter(self.__prompt_queue.history))) + + status_dict: Optional[dict] = None + if status is not None: + status_dict = copy.deepcopy(status._asdict()) + + if process_item is not None: + prompt = process_item(prompt) + + self.__prompt_queue.history[prompt[1]] = { + "prompt": prompt, + "outputs": {}, + "status": status_dict, + "user_id": user_id, + } + self.__prompt_queue.history[prompt[1]].update(history_result) + self.server.queue_updated() + + def user_queue_get_current_queue(self): + """Get the current user-specific queue.""" + with self.__prompt_queue.mutex: + running = self._visible_queue_items(self.__prompt_queue.currently_running.values()) + queued = self._visible_queue_items(copy.deepcopy(self.__prompt_queue.queue)) + return (running, queued) + + def user_queue_get_current_queue_volatile(self): + """Get the current user-specific queue without deep copying items.""" + with self.__prompt_queue.mutex: + running = self._visible_queue_items(self.__prompt_queue.currently_running.values()) + queued = self._visible_queue_items(copy.copy(self.__prompt_queue.queue)) + return (running, queued) + + def user_queue_get_tasks_remaining(self): + with self.__prompt_queue.mutex: + return ( + len(self._visible_queue_items(self.__prompt_queue.queue)) + + len(self._visible_queue_items(self.__prompt_queue.currently_running.values())) + ) + + def user_queue_wipe_queue(self): + """Wipe the current user's queue, or all queue items for admins.""" + with self.__prompt_queue.mutex: + current_user_id = self.get_current_user_id() + if self.is_admin_user(current_user_id): + self.__prompt_queue.queue = [] + else: + self.__prompt_queue.queue = [ + item + for item in self.__prompt_queue.queue + if self._queue_item_user_id(item) != current_user_id + ] + self.server.queue_updated() + + def user_queue_delete_queue_item(self, function): + """Delete an item from the current user's queue.""" + with self.__prompt_queue.mutex: + for x in range(len(self.__prompt_queue.queue)): + item = self.__prompt_queue.queue[x] + unwrapped_item = self._unwrap_queue_item(item) + if ( + function(unwrapped_item) + and self._can_access_owner(self._queue_item_user_id(item)) + ): + self.__prompt_queue.queue.pop(x) + heapq.heapify(self.__prompt_queue.queue) + self.server.queue_updated() + return True + return False + + def _visible_history(self): + current_user_id = self.get_current_user_id() + if self.is_admin_user(current_user_id): + return self.__prompt_queue.history + return { + k: v + for k, v in self.__prompt_queue.history.items() + if v.get("user_id") == current_user_id + } + + def user_queue_get_history(self, prompt_id=None, max_items=None, offset=-1, map_function=None): + """Get the current user's queue history.""" + with self.__prompt_queue.mutex: + user_history = self._visible_history() + if prompt_id is None: + out = {} + i = 0 + if offset < 0 and max_items is not None: + offset = len(user_history) - max_items + for k in user_history: + if i >= offset: + p = user_history[k] + if map_function is None: + p = copy.deepcopy(p) + else: + p = map_function(p) + out[k] = p + if max_items is not None and len(out) >= max_items: + break + i += 1 + return out + if prompt_id in user_history: + p = user_history[prompt_id] + if map_function is None: + p = copy.deepcopy(p) + else: + p = map_function(p) + return {prompt_id: p} + return {} + + def user_queue_wipe_history(self): + """Wipe the current user's history, or all history for admins.""" + with self.__prompt_queue.mutex: + current_user_id = self.get_current_user_id() + if self.is_admin_user(current_user_id): + self.__prompt_queue.history = {} + else: + self.__prompt_queue.history = { + k: v + for k, v in self.__prompt_queue.history.items() + if v.get("user_id") != current_user_id + } + + def user_queue_delete_history_item(self, id_to_delete): + with self.__prompt_queue.mutex: + history_item = self.__prompt_queue.history.get(id_to_delete) + if history_item and self._can_access_owner(history_item.get("user_id")): + self.__prompt_queue.history.pop(id_to_delete, None) + + def patch_prompt_queue(self): + """Patch the prompt queue with user-specific methods.""" + self.__prompt_queue.put = self.user_queue_put + self.__prompt_queue.get = self.user_queue_get + self.__prompt_queue.task_done = self.user_queue_task_done + self.__prompt_queue.get_current_queue = self.user_queue_get_current_queue + self.__prompt_queue.get_current_queue_volatile = self.user_queue_get_current_queue_volatile + self.__prompt_queue.get_tasks_remaining = self.user_queue_get_tasks_remaining + self.__prompt_queue.wipe_queue = self.user_queue_wipe_queue + self.__prompt_queue.delete_queue_item = self.user_queue_delete_queue_item + self.__prompt_queue.get_history = self.user_queue_get_history + self.__prompt_queue.wipe_history = self.user_queue_wipe_history + self.__prompt_queue.delete_history_item = self.user_queue_delete_history_item + + def _default_owner_id(self) -> str: + return self.get_context_user_id() or "" + + def patch_assets(self) -> None: + """Patch ComfyUI asset ownership and visibility without editing ComfyUI.""" + try: + import app.assets.database.queries as queries + import app.assets.database.queries.common as common_queries + import app.assets.database.queries.asset_reference as asset_reference_queries + import app.assets.database.queries.tags as tag_queries + import app.assets.services as asset_services + import app.assets.services.ingest as ingest + import app.assets.services.asset_management as asset_management + import app.assets.services.tagging as tagging + from app.assets.database.models import AssetReference + from app.database.db import create_session + except Exception: + return + + def build_visible_owner_clause(owner_id: str): + owner_id = (owner_id or "").strip() + if self.is_admin_user(owner_id): + return asset_reference_queries.sa.true() + if owner_id == "": + return AssetReference.owner_id == "" + return AssetReference.owner_id == owner_id + + def get_reference_with_owner_check(session, reference_id: str, owner_id: str): + ref = asset_reference_queries.get_reference_by_id( + session, reference_id=reference_id + ) + if not ref or ref.deleted_at is not None: + raise ValueError(f"AssetReference {reference_id} not found") + if self.is_admin_user(owner_id): + return ref + if not ref.owner_id or ref.owner_id != owner_id: + raise PermissionError("not owner") + return ref + + common_queries.build_visible_owner_clause = build_visible_owner_clause + asset_reference_queries.build_visible_owner_clause = build_visible_owner_clause + tag_queries.build_visible_owner_clause = build_visible_owner_clause + queries.build_visible_owner_clause = build_visible_owner_clause + + asset_reference_queries.get_reference_with_owner_check = get_reference_with_owner_check + queries.get_reference_with_owner_check = get_reference_with_owner_check + asset_management.get_reference_with_owner_check = get_reference_with_owner_check + tagging.get_reference_with_owner_check = get_reference_with_owner_check + + original_ingest_existing_file = ingest.ingest_existing_file + original_upload_from_temp_path = ingest.upload_from_temp_path + original_register_file_in_place = ingest.register_file_in_place + original_create_from_hash = ingest.create_from_hash + + def ingest_existing_file(*args, owner_id="", **kwargs): + owner_id = owner_id or self._default_owner_id() + return original_ingest_existing_file(*args, owner_id=owner_id, **kwargs) + + def upload_from_temp_path(*args, owner_id="", **kwargs): + owner_id = owner_id or self._default_owner_id() + return original_upload_from_temp_path(*args, owner_id=owner_id, **kwargs) + + def register_file_in_place(*args, owner_id="", **kwargs): + owner_id = owner_id or self._default_owner_id() + return original_register_file_in_place(*args, owner_id=owner_id, **kwargs) + + def create_from_hash(*args, owner_id="", **kwargs): + owner_id = owner_id or self._default_owner_id() + return original_create_from_hash(*args, owner_id=owner_id, **kwargs) + + ingest.ingest_existing_file = ingest_existing_file + ingest.upload_from_temp_path = upload_from_temp_path + ingest.register_file_in_place = register_file_in_place + ingest.create_from_hash = create_from_hash + + asset_services.upload_from_temp_path = upload_from_temp_path + asset_services.register_file_in_place = register_file_in_place + asset_services.create_from_hash = create_from_hash + + def resolve_hash_to_path(asset_hash: str, owner_id: str = ""): + with create_session() as session: + asset = asset_management.queries_get_asset_by_hash(session, asset_hash) + if not asset: + return None + refs = asset_management.list_references_by_asset_id( + session, asset_id=asset.id + ) + if self.is_admin_user(owner_id): + visible = refs + else: + visible = [r for r in refs if r.owner_id == owner_id] + abs_path = asset_management.select_best_live_path(visible) + if not abs_path: + return None + display_name = os.path.basename(abs_path) + for ref in visible: + if ref.file_path == abs_path and ref.name: + display_name = ref.name + break + content_type = ( + asset.mime_type + or mimetypes.guess_type(display_name)[0] + or "application/octet-stream" + ) + return asset_management.DownloadResolutionResult( + abs_path=abs_path, + content_type=content_type, + download_name=display_name, + ) + + asset_management.resolve_hash_to_path = resolve_hash_to_path + asset_services.resolve_hash_to_path = resolve_hash_to_path + + route_module = sys.modules.get("app.assets.api.routes") + if route_module: + route_module.upload_from_temp_path = upload_from_temp_path + route_module.create_from_hash = create_from_hash + + for module_name in ("server", "__main__", "main"): + module = sys.modules.get(module_name) + if not module: + continue + if hasattr(module, "register_file_in_place"): + module.register_file_in_place = register_file_in_place + if hasattr(module, "resolve_hash_to_path"): + module.resolve_hash_to_path = resolve_hash_to_path + + def create_manager_access_control_middleware( + self, manager_directory: str = "/extensions/comfyui-manager", manager_routes: tuple = () + ) -> web.middleware: + """Create middleware for manager access control.""" + + @web.middleware + async def manager_access_control_middleware( + request: web.Request, handler + ) -> web.Response: + user_id = request.get("user_id") + + if self.users_db.get_admin_user()[0] == user_id or ( + not request.path.startswith(manager_routes) + and not request.path.lower().startswith(manager_directory) + ): + return await handler(request) + + return web.HTTPForbidden( + reason="You do not have access to comfyui manager." + ) + + return manager_access_control_middleware diff --git a/utils/config.py b/utils/config.py new file mode 100644 index 0000000..b862c17 --- /dev/null +++ b/utils/config.py @@ -0,0 +1,59 @@ +import os +import warnings +import uuid +import json +from typing import Dict, Any + +EXT_PATH = os.path.join(os.path.dirname(__file__), "..") +CONFIG_FILE = os.path.join(EXT_PATH, "config.json") + + +def load_config(file_path: str) -> Dict[str, Any]: + if os.path.exists(file_path): + with open(file_path, "r") as f: + try: + return json.load(f) + except json.JSONDecodeError: + return {} + return {} + + +config = load_config(CONFIG_FILE) + +SECRET_KEY = os.getenv(config.get("secret_key_env", "SECRET_KEY")) + +if not SECRET_KEY: + warnings.warn( + "The SECRET_KEY environment variable is not set. A random key will be used for this session. " + "This will cause all users to log out on server restart." + ) + SECRET_KEY = "".join([str(uuid.uuid4().hex) for _ in range(128)]) + +MATCH_HEADERS = {"X-Forwarded-Proto": "https"} + +TOKEN_ALGORITHM = "HS256" +TOKEN_EXPIRE_MINUTES = 60 * config.get("access_token_expiration_hours", 12) +MAX_TOKEN_EXPIRE_MINUTES = 60 * config.get("max_access_token_expiration_hours", 8760) + +USERS_FILE = os.path.join(EXT_PATH, config.get("users_db", "users_db.json")) +LOG_FILE = os.path.join(EXT_PATH, config.get("log", "account_manager.log")) +LOG_LEVELS = config.get("log_levels", ["INFO"]) + +WHITELIST = os.path.join(EXT_PATH, config.get("whitelist", "whitelist.txt")) +BLACKLIST = os.path.join(EXT_PATH, config.get("blacklist", "blacklist.txt")) + +BLACKLIST_AFTER_ATTEMPTS = config.get("blacklist_after_attempts") + +FREE_MEMORY_ON_LOGOUT = config.get("free_memory_on_logout", False) +FORCE_HTTPS = config.get("force_https", False) + +SEPARATE_USERS = config.get("separate_users", config.get("seperate_users", False)) +SEPERATE_USERS = SEPARATE_USERS + +MANAGER_ADMIN_ONLY = config.get("manager_admin_only", False) + +WEB_DIR = os.path.join(EXT_PATH, "account-manager-web") +HTML_DIR = WEB_DIR +CSS_DIR = os.path.join(WEB_DIR, "css") +JS_DIR = os.path.join(WEB_DIR, "js") +ASSETS_DIR = os.path.join(WEB_DIR, "assets") diff --git a/utils/force_https.py b/utils/force_https.py new file mode 100644 index 0000000..d6ee82c --- /dev/null +++ b/utils/force_https.py @@ -0,0 +1,22 @@ +from aiohttp import web + + +def create_https_middleware(match_headers: dict | None) -> web.middleware: + """ + Create middlware to change scheme of current request when HTTPS headers matched. + """ + + @web.middleware + async def https_middleware(request: web.Request, handler) -> web.StreamResponse: + """Change scheme of current request when HTTPS headers matched.""" + + matched = any( + request.headers.get(key) == value for key, value in match_headers.items() + ) + + if matched: + request = request.clone(scheme="https") + + return await handler(request) + + return https_middleware diff --git a/utils/ip_filter.py b/utils/ip_filter.py new file mode 100644 index 0000000..cf6d3a1 --- /dev/null +++ b/utils/ip_filter.py @@ -0,0 +1,150 @@ +import os +import hashlib +import ipaddress + +from aiohttp import web +from pathlib import Path + + +def get_ip(request: web.Request) -> ipaddress.IPv4Address | ipaddress.IPv6Address: + forwarded = request.headers.get("X-Forwarded-For") + if forwarded: + ip = forwarded.split(",")[0].strip() + else: + ip = request.headers.get("X-Real-IP") + + if not ip: + ip = request.remote + + try: + ip = str(ipaddress.ip_address(ip)) + except ValueError: + ip = "" + + return ip + + +class IPFilter: + def __init__(self, whitelist_file: str | Path, blacklist_file: str | Path): + self.whitelist_file = whitelist_file + self.blacklist_file = blacklist_file + + self._whitelist_hash = None + self._blacklist_hash = None + + self.whitelist = [] + self.blacklist = [] + + self.load_filter_list() + + @staticmethod + def calculate_file_hash(filter_file) -> str: + """Calculate the SHA256 hash of the filter IP list file.""" + if os.path.exists(filter_file): + with open(filter_file, "rb") as f: + file_data = f.read() + return hashlib.sha256(file_data).hexdigest() + return "" + + def load_filter_list(self) -> tuple[dict, dict]: + """Load whitelist and blacklist IP lists from files.""" + + def load_ip_list( + file_path: str | Path, current_hash: str, hash_attribute: str + ) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]: + ip_list = [] + new_hash = self.calculate_file_hash(file_path) + if new_hash != current_hash: + if os.path.exists(file_path): + with open(file_path, "r") as f: + for line in f: + ip = line.strip() + if ip: + try: + ip_list.append(ipaddress.ip_address(ip)) + except ValueError: + continue + setattr(self, hash_attribute, new_hash) + + else: + return getattr(self, hash_attribute.split("_")[0]) + + return ip_list + + self.whitelist = load_ip_list( + self.whitelist_file, self._whitelist_hash, "_whitelist_hash" + ) + self.blacklist = load_ip_list( + self.blacklist_file, self._blacklist_hash, "_blacklist_hash" + ) + + return self.whitelist, self.blacklist + + def is_allowed(self, ip: str) -> bool: + """ + Checks if the given IP address is allowed based on the whitelist and blacklist. + - If the whitelist is not empty, the IP must be in the whitelist to be allowed. + - If the whitelist is empty, the IP is denied if it is in the blacklist. + - If the whitelist is empty and IP is not in the blacklist, it is allowed. + """ + self.load_filter_list() + + try: + ip = ipaddress.ip_address(ip) + except: + return False + + if self.whitelist: + if ip in self.whitelist: + return True + + return False + + if ip in self.blacklist: + return False + + return True + + def add_to_blacklist(self, ip: str) -> None: + """Add a given IP to the blacklist""" + try: + ip = ipaddress.ip_address(ip) + except ValueError: + return + if ip not in self.blacklist: + self.blacklist.append(ip) + + with open(self.blacklist_file, "a") as file: + if file.tell() > 0: + file.seek(file.tell() - 1) + if file.read(1) != "\n": + file.write("\n") + + file.write(str(ip) + "\n") + + def create_ip_filter_middleware(self) -> web.middleware: + """Create the middleware for managing blacklisted and whitelisted ip.""" + + @web.middleware + async def ip_filter_middleware(request: web.Request, handler) -> web.Response: + ip = get_ip(request) + + if not self.is_allowed(ip): + return await handle_access_denied( + request, + "Access denied: IP is either not whitelisted or is blacklisted.", + ) + + return await handler(request) + + async def handle_access_denied( + request: web.Request, message: str + ) -> web.Response: + """Handle denied access cases.""" + accept_header = request.headers.get("Accept", "") + if "text/html" in accept_header: + return web.HTTPForbidden(reason=message) + else: + return web.json_response({"error": message}, status=403) + + return ip_filter_middleware diff --git a/utils/jwt_auth.py b/utils/jwt_auth.py new file mode 100644 index 0000000..3139b6d --- /dev/null +++ b/utils/jwt_auth.py @@ -0,0 +1,116 @@ +import jwt +from aiohttp import web +from datetime import datetime, timedelta, timezone + +from .users_db import UsersDB +from .access_control import AccessControl +from .logger import Logger + + +class JWTAuth: + def __init__( + self, + users_db: UsersDB, + access_control: AccessControl, + logger: Logger, + secret_key: str, + expire_minutes: int = 12 * 60, + algorithm: str = "HS256", + ): + self.users_db = users_db + self.access_control = access_control + self.logger = logger + + self.expire_minutes = expire_minutes + self.algorithm = algorithm + + self.__secret_key = secret_key + + @staticmethod + def get_token_from_request(request: web.Request) -> str: + """Extract token from request headers or cookies.""" + auth_header = request.headers.get("Authorization", "") + if auth_header.startswith("Bearer "): + return auth_header[len("Bearer ") :] + return request.cookies.get("jwt_token") + + def create_access_token(self, data: dict, expire_minutes=None) -> str: + """Create a JWT access token.""" + to_encode = data.copy() + if not expire_minutes: + expire_minutes = self.expire_minutes + expire = datetime.now(timezone.utc) + timedelta(minutes=expire_minutes) + to_encode.update({"exp": expire}) + return jwt.encode(to_encode, self.__secret_key, algorithm=self.algorithm) + + def decode_access_token(self, token: str) -> dict: + """Decode a JWT access token.""" + return jwt.decode(token, self.__secret_key, algorithms=[self.algorithm]) + + def create_jwt_middleware( + self, + public: tuple = (), + public_prefixes: tuple = (), + public_suffixes: tuple = (), + ) -> web.middleware: + """Create middleware for JWT authentication.""" + + @web.middleware + async def jwt_middleware(request: web.Request, handler) -> web.Response: + """Middleware to handle JWT authentication.""" + if ( + request.path in public + or request.path.startswith(public_prefixes) + or request.path.endswith(public_suffixes) + ): + return await handler(request) + + token = self.get_token_from_request(request) + + if not token: + return await handle_unauthorized_access(request, "/login") + + try: + user = self.decode_access_token(token) + user_id = user.get("id") + username = user.get("username") + if not user_id == self.users_db.get_user(username)[0]: + raise ValueError( + f"User with username: {username} is not in the database" + ) + + request["user_id"] = user_id + request["user"] = username + + set_fallback = request.path in ["/prompt", "/api/prompt"] + self.access_control.set_current_user_id(user_id, set_fallback) + + except jwt.ExpiredSignatureError: + return await handle_unauthorized_access( + request, "/logout", message="Token has expired" + ) + except jwt.DecodeError: + return await handle_unauthorized_access( + request, "/logout", message="Token is invalid" + ) + except Exception as e: + self.logger.error(f"Unexpected error during token decoding: {e}") + return await handle_unauthorized_access( + request, "/logout", message="Unexpected error" + ) + + return await handler(request) + + async def handle_unauthorized_access( + request: web.Request, + redirect_path: str, + message: str = "Authentication required", + ) -> web.Response: + """Handle unauthorized access cases.""" + accept_header = request.headers.get("Accept", "") + if "text/html" in accept_header: + return web.HTTPFound(redirect_path) + else: + return web.json_response({"error": message}, status=401) + + return jwt_middleware diff --git a/utils/logger.py b/utils/logger.py new file mode 100644 index 0000000..56bcbd8 --- /dev/null +++ b/utils/logger.py @@ -0,0 +1,107 @@ +import logging + +from pathlib import Path +from datetime import datetime +from typing import List, Optional, Callable + +LEVELS = {"INFO", "WARNING", "ERROR", "DEBUG"} + + +class Logger: + def __init__( + self, + log_file: str | Path, + log_levels: List[str], + callback: Optional[Callable[[str], None]] = None, + ): + if not all(level in LEVELS for level in log_levels): + raise ValueError(f"Invalid log levels provided. Valid levels are: {LEVELS}") + + self.log_levels = log_levels + self.log_file = log_file + self.callback = callback + + self.logger = logging.getLogger("ComfyUI-Account-Manager") + + def log_message(self, level: str, message: str) -> None: + if level not in self.log_levels: + return + + log_entry = f"{datetime.now().isoformat()} - {level} - {message}\n" + + with open(self.log_file, "a") as log_file: + log_file.write(log_entry) + + if level == "INFO": + self.logger.info(message) + elif level == "WARNING": + self.logger.warning(message) + elif level == "ERROR": + self.logger.error(message) + elif level == "DEBUG": + self.logger.debug(message) + + if self.callback: + self.callback(log_entry) + + def info(self, message: str) -> None: + self.log_message("INFO", message) + + def warning(self, message: str) -> None: + self.log_message("WARNING", message) + + def error(self, message: str) -> None: + self.log_message("ERROR", message) + + def debug(self, message: str) -> None: + self.log_message("DEBUG", message) + + def login_attempt(self, ip: str, username: str, password: str) -> None: + self.info( + f"Warning: Attempted login from IP: {ip} with username: '{username}' and password: '{password}'" + ) + + def login_success(self, ip: str, username: str) -> None: + self.info(f"User: '{username}' logged in from IP: {ip}") + + def generate_attempt(self, ip: str, username: str, password: str, expire_hours: int) -> None: + self.info( + f"Warning: Attempted generation from IP: {ip} with username: '{username}', password: '{password}' and expiration hours: {expire_hours}" + ) + + def generate_success(self, ip: str, username: str, expire_hours: int) -> None: + self.info(f"User: '{username}' generated token from IP: {ip} with expiration hours: {expire_hours}") + + def registration_attempt( + self, + ip: str, + username: str, + password: str, + new_username: str, + new_password: str, + ) -> None: + self.info( + f"Warning: Attempted registration from IP: {ip} with username: '{username}' and password: '{password}' for new user username: '{new_username}' and password: '{new_password}'" + ) + + def registration_success( + self, ip: str, new_user: str, registered_by: str = None + ) -> None: + if registered_by: + self.info( + f"New user: '{new_user}' Registered by '{registered_by}' from IP: {ip}" + ) + else: + self.info(f"Admin user: '{new_user}' Registered from IP: {ip}") + + def memory_free( + self, ip: str, username: str, free_memory: bool, unload_models: bool + ) -> None: + if free_memory: + self.info(f"User: '{username}' freed memory from IP: {ip}") + + if unload_models: + self.info(f"User: '{username}' unloaded models from IP: {ip}") + + def logout(self, ip: str, username: str) -> None: + self.info(f"User: '{username}' logged out from IP: {ip}") diff --git a/utils/sanitizer.py b/utils/sanitizer.py new file mode 100644 index 0000000..8ca3df1 --- /dev/null +++ b/utils/sanitizer.py @@ -0,0 +1,68 @@ +import re +import unicodedata +import html +from aiohttp import web +from bleach import clean + + +class Sanitizer: + @staticmethod + def sanitize_input(value): + """Sanitize user input of various types to prevent security risks.""" + if isinstance(value, str): + value = value.strip() + value = unicodedata.normalize("NFC", value) + value = html.escape(value) + value = value.replace("\r", "").replace("\n", "") + value = re.sub(r"([;'\-()<>`=])", r"\\\1", value) + value = re.sub(r"[;&|`]", "", value) + value = clean(value, tags=[], attributes=[], protocols=[]) + + xss_patterns = [ + r".*?", + r"javascript:", + r"vbscript:", + r"data:text/html", + r"data:image", + ] + for pattern in xss_patterns: + value = re.sub(pattern, "", value, flags=re.IGNORECASE) + + elif isinstance(value, (int, float)): + return value + + elif isinstance(value, (list, dict)): + return ( + [Sanitizer.sanitize_input(item) for item in value] + if isinstance(value, list) + else {key: Sanitizer.sanitize_input(val) for key, val in value.items()} + ) + + return value + + def create_sanitizer_middleware(self) -> web.middleware: + """Create middleware to sanitize all request inputs.""" + + @web.middleware + async def sanitizer_middleware(request: web.Request, handler) -> web.Response: + """Middleware to sanitize all request inputs.""" + if request.can_read_body: + try: + data = await request.post() + sanitized_data = { + key: self.sanitize_input(value) for key, value in data.items() + } + request["_sanitized_data"] = sanitized_data + except Exception: + pass + + if request.query: + sanitized_query = { + key: self.sanitize_input(value) + for key, value in request.query.items() + } + request["_sanitized_query"] = sanitized_query + + return await handler(request) + + return sanitizer_middleware diff --git a/utils/timeout.py b/utils/timeout.py new file mode 100644 index 0000000..d75fb99 --- /dev/null +++ b/utils/timeout.py @@ -0,0 +1,97 @@ +from typing import Optional +from aiohttp import web +from datetime import datetime, timezone, timedelta + +from .ip_filter import IPFilter, get_ip + +class Timeout: + def __init__(self, ip_filter: IPFilter, blacklist_after_attempts: int = 0): + self.ip_filter = ip_filter + self.blacklist_after_attempts = blacklist_after_attempts + + self._failed_attempts_ip = {} + self._timeout_end_time_ip = {} + + def get_failed_attempts(self, ip: str) -> int: + """Get the number of failed attempts for a given IP.""" + return self._failed_attempts_ip.get(ip, 0) + + def add_failed_attempt(self, ip: str) -> None: + """Add a failed attempt for a given IP and set timeout or blacklist IP if necessary.""" + whitelist, _ = self.ip_filter.load_filter_list() + + if ip in whitelist: + return + + self._failed_attempts_ip[ip] = self._failed_attempts_ip.get(ip, 0) + 1 + failed_attempts = self._failed_attempts_ip[ip] + + if not self.blacklist_after_attempts == 0: + if failed_attempts >= self.blacklist_after_attempts: + self.ip_filter.add_to_blacklist(ip) + + timeout_duration = 0 + if failed_attempts >= 9: + timeout_duration = 300 + elif failed_attempts >= 6: + timeout_duration = 90 + elif failed_attempts >= 3: + timeout_duration = 60 + + if timeout_duration > 0: + self._timeout_end_time_ip[ip] = datetime.now(timezone.utc) + timedelta( + seconds=timeout_duration + ) + + def remove_failed_attempts(self, ip: str) -> None: + """Remove failed attempts and timeout for a given IP.""" + self._failed_attempts_ip.pop(ip, None) + self._timeout_end_time_ip.pop(ip, None) + + def get_timeout_end_time(self, ip: str) -> Optional[datetime]: + """Get the timeout end time for a given IP.""" + return self._timeout_end_time_ip.get(ip) + + def check_is_timed_out(self, ip: str) -> tuple[bool, int, int]: + """Check if a given IP is currently timed out.""" + timeout_end_time = self.get_timeout_end_time(ip) + + if timeout_end_time and datetime.now(timezone.utc) < timeout_end_time: + remaining_seconds = round( + (timeout_end_time - datetime.now(timezone.utc)).total_seconds() + ) + return True, self.get_failed_attempts(ip), remaining_seconds + + return False, self.get_failed_attempts(ip), 0 + + def create_time_out_middleware(self, limited: tuple = ()) -> web.middleware: + """Create middleware for handling timeouts.""" + + @web.middleware + async def time_out_middleware(request: web.Request, handler) -> web.Response: + """Middleware to handle request timeouts.""" + if request.path in limited and request.method == "POST": + is_timed_out, failed_attempts, remaining_seconds = ( + self.check_is_timed_out(get_ip(request)) + ) + + if is_timed_out: + minutes, seconds = divmod(int(remaining_seconds), 60) + + if minutes > 0: + remaining_time = f"{minutes} minute{'s' if minutes > 1 else ''} and {seconds} second{'s' if seconds > 1 else ''}" + else: + remaining_time = f"{seconds} second{'s' if seconds > 1 else ''}" + + return web.json_response( + { + "error": f"Too many failed attempts. Please wait {remaining_time}", + "failed_attempts": failed_attempts, + "remaining_seconds": remaining_seconds, + }, + status=403, + ) + + return await handler(request) + + return time_out_middleware diff --git a/utils/users_db.py b/utils/users_db.py new file mode 100644 index 0000000..7c33686 --- /dev/null +++ b/utils/users_db.py @@ -0,0 +1,94 @@ +import bcrypt +import json +import os +import hashlib +from pathlib import Path + + +class UsersDB: + def __init__(self, database: str | Path): + self.database = database + + self.users = {} + self.admin_user = (None, {}) + + self._database_hash = None + + self.load_users() + + @staticmethod + def hash_password(password: str) -> str: + """Hash a password using bcrypt.""" + return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + + def calculate_file_hash(self) -> str: + """Calculate the SHA256 hash of the database file.""" + if os.path.exists(self.database): + with open(self.database, "rb") as f: + file_data = f.read() + return hashlib.sha256(file_data).hexdigest() + return "" + + def load_users(self) -> dict: + """Load users from the database if it has changed.""" + current_hash = self.calculate_file_hash() + if current_hash != self._database_hash: + if os.path.exists(self.database): + with open(self.database, "r") as f: + try: + self.users = json.load(f) + self._database_hash = current_hash + except json.JSONDecodeError: + self.users = {} + return self.users + + def save_users(self, users: dict) -> None: + """Save users to the database and update the hash.""" + with open(self.database, "w") as f: + json.dump(users, f) + + self._database_hash = self.calculate_file_hash() + + def add_user(self, id: str, username: str, password: str, admin: bool) -> None: + """Add a user to the database.""" + self.load_users() + user = {"username": username, "password": self.hash_password(password)} + if admin: + user["admin"] = admin + self.users[id] = user + self.save_users(self.users) + + def get_user(self, username: str = "", user_id: str = "") -> tuple[str, dict]: + """Retrieve a user by username or ID.""" + self.load_users() + + if user_id: + user = self.users.get(user_id) + if user: + return user_id, user + return None, {} + + for uid, user_data in self.users.items(): + if user_data["username"] == username: + return uid, user_data + + return None, {} + + def check_username_password(self, username: str, password: str) -> bool: + """Check if the username and password match.""" + user_id, user_data = self.get_user(username) + if not user_id: + return False + + return bcrypt.checkpw( + password.encode("utf-8"), user_data["password"].encode("utf-8") + ) + + def get_admin_user(self) -> tuple[str, dict] | None: + """Get the admin user from the database.""" + self.load_users() + for uid, user_data in self.users.items(): + if user_data.get("admin"): + self.admin_user = (uid, user_data) + + return self.admin_user diff --git a/utils/validate.py b/utils/validate.py new file mode 100644 index 0000000..f819e56 --- /dev/null +++ b/utils/validate.py @@ -0,0 +1,32 @@ +import re + + +def validate_username(username: str) -> tuple[bool, str]: + """ + Validate username based on: + - Only letters, numbers, and underscores. + - No spaces. + - At least 3 characters long. + """ + if re.match(r"^[a-zA-Z0-9_]{3,}$", username): + return True, "" + return ( + False, + "Username must be at least 3 characters, contain only letters, numbers, and underscores, and cannot contain spaces.", + ) + + +def validate_password(password: str) -> tuple[bool, str]: + """ + Validate password based on: + - At least 8 characters long. + - Must contain at least one digit. + - Must contain at least one special character (e.g., !@#$%^&*). + - Cannot contain spaces. + """ + if re.match(r"^(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>?/`~])[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>?/`~]{8,}$", password): + return True, "" + return ( + False, + "Password must be at least 8 characters long, contain at least one digit, one special character, and no spaces.", + ) diff --git a/web/js/injectCSS.js b/web/js/injectCSS.js new file mode 100644 index 0000000..5b75b44 --- /dev/null +++ b/web/js/injectCSS.js @@ -0,0 +1,28 @@ +import { $el } from "/scripts/ui.js"; + +$el("style", { + textContent: ` + .account-manager-logout { + color: var(--p-red-600) !important; + } + + .account-manager-logout:hover { + background: var(--p-red-600) !important; + color: var(--p-red-300) !important; + } + + #logout-menu-button { + background-color: var(--p-red-600) !important; + } + + #logout-menu-button { + background-color: var(--p-red-500) !important; + } + + #logout-menu-button .logout-icon { + margin: 8px 0 8px 10px; + font-size: 15px; + } + `, + parent: document.head, +}); diff --git a/web/js/logout.js b/web/js/logout.js new file mode 100644 index 0000000..3540274 --- /dev/null +++ b/web/js/logout.js @@ -0,0 +1,87 @@ +import { $el } from "/scripts/ui.js"; + +async function setupLogout() { + try { + await new Promise((resolve) => { + const interval = setInterval(() => { + if (document.querySelector(".side-tool-bar-end")) { + clearInterval(interval); + resolve(); + } + }, 100); + }); + + function logoutAction() { + try { + localStorage.removeItem("Comfy.userId"); + localStorage.clear(); + sessionStorage.clear(); + document.cookie.split(";").forEach((cookie) => { + const cookieName = cookie.split("=")[0].trim(); + document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`; + }); + + window.location.href = "/logout"; + } catch (error) { + console.error("Error during logout process:", error); + } + } + + $el( + "button", + { + className: + "p-button p-component p-button-icon-only p-button-text comfy-settings-btn side-bar-button p-button-secondary account-manager-logout", + type: "button", + id: "logout-button", + ariaLabel: "Logout", + dataset: { + pcName: "button", + pDisabled: false, + pcSection: "root", + pdTooltip: false, + "v-6ab4daa6": "", + "v-33cac83a": "", + }, + parent: document.querySelector(".side-tool-bar-end"), + onclick: logoutAction, + }, + [ + $el("li", { + className: "pi pi-sign-out side-bar-button-icon", + dataset: { + "v-6ab4daa6": "", + }, + }), + ] + ); + + $el( + "button", + { + textContent: "Logout", + id: "logout-menu-button", + parent: document.querySelector(".comfy-menu"), + onclick: logoutAction, + }, + [ + $el("li", { + className: "pi pi-sign-out logout-icon", + }), + ] + ); + + } catch (error) { + console.error("Error setting up Logout button:", error); + } +} + +let isSettingUp = false; + +setInterval(async () => { + if (document.getElementById("logout-button") === null && !isSettingUp) { + isSettingUp = true; + await setupLogout(); + isSettingUp = false; + } +}, 500);