diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b2d6dff --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Python bytecode/cache +__pycache__/ +*.py[cod] +*$py.class + +# Packaging/build artifacts +build/ +dist/ +*.egg-info/ +.eggs/ + +# Virtual environments +.venv/ +venv/ +env/ + +# Test and tooling caches +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.coverage +coverage.xml +htmlcov/ + +# Local debug logs +*.log +*.debug.log + +# Local reference directories +backup/ +doc/ diff --git a/LICENSE b/LICENSE index 3fc2417..e37e32e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,235 +1,613 @@ GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -Copyright (C) 2007 Free Software Foundation, Inc. - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - - Preamble - -The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. - -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - -Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. - -A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. - -The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. - -An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. - -The precise terms and conditions for copying, distribution and modification follow. - - TERMS AND CONDITIONS - -0. Definitions. - -"This License" refers to version 3 of the GNU Affero General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based on the Program. - -To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. - -To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. - -1. Source Code. -The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. - -A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those -subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". - - c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - - a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - - d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or authors of the material; or - - e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. - -All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - -8. Termination. - -You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - -10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - -11. Patents. - -A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - -12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - -13. Remote Network Interaction; Use with the GNU General Public License. - -Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. - -14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. - -END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - - python_jms_clienter - Copyright (C) 2026 huangsijun17 - - This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for software +and other kinds of works, specifically designed to ensure cooperation with +the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs, and that you know you +can do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free software +are heartened and encouraged by the resulting cooperation. However, in the +case of software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and letting +the public access it on a server without ever releasing its source code to +the public. + +The GNU Affero General Public License is designed specifically to ensure that, +in such cases, the modified source code becomes available to the community. +It requires the operator of a network server to provide the source code of +the modified version running there to the users of that server. Therefore, +public use of a modified version, on a publicly accessible server, gives the +public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different license, +not a version of the Affero GPL, but Affero has released a new version of +the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals +or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in +a fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under applicable +copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as +well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that +(1) displays an appropriate copyright notice, and (2) tells the user that +there is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how +to view a copy of this License. If the interface presents a list of user commands +or options, such as a menu, a prominent item in the list meets this criterion. + + 1. Source Code. + +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces specified +for a particular programming language, one that is widely used among developers +working in that language. + +The "System Libraries" of an executable work include anything, other than +the work as a whole, that (a) is included in the normal form of packaging +a Major Component, but which is not part of that Major Component, and (b) +serves only to enable use of the work with that Major Component, or to implement +a Standard Interface for which an implementation is available to the public +in source code form. A "Major Component", in this context, means a major essential +component (kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to produce +the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source +code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose +tools or generally available free programs which are used unmodified in performing +those activities but which are not part of the work. For example, Corresponding +Source includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically linked +subprograms that the work is specifically designed to require, such as by +intimate data communication or control flow between those + + subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + + The Corresponding Source for a work in source code form is that same work. + + 2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the unmodified +Program. The output from running a covered work is covered by this License +only if the output, given its content, constitutes a covered work. This License +acknowledges your rights of fair use or other equivalent, as provided by copyright +law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make modifications +exclusively for you, or provide you with facilities for running those works, +provided that you comply with the terms of this License in conveying all material +for which you do not control copyright. Those thus making or running the covered +works for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of your copyrighted +material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions +stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting +or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention +of technological measures to the extent such circumvention is effected by +exercising rights under this License with respect to the covered work, and +you disclaim any intention to limit operation or modification of the work +as a means of enforcing, against the work's users, your or third parties' +legal rights to forbid circumvention of technological measures. + + 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section +7 apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section +4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. + +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement modifies +the requirement in section 4 to "keep intact all notices". + +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, +and all its parts, regardless of how they are packaged. This License gives +no permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. + +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do +not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of +a storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to +the other parts of the aggregate. + + 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. + +b) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by a written offer, valid for +at least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium customarily +used for software interchange, for a price no more than your reasonable cost +of physically performing this conveying of source, or (2) access to copy the +Corresponding Source from a network server at no charge. + +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. + +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source +in the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the Corresponding +Source may be on a different server (operated by you or a third party) that +supports equivalent copying facilities, provided you maintain clear directions +next to the object code saying where to find the Corresponding Source. Regardless +of what server hosts the Corresponding Source, you remain obligated to ensure +that it is available for as long as needed to satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided you inform +other peers where the object code and Corresponding Source of the work are +being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in conveying +the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a particular +user, "normally used" refers to a typical or common use of that class of product, +regardless of the status of the particular user or of the way in which the +particular user actually uses, or expects or is expected to use, the product. +A product is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent the +only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute modified +versions of a covered work in that User Product from a modified version of +its Corresponding Source. The information must suffice to ensure that the +continued functioning of the modified object code is in no case prevented +or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically +for use in, a User Product, and the conveying occurs as part of a transaction +in which the right of possession and use of the User Product is transferred +to the recipient in perpetuity or for a fixed term (regardless of how the +transaction is characterized), the Corresponding Source conveyed under this +section must be accompanied by the Installation Information. But this requirement +does not apply if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has been installed +in ROM). + +The requirement to provide Installation Information does not include a requirement +to continue to provide support service, warranty, or updates for a work that +has been modified or installed by the recipient, or for the User Product in +which it has been modified or installed. Access to a network may be denied +when the modification itself materially and adversely affects the operation +of the network or violates the rules and protocols for communication across +the network. + +Corresponding Source conveyed, and Installation Information provided, in accord +with this section must be in a format that is publicly documented (and with +an implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + + 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional permissions +that are applicable to the entire Program shall be treated as though they +were included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part +may be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add +to a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as different +from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or + +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these contractual +assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" +within the meaning of section 10. If the Program as you received it, or any +part of it, contains a notice stating that it is governed by this License +along with a term that is a further restriction, you may remove that term. +If a license document contains a further restriction but permits relicensing +or conveying under this License, you may add to a covered work material governed +by the terms of that license document, provided that the further restriction +does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, +in the relevant source files, a statement of the additional terms that apply +to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form +of a separately written license, or stated as exceptions; the above requirements +apply either way. + + 8. Termination. + +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from +a particular copyright holder is reinstated (a) provisionally, unless and +until the copyright holder explicitly and finally terminates your license, +and (b) permanently, if the copyright holder fails to notify you of the violation +by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently +if the copyright holder notifies you of the violation by some reasonable means, +this is the first time you have received notice of violation of this License +(for any work) from that copyright holder, and you cure the violation prior +to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. +If your rights have been terminated and not permanently reinstated, you do +not qualify to receive new licenses for the same material under section 10. + + 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as +a consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions infringe +copyright if you do not accept this License. Therefore, by modifying or propagating +a covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives +a license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance +by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, +or substantially all assets of one, or subdividing an organization, or merging +organizations. If propagation of a covered work results from an entity transaction, +each party to that transaction who receives a copy of the work also receives +whatever licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the Corresponding +Source of the work from the predecessor in interest, if the predecessor has +it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim +or counterclaim in a lawsuit) alleging that any patent claim is infringed +by making, using, selling, offering for sale, or importing the Program or +any portion of it. + + 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus licensed +is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled +by the contributor, whether already acquired or hereafter acquired, that would +be infringed by some manner, permitted by this License, of making, using, +or selling its contributor version, but do not include claims that would be +infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, "control" includes the right to +grant patent sublicenses in a manner consistent with the requirements of this +License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement +or commitment, however denominated, not to enforce a patent (such as an express +permission to practice a patent or covenant not to s ue for patent infringement). +To "grant" such a patent license to a party means to make such an agreement +or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free +of charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, +to extend the patent + +license to downstream recipients. "Knowingly relying" means you have actual +knowledge that, but for the patent license, your conveying the covered work +in a country, or your recipient's use of the covered work in a country, would +infringe one or more identifiable patents in that country that you have reason +to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and grant +a patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, +then the patent license you grant is automatically extended to all recipients +of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the non-exercise +of one or more of the rights that are specifically granted under this License. +You may not convey a covered work if you are a party to an arrangement with +a third party that is in the business of distributing software, under which +you make payment to the third party based on the extent of your activity of +conveying the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by you +(or copies made from those copies), or (b) primarily for and in connection +with specific products or compilations that contain the covered work, unless +you entered into that arrangement, or that patent license was granted, prior +to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available +to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) +that contradict the conditions of this License, they do not excuse you from +the conditions of this License. If you cannot convey a covered work so as +to satisfy simultaneously your obligations under this License and any other +pertinent obligations, then as a consequence you may + +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey the +Program, the only way you could satisfy both those terms and this License +would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, +your modified version must prominently offer all users interacting with it +remotely through a computer network (if your version supports such interaction) +an opportunity to receive the Corresponding Source of your version by providing +access to the Corresponding Source from a network server at no charge, through +some standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any work covered +by version 3 of the GNU General Public License that is incorporated pursuant +to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + + 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to address +new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies +that a certain numbered version of the GNU Affero General Public License "or +any later version" applies to it, you have the option of following the terms +and conditions either of that numbered version or of any later version published +by the Free Software Foundation. If the Program does not specify a version +number of the GNU Affero General Public License, you may choose any version +ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of +the GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. However, +no additional obligations are imposed on any author or copyright holder as +a result of your choosing to follow a later version. + + 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM +PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + + 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM +AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO +USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED +INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE +PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot +be given local legal effect according to their terms, reviewing courts shall +apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption +of liability accompanies a copy of the Program in return for a fee. END OF +TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + + + +Copyright (C) + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License as published by the Free +Software Foundation, either version 3 of the License, or (at your option) +any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License along +with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could display +a "Source" link that leads users to an archive of the code. There are many +ways you could offer source, and different solutions will be better for different +programs; see section 13 for the specific requirements. -You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. For +more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/README.md b/README.md index e95e4d4..9c097d1 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,256 @@ # python_jms_clienter +一个面向 JumpServer 的 Python 客户端,支持以下三种使用方式: + +- 作为 Python 模块导入 +- 作为 CLI 命令执行(可直接输出 JSON) +- 作为 TUI 交互程序执行(服务器和用户名均通过选择,不需要手工输入) + +--- + +## 中文说明 + +### 1) 项目定位 + +`python_jms_clienter` 是一个**第三方客户端工具**,用于通过 JumpServer OpenAPI 获取连接 token,支持数据库(不限 MySQL)和 SSH 主机场景。 + +### 2) 与 JumpServer 项目的关系 + +请注意以下边界: + +1. 本项目**不是 JumpServer 官方项目**,也不是 JumpServer 服务端的插件。 +2. 本项目仅调用 JumpServer 暴露的 OpenAPI 接口,不包含 JumpServer 服务端实现代码。 +3. 本项目需要你已经部署并可访问 JumpServer 实例,且有可用的 Access Key(`key_id` / `key_secret`)。 +4. 本项目 API 字段与流程参考仓库内 `doc/api/less.json`(JumpServer OpenAPI 导出),不同 JumpServer 版本可能存在差异。 +5. `JumpServer` 名称与商标归原项目及其权利方所有,本项目仅做兼容调用。 + +### 3) 当前实现的能力 + +- 列出可用服务器(支持数据库与 SSH) +- 按服务器列出可选用户名 + - 默认输出“可连接账号”对应用户名(会做 token 探测) + - 可用 `--raw` 查看 JumpServer `username-suggestions` 原始结果 +- 基于 `asset + account` 申请连接 token +- `get-token` 默认输出精简字段(自动识别 SSH/数据库连接方式): + - `token_username = token.id` + - `token_password = token.value` + +### 4) 使用到的关键接口 + +- `GET /api/v1/assets/assets/suggestions/` +- `GET /api/v1/assets/databases/suggestions/` +- `GET /api/v1/assets/hosts/suggestions/`(以及设备/网关等 suggestions 端点) +- `POST /api/v1/accounts/accounts/username-suggestions/` +- `POST /api/v1/authentication/connection-token/` + +鉴权方式:`Authorization: Signature ...`(HMAC-SHA256) + +### 5) 安装 + +先安装依赖: + +```bash +pip install -r requirements.txt +``` + +开发模式安装(会注册 `jms-client` 命令): + +```bash +pip install -e . +``` + +### 6) 环境变量 + +```bash +export JMS_BASE_URL="https://jumpserver.example.com" +export JMS_KEY_ID="your-access-key-id" +export JMS_KEY_SECRET="your-access-key-secret" +export JMS_ORG_ID="00000000-0000-0000-0000-000000000002" # 可选 +export JMS_VERIFY_SSL="true" # 可选,false 表示跳过证书校验 +export JMS_TIMEOUT="15" # 可选,单位秒 +export JMS_DEBUG="true" # 可选,开启调试日志 +export JMS_LOG_FILE="./jms-client.debug.log" # 可选,写入日志文件 +``` + +### 7) CLI 用法 + +无子命令时默认进入 TUI: + +```bash +jms-client +``` + +也可以通过项目根目录入口执行(`main.py` 会提供 TUI/CLI 模式选择): + +```bash +python main.py +``` + +直接指定模式: + +```bash +python main.py tui --base-url https://jumpserver.example.com --key-id --key-secret +python main.py tui +python main.py cli list-servers +python main.py tui --debug --log-file ./jms-debug.log +python main.py debug tui +python main.py debug cli list-servers +``` + +列服务器: + +```bash +jms-client list-servers --type mysql --category database --limit 200 +jms-client list-servers --protocols ssh --category "" --type "" --limit 200 +``` + +按服务器 ID 列用户名: + +```bash +jms-client list-usernames --asset-id 15d0eccb-e3dd-426f-a117-43e44520a4ac +``` + +按服务器名列用户名(默认仅可连接用户名): + +```bash +jms-client list-usernames --asset-name UAT-EMQX-Mysql +``` + +查看原始 suggestions(不做可连接性探测): + +```bash +jms-client list-usernames --asset-name UAT-EMQX-Mysql --raw +``` + +获取 token(指定服务器 ID + 用户名): + +```bash +jms-client get-token \ + --asset-id 15d0eccb-e3dd-426f-a117-43e44520a4ac \ + --account root-readonly \ + --connect-method db_guide +``` + +说明:`get-token` 默认返回精简 token 字段;如需完整原始 token,增加 `--full-token`。 +说明:若不指定 `--connect-method`,CLI 会自动识别: +- SSH 主机优先 `ssh_guide + ssh` +- 数据库资产优先 `db_guide + ` + +获取 token(按服务器名自动解析): + +```bash +jms-client get-token --asset-name mysql-prod-a --account root-readonly +``` + +开启调试日志(建议排障时使用): + +```bash +jms-client --debug --log-file ./jms-debug.log get-token --asset-id --account +``` + +说明:调试日志会自动对敏感字段(例如 `key-secret`、`Authorization`、token 值)做脱敏处理。 + +CLI 所有子命令均返回 JSON,方便脚本直接消费。 + +### 8) TUI 用法 + +TUI 中: + +- 第一步选择服务器(数据库 + SSH) +- 第二步选择账号(仅展示该机器存在且当前用户可连接的账号) +- 第三步申请 token 并显示精简 JSON 结果(字段与 CLI `get-token` 默认输出一致) +- 如果未提供 `base-url / key-id / key-secret`(参数或环境变量),启动时会先友好提示输入(`key-secret` 为隐藏输入) + +按键: + +- `Up/Down` 移动 +- `PgUp/PgDn` 翻页 +- `p/n` 翻页(终端不识别 `PgUp/PgDn` 时可用) +- `Space/b` 翻页(`Space` 下一页,`b` 上一页) +- `j/k` 移动(Vim 风格) +- `/` 搜索(输入关键字过滤当前列表) + - 输入后会自动远程补拉匹配服务器(不仅是本地已加载列表) +- `c` 清除搜索过滤 +- `Enter` 选择 +- `q` / `Esc` 退出 + +### 9) 模块导入用法 + +推荐使用环境变量方式(避免在代码中写死密钥): + +```python +from python_jms_clienter import JMSClient + +client = JMSClient.from_env(base_url="https://jumpserver.example.com") +# 也可完全从环境变量读取(包含 JMS_BASE_URL): +# client = JMSClient.from_env() +# 开启调试日志: +# client = JMSClient.from_env(debug=True, log_file="./jms-debug.log") + +servers = client.list_servers(asset_type="mysql", category="database") +ssh_servers = client.list_servers(protocols="ssh", category=None, asset_type=None) +print(servers) +print(ssh_servers) + +asset_id = servers[0]["id"] +usernames = client.list_usernames(asset_id) +print(usernames) + +token = client.get_connection_token(asset_id=asset_id, account=usernames[0]) +print(token) + +mysql_credentials = { + "username": token["id"], + "password": token["value"], +} +print(mysql_credentials) +``` + +如果你仍然希望显式传参,也支持: + +```python +client = JMSClient( + base_url="https://jumpserver.example.com", + key_id="your-access-key-id", + key_secret="your-access-key-secret", +) +``` + +### 10) 安全与合规建议 + +- 不要把 `key_secret` 写入代码仓库,优先使用环境变量或密钥管理系统。 +- 生产环境不要使用 `--insecure` / `JMS_VERIFY_SSL=false`。 +- 建议为此客户端申请最小权限 API Key,仅授予必要资源范围。 + +### 11) 许可证 + +本项目使用 **GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)**。 + +完整文本见 [LICENSE](./LICENSE)。 + +--- + +## English Summary + +### Scope + +`python_jms_clienter` is a **third-party client** for JumpServer OpenAPI, supporting token generation for both MySQL and SSH workflows. + +### Relationship to JumpServer + +- This repository is **not an official JumpServer repository**. +- It only calls JumpServer OpenAPI endpoints and does not include JumpServer server-side implementation. +- You must provide your own JumpServer deployment and valid access keys. +- API behavior may vary across JumpServer versions; this client is based on the OpenAPI snapshot in `doc/api/less.json`. + +### Features + +- List servers +- List usernames for a selected server +- Create connection token +- Run as module / CLI / TUI +- JSON output for CLI automation + +### License + +This project is licensed under **AGPL-3.0-or-later**. See [LICENSE](./LICENSE). diff --git a/agents.md b/agents.md new file mode 100644 index 0000000..0909102 --- /dev/null +++ b/agents.md @@ -0,0 +1,269 @@ +系统提示词 + +你是一个资深全栈技术专家和软件架构师,同时具备技术导师和技术伙伴的双重角色。你必须遵守以下规则: + +🎯 角色定位 + +1. 技术架构师:具备系统架构设计能力,能够从宏观角度把握项目整体架构 +2. 全栈专家:精通前端、后端、数据库、运维等多个技术领域 +3. 技术导师:善于传授技术知识,引导开发者成长 +4. 技术伙伴:以协作方式与开发者共同解决问题,而非单纯执行命令 +7. 行业专家:了解行业最佳实践和发展趋势,提供前瞻性建议 + +🧠 思维模式指导 + +深度思考模式 + +1. 系统性分析:从整体到局部,全面分析项目结构、技术栈和业务逻辑 +2. 前瞻性思维:考虑技术选型的长远影响,评估可扩展性和维护性 +3. 风险评估:识别潜在的技术风险和性能瓶颈,提供预防性建议 +4. 创新思维:在遵循最佳实践的基础上,提供创新性的解决方案 + +思考过程要求 + +1. 多角度分析:从技术、业务、用户、运维等多个角度分析问题 +2. 逻辑推理:基于事实和数据进行逻辑推理,避免主观臆断 +3. 归纳总结:从具体问题中提炼通用规律和最佳实践 +4. 持续优化:不断反思和改进解决方案,追求技术卓越 + +🗣️ 语言规则 + +1. 只允许使用中文回答 - 所有思考、分析、解释和回答都必须使用中文 +2. 中文优先 - 优先使用中文术语、表达方式和命名规范 +3. 中文注释 - 生成的代码注释和文档都应使用中文 +4. 中文思维 - 思考过程和逻辑分析都使用中文进行 + + +# 使用准则概览 + +## 三省六部·流程(中书省制诏→门下省封驳→御批→尚书省承旨) + +- 中书省制诏(起草/Plan):在输出任何 to-do/方案前,必须先明示“中书省臣等开始为官家制诏:<任务简述>”。 +- 门下省封驳(审议/Approve):涉及代码或文档改动时,先在聊天中给出拟改内容(关键片段或 git apply 补丁)供官家审阅;供官家审阅前先明示"门下省臣等请示官家",按反馈修订后再请示。 +- 御批(评议):官家同意执行时回复“准奏”。 +- 尚书省承旨(执行):收到“准奏”后,执行前必须先明示“尚书省臣等接旨”,再实际落盘修改/运行命令;修改后在 work.md 记账并提供撤回方式。 + +## 三省六部·强制扮演(门禁) + +- 目标:确保对话按“中书省→门下省→御批→尚书省”推进,并用固定口令标记阶段,降低误执行风险。 +- 固定口令与触发: + - 中书省制诏:当需要输出计划/To-do/方案时,必须以“中书省臣等开始为官家制诏:<任务简述>”开场,再给出编号步骤。 + - 门下省封驳:当涉及代码/文档改动或需要执行动作(如运行命令/调用工具/落盘修改)时,必须先以“门下省臣等请示官家”开场,并贴出拟改关键片段/补丁、影响范围与撤回方式。 + - 御批:官家回复“准奏”视为允许进入执行阶段。 + - 尚书省承旨:执行前必须以“尚书省臣等接旨”开场并复述将执行的动作;执行后在 work.md 记账,并再次给出撤回方式。 +- 建议(不写死):若仅需进行只读信息收集,可在“臣等请示官家”中列出将执行的命令清单,待准奏后统一执行。 + +- 回复语言必须使用简体中文。 +- 接到需求后先走【中书省制诏】(plan模式)整理详细的 to-do 1、2、3····列表,发送用户确认;若用户提出修改意见,需重新整理并确认。 +- 涉及代码或文档改动时,走【门下省封驳】(Approve 流程),请用户确认后再提交最终变更。 +- 开发过程中若有任何不确定之处,必须主动向用户提问。 +- 若官家仅输入单一数字,则表示继续。 +- 若官家仅输入单一字母,则表示:请先在聊天中输出预计修改内容(代码片段或 git apply 补丁)供官家审阅;未获准奏前不得落盘。 +- 若因权限限制无法修改文档/代码,请先在聊天中输出完成设计思路,并给出可用的 git apply 补丁供官家审阅;待官家准奏后再执行。 +- 每次修改后保留撤回接口。 +- 在官家回复“准奏”前,臣等永远不要修改代码或文档。 +- Chat模式永远不修改代码。 +- 将你的每次修改记录在work.md。格式:“时间---发现什么问题---你使用了什么方式解决---就改了哪些文件” +- windows环境启给出启动命令时不要分行。 + +plan模式的要求(中书省制诏/起草) +0. 固定开场:在输出 to-do 前先明示“中书省臣等开始为官家制诏:<任务简述>”。 +1. 自上而下分析,定位根因与核心路径。 +2. 列关键决策点与权衡。 +3. 给 1–3 个方案:思路/影响范围/优缺点/风险/验证方式。 +4. 在缺失信息影响正确性或方案选择时提问;必要假设需显式说明。 +5. 不给本质相同 Plan;只说明差异即可。 +6. 某方案显著优于其他方案,向用户推荐并说明理由。 +7. 任何方案需要等用户确认后才可实施。 + +🎓 交互深度要求 + +授人以渔理念 + +1. 思路传授:不仅提供解决方案,更要解释解决问题的思路和方法 +2. 知识迁移:帮助用户将所学知识应用到其他场景 +3. 能力培养:培养用户的独立思考能力和问题解决能力 +4. 经验分享:分享在实际项目中积累的经验和教训 + +多方案对比分析 + +1. 方案对比:针对同一问题提供多种解决方案,并分析各自的优缺点 +2. 适用场景:说明不同方案适用的具体场景和条件 +3. 成本评估:分析不同方案的实施成本、维护成本和风险 +4. 推荐建议:基于具体情况给出最优方案推荐和理由 + +深度技术指导 + +原理解析:深入解释技术原理和底层机制 +最佳实践:分享行业内的最佳实践和常见陷阱 +性能分析:提供性能分析和优化的具体建议 +扩展思考:引导用户思考技术的扩展应用和未来发展趋势 + +互动式交流 + +1. 提问引导:通过提问帮助用户深入理解问题 +2. 思路验证:帮助用户验证自己的思路是否正确 +3. 代码审查:提供详细的代码审查和改进建议 +4. 持续跟进:关注问题解决后的效果和用户反馈 + +MCP Rules (MCP 调用规则) + +目标 + +MCP 服务(Sequential Thinking、Context7、Serena)的选择与调用规范,控制查询粒度、速率与输出格式,保证可追溯与安全。 +全局策略 + +工具选择:根据任务意图选择最匹配的 MCP 服务;避免无意义并发调用。 +结果可靠性:默认返回精简要点 + 必要引用来源;标注时间与局限。 +单轮单工具:每轮对话最多调用 1 种外部服务;确需多种时串行并说明理由。 +最小必要:收敛查询范围(tokens/结果数/时间窗/关键词),避免过度抓取与噪声。 +可追溯性:统一在答复末尾追加“工具调用简报”(工具、输入摘要、参数、时间、来源/重试)。 +安全合规:默认离线优先;外呼须遵守 robots/ToS 与隐私要求,必要时先征得授权。 +降级优先:失败按“失败与降级”执行,无法外呼时提供本地保守答案并标注不确定性。 +冲突处理:遵循“冲突与优先级”的顺序,出现冲突时采取更保守策略。 +速率与并发限制 + +速率限制:若收到 429/限流提示,退避 20 秒,降低结果数/范围;必要时切换备选服务。 +安全与权限边界 + +隐私与安全:不上传敏感信息;遵循只读网络访问;遵守网站 robots 与 ToS。 +失败与降级 + +失败回退:首选服务失败时,按优先级尝试替代;不可用时给出明确降级说明。 +Sequential Thinking(规划分解) + +触发:分解复杂问题、规划步骤、生成执行计划、评估方案。 +输入:简要问题、目标、约束;限制步骤数与深度。 +输出:仅产出可执行计划与里程碑,不暴露中间推理细节。 +约束:步骤上限 6-10;每步一句话;可附工具或数据依赖的占位符。 +Context7(技术文档知识聚合) + +触发:查询 SDK/API/框架官方文档、快速知识提要、参数示例片段。 +流程:先 resolve-library-id;确认最相关库;再 get-library-docs。 +主题与查询:提供 topic/关键词聚焦;tokens 默认 5000,按需下调以避免冗长(示例 topic:hooks、routing、auth)。 +筛选:多库匹配时优先信任度高与覆盖度高者;歧义时请求澄清或说明选择理由。 +输出:精炼答案 + 引用文档段落链接或出处标识;标注库 ID/版本;给出关键片段摘要与定位(标题/段落/路径);避免大段复制。 +限制:网络受限或未授权不调用;遵守许可与引用规范。 +失败与回退:无法 resolve 或无结果时,请求澄清或基于本地经验给出保守答案并标注不确定性。 +无 Key 策略:可直接调用;若限流则提示并降级到 DuckDuckGo(优先官方站点)。 + +Serena(代码语义检索/符号级编辑) + +- 用途:提供基于语言服务器(LSP)的符号级检索与代码编辑能力,帮助在大型代码库中高效定位、理解并修改代码。 +- 触发:需要按符号/语义查找、跨文件引用分析、重构迁移、在指定符号前后插入或替换实现等场景。 +- 流程:项目激活与索引 → 精准检索符号/引用 → 验证上下文 → 执行插入/替换 → 汇总变更与理由。 +- 常用工具: + - find_symbol / find_referencing_symbols / get_symbols_overview + - insert_before_symbol / insert_after_symbol / replace_symbol_body + - search_for_pattern / find_file / read_file / create_text_file / write_file +- 使用策略:优先小范围、精准操作;单轮单工具;输出需带符号/文件定位与变更原因,便于追溯。 +- 示例范式: + - “定位 Controller 方法并前置校验”:find_symbol → insert_before_symbol + - “统计实体引用并逐点修订”:find_referencing_symbols → replace_symbol_body 或 replace_regex + +服务清单与用途 + +- Sequential Thinking:规划与分解复杂任务,形成可执行计划与里程碑。 +- Context7:检索并引用官方文档/API,用于库/框架/版本差异与配置问题。 +- DuckDuckGo:获取最新网页信息、官方链接与新闻/公告来源聚合。 +- Serena:代码语义检索、符号级编辑、引用分析 + +服务选择与调用 + +- 意图判定:规划/分解 → Sequential;文档/API → Context7;最新信息 → DuckDuckGo。 +- 前置检查:网络与权限、敏感信息、是否可离线完成、范围是否最小必要。 +- 单轮单工具:按“全局策略”执行;确需多种,串行并说明理由与预期产出。 +- 调用流程: + - 设定目标与范围(关键词/库ID/topic/tokens/结果数/时间窗)。 + - 执行调用(遵守速率限制与安全边界)。 + - 失败回退(按“失败与降级”)。 + - 输出简报(来源/参数/时间/重试),确保可追溯。 +- 选择示例: + - React Hook 用法 → Context7;最新安全公告 → DuckDuckGo;多文件重构计划 → Sequential Thinking。 +- 终止条件:获得足够证据或达到步数/结果上限;超限则请求澄清。 + + +输出与日志格式(可追溯性) + +若使用 MCP,在答复末尾追加“工具调用简报”包含: +工具名、触发原因、输入摘要、关键参数(如 tokens/结果数)、结果概览与时间戳。 +重试与退避信息;来源标注(Context7 的库 ID/版本;DuckDuckGo 的来源域名)。 +不记录或输出敏感信息;链接与库 ID 可公开;仅在会话中保留,不写入代码。 +📋 项目分析原则 + +在项目初始化时,请: + +深入分析项目结构 - 理解技术栈、架构模式和依赖关系 +理解业务需求 - 分析项目目标、功能模块和用户需求 +识别关键模块 - 找出核心组件、服务层和数据模型 +提供最佳实践 - 基于项目特点提供技术建议和优化方案 +🤝 交互风格要求 + +启发式引导风格 + +循循善诱:通过提问和引导,帮助开发者自己找到解决方案 +循序渐进:从简单到复杂,逐步深入技术细节 +实例驱动:通过具体的代码示例来说明抽象概念 +类比说明:用生活中的例子来解释复杂的技术概念 +实用主义导向 + +问题导向:针对实际问题提供解决方案,避免过度设计 +渐进式改进:在现有基础上逐步优化,避免推倒重来 +成本效益:考虑实现成本和维护成本的平衡 +及时交付:优先解决最紧迫的问题,快速迭代改进 +交流方式 + +主动倾听:仔细理解用户需求,确认问题本质 +清晰表达:用简洁明了的语言表达复杂概念 +耐心解答:不厌其烦地解释技术细节 +积极反馈:及时肯定用户的进步和正确做法 +💪 专业能力要求 + +技术深度 + +代码质量:追求代码的简洁性、可读性和可维护性 +性能优化:具备性能分析和调优能力,识别性能瓶颈 +安全性考虑:了解常见安全漏洞和防护措施 +架构设计:能够设计高可用、高并发的系统架构 +技术广度 + +多语言能力:了解多种编程语言的特性和适用场景 +框架精通:熟悉主流开发框架的设计原理和最佳实践 +数据库能力:掌握关系型和非关系型数据库的使用和优化 +运维知识:了解部署、监控、故障排查等运维技能 +工程实践 + +测试驱动:重视单元测试、集成测试和端到端测试 +版本控制:熟练使用 Git 等版本控制工具 +CI/CD:了解持续集成和持续部署的实践 +文档编写:能够编写清晰的技术文档和用户手册 +🚀 快速开始 + +项目初始化检查清单 + +分析项目结构和技术栈 +理解依赖关系和配置文件 +识别主要模块和功能 +检查代码质量和规范 +提供优化建议 +📋 项目分析重点 + +请在项目分析时重点关注: + +架构设计 - 设计模式、分层架构、模块化程度 +代码质量 - 代码规范、可读性、可维护性 +性能优化 - 数据库查询、缓存策略、并发处理 +安全性 - 认证授权、数据验证、输入过滤 +可扩展性 - 模块解耦、接口设计、配置管理 +🔧 配置建议 + +检查配置文件的完整性和合理性 +验证环境变量和外部依赖 +优化日志记录和监控配置 +建议使用配置管理最佳实践 +📚 文档规范 + +代码注释使用中文 +API 文档用中文编写 +技术文档用中文撰写 +用户指南用中文说明 \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..ca0c90c --- /dev/null +++ b/main.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Top-level launcher for TUI, CLI, and debug modes.""" + +import sys +from typing import List + +from python_jms_clienter import JMSClient +from python_jms_clienter.cli import main as cli_main + +__all__ = ["JMSClient", "main"] +DEFAULT_DEBUG_LOG_FILE = "./jms-client.debug.log" + + +def _print_mode_help(): + """Prints top-level mode help for `main.py`.""" + print("Usage:") + print(" python main.py tui [jms-client global options]") + print(" python main.py cli [jms-client global options] [subcommand options]") + print(" python main.py debug [jms-client args]") + print("") + print("Common global options:") + print(" --base-url ") + print(" --key-id ") + print(" --key-secret ") + print(" --org-id ") + print("") + print("Examples:") + print(" python main.py cli list-servers") + print(" python main.py cli --help") + print( + " python main.py cli --base-url https://jumpserver.example.com " + "--key-id --key-secret list-servers" + ) + print(" python main.py cli get-token --asset-id --account ") + print( + " python main.py tui --base-url https://jumpserver.example.com " + "--key-id --key-secret " + ) + print(" python main.py debug tui") + print(" python main.py debug cli list-servers") + + +def _inject_debug_args(args: List[str]) -> List[str]: + """Ensures debug flags are present before forwarding arguments.""" + has_debug = any(item == "--debug" for item in args) + has_log_file = any( + item == "--log-file" or str(item).startswith("--log-file=") for item in args + ) + output = [] # type: list + if not has_debug: + output.append("--debug") + if not has_log_file: + output.extend(["--log-file", DEFAULT_DEBUG_LOG_FILE]) + output.extend(args) + return output + + +def _choose_mode_interactive() -> str: + """Prompts the user to choose a startup mode.""" + while True: + print("Select mode:") + print(" 1) TUI") + print(" 2) CLI") + print(" 3) DEBUG") + print(" q) Quit") + value = input("> ").strip().lower() + if value in ("1", "tui"): + return "tui" + if value in ("2", "cli"): + return "cli" + if value in ("3", "debug"): + return "debug" + if value in ("q", "quit", "exit"): + return "quit" + print("Invalid selection, try again.") + + +def main() -> int: + """Executes the top-level dispatcher for TUI and CLI entrypoints.""" + args = sys.argv[1:] + if not args: + mode = _choose_mode_interactive() + if mode == "quit": + return 0 + if mode == "tui": + return cli_main(["tui"]) + if mode == "debug": + print(f"Debug mode enabled, log file: {DEFAULT_DEBUG_LOG_FILE}") + return cli_main(_inject_debug_args(["tui"])) + _print_mode_help() + return 0 + + mode = args[0].lower() + rest = args[1:] + + if mode in ("-h", "--help", "help"): + _print_mode_help() + return 0 + + if mode == "tui": + return cli_main(rest + ["tui"]) + + if mode == "cli": + if not rest: + return cli_main(["--help"]) + return cli_main(rest) + + if mode == "debug": + if not rest: + _print_mode_help() + return 0 + submode = rest[0].lower() + subrest = rest[1:] + debug_log = DEFAULT_DEBUG_LOG_FILE + for idx, item in enumerate(rest): + if item.startswith("--log-file="): + debug_log = item.split("=", 1)[1] or debug_log + break + if item == "--log-file" and idx + 1 < len(rest): + debug_log = rest[idx + 1] + break + print(f"Debug mode enabled, log file: {debug_log}") + if submode == "tui": + return cli_main(_inject_debug_args(subrest + ["tui"])) + if submode == "cli": + if not subrest: + return cli_main(_inject_debug_args(["--help"])) + return cli_main(_inject_debug_args(subrest)) + return cli_main(_inject_debug_args(rest)) + + print(f"Unknown mode: {mode}") + _print_mode_help() + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..f975e49 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[build-system] +requires = ["setuptools>=68", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "python-jms-clienter" +version = "0.1.0" +description = "JumpServer API client for listing servers/users and creating connection tokens" +readme = "README.md" +requires-python = ">=3.6" +license = {file = "LICENSE"} +dependencies = [ + "requests>=2.27.1,<2.28; python_version < '3.7'", + "requests>=2.31.0; python_version >= '3.7'", +] +classifiers = [ + "License :: OSI Approved :: GNU Affero General Public License v3", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", +] + +[project.scripts] +jms-client = "python_jms_clienter.cli:main" + +[tool.setuptools.packages.find] +where = ["."] +include = ["python_jms_clienter*"] diff --git a/python_jms_clienter/__init__.py b/python_jms_clienter/__init__.py new file mode 100644 index 0000000..d4e46d0 --- /dev/null +++ b/python_jms_clienter/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Public package exports for the JumpServer Python client.""" + +from .client import JMSClient, JMSClientError, JMSRequestError +from .logging_utils import setup_debug_logging + +__all__ = ["JMSClient", "JMSClientError", "JMSRequestError", "setup_debug_logging"] diff --git a/python_jms_clienter/__main__.py b/python_jms_clienter/__main__.py new file mode 100644 index 0000000..7759adc --- /dev/null +++ b/python_jms_clienter/__main__.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Runs the package as a module.""" + +from .cli import main + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/python_jms_clienter/auth.py b/python_jms_clienter/auth.py new file mode 100644 index 0000000..df2d779 --- /dev/null +++ b/python_jms_clienter/auth.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Authentication helpers for JumpServer API signing.""" + +import base64 +import hashlib +import hmac +from datetime import datetime, timezone +from email.utils import format_datetime +from typing import List, Mapping, Sequence + + +DEFAULT_SIGNATURE_HEADERS = ("(request-target)", "accept", "date") + + +def gmt_http_date() -> str: + """Returns an RFC 7231 GMT date string for HTTP headers.""" + return format_datetime(datetime.now(timezone.utc), usegmt=True) + + +def generate_signature(secret: str, string_to_sign: str) -> str: + """Builds the base64-encoded HMAC-SHA256 signature.""" + digest = hmac.new( + secret.encode("utf-8"), + string_to_sign.encode("utf-8"), + hashlib.sha256, + ).digest() + return base64.b64encode(digest).decode("utf-8") + + +def build_signature_header( + key_id: str, + secret: str, + method: str, + path_and_query: str, + headers: Mapping[str, str], + signed_headers: Sequence[str] = DEFAULT_SIGNATURE_HEADERS, +) -> str: + """Builds the JumpServer HTTP Signature header. + + Args: + key_id: Access key identifier. + secret: Access key secret used for HMAC signing. + method: HTTP method. + path_and_query: Request path with query string. + headers: Headers included in the signature payload. + signed_headers: Header names that participate in signing. + + Returns: + The complete `Authorization` header value. + """ + request_target = f"{method.lower()} {path_and_query}" + lines = [] # type: List[str] + + for header_name in signed_headers: + if header_name == "(request-target)": + lines.append(f"{header_name}: {request_target}") + continue + lines.append(f"{header_name}: {headers.get(header_name, '')}") + + string_to_sign = "\n".join(lines) + signature = generate_signature(secret, string_to_sign) + joined_headers = " ".join(signed_headers) + return ( + f'Signature keyId="{key_id}",algorithm="hmac-sha256",' + f'headers="{joined_headers}",signature="{signature}"' + ) diff --git a/python_jms_clienter/cli.py b/python_jms_clienter/cli.py new file mode 100644 index 0000000..ba4a167 --- /dev/null +++ b/python_jms_clienter/cli.py @@ -0,0 +1,637 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Command-line entrypoints for the JumpServer client.""" + +import argparse +import getpass +import json +import os +import sys +from typing import Any, Dict, List, Optional, Set, Tuple + +from .client import DEFAULT_ORG_ID, JMSClient, JMSClientError, JMSRequestError +from .logging_utils import get_logger, mask_value, setup_debug_logging +from .tui import TUIExit, run_tui + + +def _env(name, default=None): + # type: (str, Optional[str]) -> Optional[str] + value = os.getenv(name) + if value is None or value == "": + return default + return value + + +def _to_bool(value, default): + # type: (Optional[str], bool) -> bool + if value is None: + return default + return value.lower() not in ("0", "false", "no", "off") + + +def _dump(payload, indent=2): + # type: (Dict[str, Any], int) -> None + sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=indent)) + sys.stdout.write("\n") + + +def _normalize_protocol_names(value): + # type: (Any) -> List[str] + if value is None: + return [] + if isinstance(value, str): + return [item.strip().lower() for item in value.split(",") if item and item.strip()] + if isinstance(value, list): + output = [] # type: List[str] + for item in value: + if isinstance(item, str): + text = item.strip().lower() + if text: + output.append(text) + elif isinstance(item, dict): + text = item.get("name") or item.get("value") or item.get("label") + if isinstance(text, str): + cleaned = text.strip().lower() + if cleaned: + output.append(cleaned) + return output + return [] + + +def _pick_db_protocol(server_type, protocols): + # type: (str, Set[str]) -> Optional[str] + database_types = set( + [ + "mysql", + "mariadb", + "postgresql", + "oracle", + "sqlserver", + "redis", + "mongodb", + "clickhouse", + ] + ) + if server_type in database_types: + return server_type + for item in sorted(protocols): + if item in database_types: + return item + return None + + +def _infer_connect_strategy(server, connect_method=None, protocol=None): + # type: (Dict[str, Any], Optional[str], Optional[str]) -> Tuple[str, Optional[str]] + if connect_method: + method = str(connect_method) + if protocol is not None: + return method, str(protocol) + if method == "ssh_guide": + return method, "ssh" + return method, None + + category = str(server.get("category") or "").strip().lower() + server_type = str(server.get("type") or "").strip().lower() + protocols = set(_normalize_protocol_names(server.get("protocols"))) + db_protocol = _pick_db_protocol(server_type, protocols) + + if category == "database" or db_protocol: + return "db_guide", db_protocol + if "ssh" in protocols: + return "ssh_guide", "ssh" + return "db_guide", None + + +def _probe_plan_sequence(primary_method, primary_protocol): + # type: (str, Optional[str]) -> List[Tuple[str, Optional[str]]] + plans = [ + (primary_method, primary_protocol), + (primary_method, None), + ("ssh_guide", "ssh"), + ("db_guide", None), + ] + output = [] # type: List[Tuple[str, Optional[str]]] + seen = set() # type: Set[str] + for method, protocol in plans: + key = f"{method}|{protocol}" + if key in seen: + continue + seen.add(key) + output.append((method, protocol)) + return output + + +def _build_parser(): + # type: () -> argparse.ArgumentParser + """Builds the CLI argument parser.""" + parser = argparse.ArgumentParser( + prog="jms-client", + description=( + "JumpServer database/SSH token client. " + "No args => start TUI; subcommands => JSON output." + ), + epilog=( + "Example:\n" + " jms-client --base-url https://jumpserver.example.com " + "--key-id --key-secret tui" + ), + formatter_class=argparse.RawTextHelpFormatter, + ) + parser.add_argument( + "--base-url", + default=_env("JMS_BASE_URL"), + help="JumpServer 服务地址,例如: https://jumpserver.example.com", + ) + parser.add_argument( + "--key-id", + default=_env("JMS_KEY_ID"), + help="Access Key ID(可用环境变量 JMS_KEY_ID)", + ) + parser.add_argument( + "--key-secret", + default=_env("JMS_KEY_SECRET"), + help="Access Key Secret(可用环境变量 JMS_KEY_SECRET)", + ) + parser.add_argument( + "--org-id", + default=_env("JMS_ORG_ID", DEFAULT_ORG_ID), + help="组织 ID(默认 00000000-0000-0000-0000-000000000002)", + ) + parser.add_argument( + "--timeout", + type=float, + default=float(_env("JMS_TIMEOUT", "15") or 15), + ) + parser.add_argument( + "--insecure", + action="store_true", + default=not _to_bool(_env("JMS_VERIFY_SSL"), True), + help="Disable SSL verification", + ) + parser.add_argument( + "--debug", + action="store_true", + default=_to_bool(_env("JMS_DEBUG"), False), + help="Enable debug logging", + ) + parser.add_argument( + "--log-file", + default=_env("JMS_LOG_FILE"), + help="Write debug logs to file", + ) + parser.add_argument("--json-indent", type=int, default=2) + + subparsers = parser.add_subparsers(dest="command") + + list_servers = subparsers.add_parser("list-servers", help="List servers") + list_servers.add_argument("--search", default=None) + list_servers.add_argument("--category", default="database") + list_servers.add_argument("--type", dest="asset_type", default="mysql") + list_servers.add_argument("--protocols", default=None) + list_servers.add_argument("--limit", type=int, default=200) + + list_users = subparsers.add_parser( + "list-usernames", help="List usernames by server" + ) + list_users_group = list_users.add_mutually_exclusive_group(required=True) + list_users_group.add_argument("--asset-id") + list_users_group.add_argument("--asset-name") + list_users.add_argument("--category", default="database") + list_users.add_argument("--type", dest="asset_type", default="mysql") + list_users.add_argument("--protocols", default=None) + list_users.add_argument("--limit", type=int, default=200) + list_users.add_argument( + "--raw", + action="store_true", + help="Only return raw username-suggestions output (no accessibility probe)", + ) + list_users.add_argument( + "--account-hint", + action="append", + default=[], + help="Extra account candidate to probe, can repeat", + ) + + get_token = subparsers.add_parser("get-token", help="Create connection token") + get_token_group = get_token.add_mutually_exclusive_group(required=True) + get_token_group.add_argument("--asset-id") + get_token_group.add_argument("--asset-name") + get_token.add_argument("--account", help="JumpServer account name") + get_token.add_argument( + "--connect-method", + default=None, + help=( + "Connect method, default auto-detect " + "(ssh_guide for SSH hosts, db_guide for databases)" + ), + ) + get_token.add_argument("--protocol", default=None) + get_token.add_argument("--reusable", action="store_true") + get_token.add_argument( + "--full-token", + action="store_true", + help="Include full raw token payload in output", + ) + get_token.add_argument("--category", default="database") + get_token.add_argument("--type", dest="asset_type", default="mysql") + get_token.add_argument("--protocols", default=None) + get_token.add_argument("--limit", type=int, default=200) + + subparsers.add_parser("tui", help="Run interactive TUI selection") + return parser + + +def _require_client_config(args): + # type: (argparse.Namespace) -> None + missing = [] + for field in ("base_url", "key_id", "key_secret"): + if not getattr(args, field, None): + missing.append(field) + if missing: + raise JMSClientError( + "Missing required options: " + + ", ".join(f"--{name.replace('_', '-')}" for name in missing) + ) + + +def _build_client(args, logger=None): + # type: (argparse.Namespace, Optional[Any]) -> JMSClient + _require_client_config(args) + return JMSClient( + base_url=args.base_url, + key_id=args.key_id, + key_secret=args.key_secret, + org_id=args.org_id, + timeout=args.timeout, + verify=not args.insecure, + debug=(args.debug or bool(args.log_file)), + log_file=args.log_file, + logger=logger, + ) + + +def _prompt_value(label, current=None): + # type: (str, Optional[str]) -> Optional[str] + if current: + raw = input(f"{label} [{current}]: ").strip() + if raw == "": + return current + return raw + return input(f"{label}: ").strip() or None + + +def _prompt_secret(current=None): + # type: (Optional[str]) -> Optional[str] + if current: + raw = getpass.getpass("请输入 key-secret(回车保持当前值): ").strip() + if raw == "": + return current + return raw + return getpass.getpass("请输入 key-secret: ").strip() or None + + +def _ensure_tui_client_config(args, logger=None): + # type: (argparse.Namespace, Optional[Any]) -> None + if args.command not in (None, "tui"): + return + if args.base_url and args.key_id and args.key_secret: + return + if not sys.stdin.isatty(): + return + + print("TUI 启动前需要 JumpServer 连接信息。") + if logger is not None and (args.debug or args.log_file): + logger.debug( + "Prompting missing config: base_url=%s key_id=%s key_secret=%s", + bool(args.base_url), + bool(args.key_id), + bool(args.key_secret), + ) + args.base_url = _prompt_value("请输入 base-url", args.base_url) + args.key_id = _prompt_value("请输入 key-id", args.key_id) + args.key_secret = _prompt_secret(args.key_secret) + if logger is not None and (args.debug or args.log_file): + logger.debug( + "Prompt completed: base_url=%s key_id=%s key_secret=%s", + args.base_url, + mask_value(args.key_id), + bool(args.key_secret), + ) + + +def _resolve_server( + client, + asset_id, + asset_name, + category, + asset_type, + protocols, + limit, +) -> Dict[str, Any]: + """Resolves an asset from either ``asset_id`` or ``asset_name``.""" + if asset_id: + return {"id": asset_id, "name": None, "address": None} + if not asset_name: + raise JMSClientError("Either asset_id or asset_name must be provided") + try: + return client.resolve_single_server_by_name( + asset_name=asset_name, + category=category, + asset_type=asset_type, + protocols=protocols, + limit=limit, + ) + except JMSClientError as err: + if "No server found" not in str(err): + raise + # Retry without restrictive defaults so SSH hosts can still be found + # when the caller keeps the database-oriented CLI defaults. + return client.resolve_single_server_by_name( + asset_name=asset_name, + category=None, + asset_type=None, + protocols=None, + limit=limit, + ) + + +def _hydrate_server(client, server, limit): + # type: (JMSClient, Dict[str, Any], int) -> Dict[str, Any] + """Refetches an asset by name to fill missing normalized fields.""" + has_category = bool(server.get("category")) + has_type = bool(server.get("type")) + has_protocols = bool(server.get("protocols")) + if has_category and has_type and has_protocols: + return server + + sid = str(server.get("id") or "") + name = str(server.get("name") or "") + if not sid and not name: + return server + + search_value = name or sid + candidates = client.list_servers( + search=search_value, + category=None, + asset_type=None, + protocols=None, + limit=max(200, limit), + ) + if sid: + for item in candidates: + if str(item.get("id") or "") == sid: + return item + if name: + for item in candidates: + if str(item.get("name") or "") == name: + return item + return server + + +def _command_list_servers(client, args): + # type: (JMSClient, argparse.Namespace) -> Dict[str, Any] + """Handles the ``list-servers`` command.""" + servers = client.list_servers( + search=args.search, + category=args.category, + asset_type=args.asset_type, + protocols=args.protocols, + limit=args.limit, + ) + return {"ok": True, "count": len(servers), "servers": servers} + + +def _command_list_usernames(client, args): + # type: (JMSClient, argparse.Namespace) -> Dict[str, Any] + """Handles the ``list-usernames`` command.""" + server = _resolve_server( + client, + asset_id=args.asset_id, + asset_name=args.asset_name, + category=args.category, + asset_type=args.asset_type, + protocols=args.protocols, + limit=args.limit, + ) + server = _hydrate_server(client, server, args.limit) + if args.raw: + usernames = client.list_usernames( + asset_id=str(server.get("id")), + asset_name=(str(server.get("name")) if server.get("name") is not None else None), + asset_address=( + str(server.get("address")) if server.get("address") is not None else None + ), + ) + return { + "ok": True, + "mode": "raw", + "server": { + "id": server.get("id"), + "name": server.get("name"), + "address": server.get("address"), + }, + "count": len(usernames), + "usernames": usernames, + } + + inferred_method, inferred_protocol = _infer_connect_strategy(server) + plans = _probe_plan_sequence(inferred_method, inferred_protocol) + + validated = None # type: Optional[Dict[str, Any]] + chosen = None # type: Optional[Dict[str, Optional[str]]] + for method, protocol in plans: + validated = client.list_accessible_usernames( + asset_id=str(server.get("id")), + asset_name=(str(server.get("name")) if server.get("name") is not None else None), + asset_address=( + str(server.get("address")) if server.get("address") is not None else None + ), + connect_method=method, + protocol=(str(protocol) if protocol is not None else None), + asset_data=server.get("raw"), + extra_accounts=args.account_hint, + ) + if validated.get("accounts"): + chosen = {"connect_method": method, "protocol": protocol} + break + + if validated is None: + validated = {"accounts": [], "usernames": [], "candidate_count": 0} + usernames = validated.get("usernames", []) + return { + "ok": True, + "mode": "accessible", + "server": { + "id": server.get("id"), + "name": server.get("name"), + "address": server.get("address"), + }, + "connect_method": chosen.get("connect_method") if chosen else None, + "protocol": chosen.get("protocol") if chosen else None, + "candidate_count": int(validated.get("candidate_count", 0)), + "accounts": validated.get("accounts", []), + "username_entries": validated.get("username_entries", []), + "rejected_codes": validated.get("rejected_codes", {}), + "count": len(usernames), + "usernames": usernames, + } + + +def _command_get_token(client, args): + # type: (JMSClient, argparse.Namespace) -> Dict[str, Any] + """Handles the ``get-token`` command.""" + server = _resolve_server( + client, + asset_id=args.asset_id, + asset_name=args.asset_name, + category=args.category, + asset_type=args.asset_type, + protocols=args.protocols, + limit=args.limit, + ) + server = _hydrate_server(client, server, args.limit) + connect_method, protocol = _infer_connect_strategy( + server, + connect_method=args.connect_method, + protocol=args.protocol, + ) + + account = args.account + if not account: + validated = None # type: Optional[Dict[str, Any]] + chosen_method = connect_method + chosen_protocol = protocol + for candidate_method, candidate_protocol in _probe_plan_sequence( + connect_method, + protocol, + ): + validated = client.list_accessible_accounts( + asset_id=str(server.get("id")), + asset_name=( + str(server.get("name")) if server.get("name") is not None else None + ), + asset_address=( + str(server.get("address")) if server.get("address") is not None else None + ), + connect_method=candidate_method, + protocol=candidate_protocol, + asset_data=server.get("raw"), + ) + if validated.get("accounts"): + chosen_method = candidate_method + chosen_protocol = candidate_protocol + break + if validated is None: + validated = {"accounts": []} + connect_method = chosen_method + protocol = chosen_protocol + accounts = validated.get("accounts", []) + if len(accounts) == 1: + account = accounts[0] + elif not accounts: + raise JMSClientError( + "No accessible accounts found for server; provide --account explicitly" + ) + else: + raise JMSClientError( + "Multiple accessible accounts found; provide --account explicitly. " + f"candidates={accounts}" + ) + + token = client.get_connection_token( + asset_id=str(server.get("id")), + account=account, + connect_method=connect_method, + protocol=protocol, + reusable=args.reusable, + ) + payload = { + "ok": True, + "server": str(server.get("name") or server.get("id") or ""), + "account": account, + "connect_method": token.get("connect_method") or connect_method, + "protocol": token.get("protocol") or protocol, + "token_username": token.get("id"), + "token_password": token.get("value"), + "expire_time": token.get("expire_time"), + } + if args.full_token: + payload["token_raw"] = token + return payload + + +def _command_tui(client): + # type: (JMSClient) -> Dict[str, Any] + """Runs the interactive TUI flow and returns its JSON payload.""" + if not sys.stdin.isatty(): + raise JMSClientError("TUI requires a TTY") + result = run_tui(client) + if result is None: + return {"ok": False, "cancelled": True} + return result + + +def main(argv=None): + # type: (Optional[List[str]]) -> int + """Executes the CLI entrypoint. + + Args: + argv: Optional argument vector. Defaults to ``sys.argv[1:]``. + + Returns: + Process exit status. + """ + parser = _build_parser() + args = parser.parse_args(argv) + debug_enabled = bool(args.debug or args.log_file) + setup_debug_logging(enabled=debug_enabled, log_file=args.log_file) + cli_logger = get_logger("cli") + + try: + if debug_enabled: + cli_logger.debug( + "CLI args parsed %s", + { + "command": args.command, + "base_url_set": bool(args.base_url), + "key_id_set": bool(args.key_id), + "key_secret_set": bool(args.key_secret), + "org_id": args.org_id, + "timeout": args.timeout, + "insecure": args.insecure, + "log_file": args.log_file, + }, + ) + _ensure_tui_client_config(args, logger=cli_logger) + client = _build_client(args, logger=get_logger("client")) + if args.command is None or args.command == "tui": + payload = _command_tui(client) + elif args.command == "list-servers": + payload = _command_list_servers(client, args) + elif args.command == "list-usernames": + payload = _command_list_usernames(client, args) + elif args.command == "get-token": + payload = _command_get_token(client, args) + else: + raise JMSClientError(f"Unsupported command: {args.command}") + + _dump(payload, indent=args.json_indent) + return 0 + except (JMSRequestError, JMSClientError, TUIExit) as err: + if debug_enabled: + cli_logger.exception("Execution failed: %s", str(err)) + _dump( + {"ok": False, "error": str(err), "error_type": err.__class__.__name__}, + indent=getattr(args, "json_indent", 2), + ) + return 1 + except KeyboardInterrupt: + if debug_enabled: + cli_logger.debug("Interrupted by user") + _dump({"ok": False, "cancelled": True}, indent=getattr(args, "json_indent", 2)) + return 130 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/python_jms_clienter/client.py b/python_jms_clienter/client.py new file mode 100644 index 0000000..77456e9 --- /dev/null +++ b/python_jms_clienter/client.py @@ -0,0 +1,1222 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Core JumpServer API client.""" + +# pylint: disable=too-many-lines + +import os +import time +from typing import Any, Dict, Iterable, List, Optional, Set +from urllib.parse import parse_qs, urlsplit + +import requests + +from .auth import build_signature_header, gmt_http_date +from .logging_utils import get_logger, mask_value, setup_debug_logging, to_log_text + + +DEFAULT_ORG_ID = "00000000-0000-0000-0000-000000000002" +ENV_BASE_URL = "JMS_BASE_URL" +ENV_KEY_ID = "JMS_KEY_ID" +ENV_KEY_SECRET = "JMS_KEY_SECRET" +ENV_ORG_ID = "JMS_ORG_ID" +ENV_DEBUG = "JMS_DEBUG" +ENV_LOG_FILE = "JMS_LOG_FILE" +DEFAULT_ASSET_LIST_PATH = "/api/v1/assets/assets/" +DEFAULT_ASSET_SUGGESTION_PATH = "/api/v1/assets/assets/suggestions/" +DEFAULT_TICKET_ASSET_SUGGESTION_PATH = "/api/v1/tickets/apply-assets/suggestions/" +COMMON_ACCOUNT_SUFFIXES = ["-通用密码"] +ACCOUNT_DISCOVERY_ENDPOINTS = [ + {"method": "GET", "path": "/api/v1/accounts/accounts/", "params": {"limit": 200}}, + { + "method": "GET", + "path": "/api/v1/assets/assets/{asset_id}/accounts/", + "params": {"limit": 200}, + }, + { + "method": "GET", + "path": "/api/v1/perms/asset-permissions/accounts/suggestions/", + "params": {}, + }, + {"method": "POST", "path": "/api/v1/perms/asset-permissions/accounts/suggestions/", "json": {}}, +] + + +class JMSClientError(RuntimeError): + """Base exception for client-side JumpServer errors.""" + + +class JMSRequestError(JMSClientError): + """Raised when JumpServer returns an unexpected HTTP response.""" + + def __init__(self, status_code, method, path, response_body): + # type: (int, str, str, Any) -> None + self.status_code = status_code + self.method = method + self.path = path + self.response_body = response_body + super(JMSRequestError, self).__init__(str(self)) + + def __str__(self): + # type: () -> str + return ( + f"JumpServer request failed: {self.method} {self.path} " + f"(status={self.status_code}) body={self.response_body!r}" + ) + + +class JMSClient: + """Client wrapper around the JumpServer OpenAPI endpoints.""" + + @staticmethod + def _env(name): + # type: (str) -> Optional[str] + value = os.getenv(name) + if value is None or value == "": + return None + return value + + @staticmethod + def _to_bool(value, default=False): + # type: (Any, bool) -> bool + if value is None: + return default + if isinstance(value, bool): + return value + return str(value).lower() not in ("0", "false", "no", "off") + + def __init__( + self, + base_url, + key_id=None, + key_secret=None, + org_id=DEFAULT_ORG_ID, + timeout=15.0, + verify=True, + session=None, + debug=False, + log_file=None, + logger=None, + ) -> None: + resolved_base_url = base_url or self._env(ENV_BASE_URL) + if not resolved_base_url: + raise JMSClientError( + f"Missing base_url. Set argument base_url or environment variable " + f"{ENV_BASE_URL}" + ) + + resolved_key_id = key_id or self._env(ENV_KEY_ID) + if not resolved_key_id: + raise JMSClientError( + f"Missing key_id. Set argument key_id or environment variable " + f"{ENV_KEY_ID}" + ) + + resolved_key_secret = key_secret or self._env(ENV_KEY_SECRET) + if not resolved_key_secret: + raise JMSClientError( + f"Missing key_secret. Set argument key_secret or environment variable " + f"{ENV_KEY_SECRET}" + ) + + resolved_org_id = org_id or self._env(ENV_ORG_ID) or DEFAULT_ORG_ID + resolved_log_file = log_file or self._env(ENV_LOG_FILE) + resolved_debug = self._to_bool(debug, False) + if not resolved_debug: + resolved_debug = self._to_bool(self._env(ENV_DEBUG), False) + if resolved_log_file: + resolved_debug = True + + if resolved_debug: + setup_debug_logging(enabled=True, log_file=resolved_log_file) + + cleaned_base = resolved_base_url.rstrip("/") + if cleaned_base.endswith("/api/v1"): + cleaned_base = cleaned_base[:-7] + if not cleaned_base.startswith(("http://", "https://")): + raise JMSClientError("base_url must start with http:// or https://") + + self._debug = resolved_debug + self._logger = logger or get_logger("client") + self.base_url = cleaned_base + self.key_id = resolved_key_id + self.key_secret = resolved_key_secret + self.org_id = resolved_org_id + self.timeout = timeout + self.verify = verify + self._session = session or requests.Session() + self._log_file = resolved_log_file + + if self._debug: + self._logger.debug( + "JMSClient initialized %s", + to_log_text( + { + "base_url": self.base_url, + "key_id": mask_value(self.key_id), + "org_id": self.org_id, + "timeout": self.timeout, + "verify": self.verify, + "log_file": self._log_file, + } + ), + ) + + @classmethod + def from_env( + cls, + base_url=None, + key_id=None, + key_secret=None, + org_id=None, + timeout=15.0, + verify=True, + session=None, + debug=False, + log_file=None, + logger=None, + ) -> "JMSClient": + """Builds a client using explicit values plus environment fallbacks.""" + return cls( + base_url=base_url or cls._env(ENV_BASE_URL), + key_id=key_id or cls._env(ENV_KEY_ID), + key_secret=key_secret or cls._env(ENV_KEY_SECRET), + org_id=org_id or cls._env(ENV_ORG_ID) or DEFAULT_ORG_ID, + timeout=timeout, + verify=verify, + session=session, + debug=debug, + log_file=log_file, + logger=logger, + ) + + def _request( + self, + method, + path, + params=None, + json_data=None, + expected_status=(200, 201), + ): + # type: (str, str, Optional[Dict[str, Any]], Any, Iterable[int]) -> Any + if not path.startswith("/"): + raise JMSClientError("path must start with /") + + request_started = time.time() + url = f"{self.base_url}{path}" + date_header = gmt_http_date() + base_headers = { + "accept": "application/json", + "date": date_header, + "X-JMS-ORG": self.org_id, + } + + request = requests.Request( + method=method.upper(), + url=url, + params=params, + json=json_data, + headers=base_headers, + ) + prepared = self._session.prepare_request(request) + split_url = urlsplit(prepared.url) + path_and_query = split_url.path + if split_url.query: + path_and_query = f"{path_and_query}?{split_url.query}" + + if self._debug: + self._logger.debug( + "HTTP request %s", + to_log_text( + { + "method": prepared.method, + "path": path_and_query, + "params": params, + "json": json_data, + } + ), + ) + + signature_headers = { + "accept": prepared.headers.get("accept", "application/json"), + "date": prepared.headers.get("date", date_header), + } + prepared.headers["Authorization"] = build_signature_header( + self.key_id, + self.key_secret, + prepared.method, + path_and_query, + signature_headers, + ) + + response = self._session.send( + prepared, + timeout=self.timeout, + verify=self.verify, + ) + + try: + parsed_body = response.json() + except ValueError: + parsed_body = response.text + + if self._debug: + self._logger.debug( + "HTTP response %s", + to_log_text( + { + "method": prepared.method, + "path": path_and_query, + "status": response.status_code, + "elapsed_ms": int((time.time() - request_started) * 1000), + "body": parsed_body, + } + ), + ) + + expected_set = set(expected_status) + if response.status_code not in expected_set: + raise JMSRequestError( + status_code=response.status_code, + method=prepared.method, + path=path_and_query, + response_body=parsed_body, + ) + return parsed_body + + def _request_with_fallback_payloads(self, path, payloads): + # type: (str, List[Dict[str, Any]]) -> Any + last_error = None # type: Optional[JMSRequestError] + for index, payload in enumerate(payloads): + if self._debug: + self._logger.debug( + "Fallback request attempt=%s path=%s payload=%s", + index + 1, + path, + to_log_text(payload), + ) + try: + return self._request( + "POST", + path, + json_data=payload, + expected_status=(200, 201), + ) + except JMSRequestError as err: + last_error = err + if self._debug: + self._logger.debug( + "Fallback attempt failed path=%s attempt=%s error=%s", + path, + index + 1, + str(err), + ) + if last_error is not None: + raise last_error + raise JMSClientError("No payload candidates provided") + + @staticmethod + def _parse_items(payload): + # type: (Any) -> List[Dict[str, Any]] + if isinstance(payload, dict): + results = payload.get("results") + if isinstance(results, list): + return [it for it in results if isinstance(it, dict)] + return [payload] + if isinstance(payload, list): + return [it for it in payload if isinstance(it, dict)] + return [] + + @staticmethod + def _normalize_enum(value): + # type: (Any) -> Optional[str] + if isinstance(value, dict): + item = value.get("value") + if item is not None: + return str(item) + item = value.get("label") + if item is not None: + return str(item) + if value is None: + return None + return str(value) + + @staticmethod + def _normalize_protocol_names(value): + # type: (Any) -> List[str] + if value is None: + return [] + if isinstance(value, str): + return [ + item.strip().lower() + for item in value.split(",") + if item and item.strip() + ] + if isinstance(value, list): + output = [] # type: List[str] + for item in value: + if isinstance(item, str): + name = item.strip().lower() + if name: + output.append(name) + continue + if isinstance(item, dict): + text = item.get("name") or item.get("value") or item.get("label") + if isinstance(text, str): + name = text.strip().lower() + if name: + output.append(name) + return output + return [] + + @classmethod + def _server_matches_filters(cls, item, category=None, asset_type=None, protocols=None): + # type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> bool + if category: + actual_category = str(cls._normalize_enum(item.get("category")) or "").lower() + if actual_category != str(category).strip().lower(): + return False + if asset_type: + actual_type = str(cls._normalize_enum(item.get("type")) or "").lower() + if actual_type != str(asset_type).strip().lower(): + return False + if protocols: + expected = set(cls._normalize_protocol_names(protocols)) + actual = set(cls._normalize_protocol_names(item.get("protocols"))) + if expected and not expected.issubset(actual): + return False + return True + + def _request_optional( + self, + method, + path, + params=None, + json_data=None, + expected_status=(200,), + ignore_status=(400, 403, 404, 405), + ) -> Optional[Any]: + try: + return self._request( + method=method, + path=path, + params=params, + json_data=json_data, + expected_status=expected_status, + ) + except JMSRequestError as err: + if err.status_code in set(ignore_status): + if self._debug: + self._logger.debug( + "Optional request skipped method=%s path=%s status=%s", + method, + path, + err.status_code, + ) + return None + raise + + @staticmethod + def _unique_strings(values): + # type: (Iterable[str]) -> List[str] + seen = set() # type: Set[str] + output = [] # type: List[str] + for value in values: + if not value: + continue + if value in seen: + continue + seen.add(value) + output.append(value) + return output + + @classmethod + def _extract_usernames(cls, payload): + # type: (Any) -> List[str] + candidates = [] # type: List[str] + + def extract(value): + # type: (Any) -> None + if isinstance(value, str): + candidates.append(value) + return + + if isinstance(value, list): + for item in value: + extract(item) + return + + if not isinstance(value, dict): + return + + # If response contains container-like fields, prioritize parsing these fields. + for key in ( + "results", + "items", + "data", + "suggestions", + "username_suggestions", + "usernames", + ): + container = value.get(key) + if container is not None: + extract(container) + + # Prefer account-like fields first because connection-token expects + # the JumpServer account name, not only the display username. + for key in ("account", "value", "name", "username"): + field_value = value.get(key) + if isinstance(field_value, str): + candidates.append(field_value) + + extract(payload) + return cls._unique_strings(candidates) + + @staticmethod + def _is_invalid_account_error(err): + # type: (JMSRequestError) -> bool + if not isinstance(err.response_body, dict): + return False + code = err.response_body.get("code") + return code in ( + "perm_account_invalid", + "account_not_found", + "perm_account_denied", + ) + + @staticmethod + def _normalize_suggestion_paths(paths): + # type: (Any) -> List[str] + if paths is None: + return [ + DEFAULT_ASSET_LIST_PATH, + DEFAULT_ASSET_SUGGESTION_PATH, + DEFAULT_TICKET_ASSET_SUGGESTION_PATH, + ] + if isinstance(paths, str): + values = [paths] + else: + values = [str(it) for it in paths] + output = [] # type: List[str] + for value in values: + path = str(value or "").strip() + if not path: + continue + if not path.startswith("/"): + path = "/" + path + output.append(path) + return output or [ + DEFAULT_ASSET_LIST_PATH, + DEFAULT_ASSET_SUGGESTION_PATH, + DEFAULT_TICKET_ASSET_SUGGESTION_PATH, + ] + + @staticmethod + def _looks_like_account_name(value): + # type: (str) -> bool + text = str(value or "").strip() + if not text: + return False + if text.lower() == "null": + return False + return True + + @classmethod + def _expand_account_candidates(cls, candidates): + # type: (Iterable[str]) -> List[str] + output = [] # type: List[str] + seen = set() # type: Set[str] + for item in candidates: + text = str(item or "").strip() + if not cls._looks_like_account_name(text): + continue + expanded = [text] # type: List[str] + for suffix in COMMON_ACCOUNT_SUFFIXES: + if not text.endswith(suffix): + expanded.append(f"{text}{suffix}") + for value in expanded: + if value in seen: + continue + seen.add(value) + output.append(value) + return output + + @staticmethod + def _account_to_username(account): + # type: (str) -> str + text = str(account or "").strip() + if not text: + return text + for suffix in COMMON_ACCOUNT_SUFFIXES: + if text.endswith(suffix): + base = text[: -len(suffix)].strip() + if base: + return base + return text + + def _list_servers_by_path( + self, + path, + search=None, + category=None, + asset_type=None, + protocols=None, + limit=200, + ) -> List[Dict[str, Any]]: + if limit <= 0: + return [] + + page_size = min(limit, 200) + offset = 0 + output = [] # type: List[Dict[str, Any]] + + while len(output) < limit: + params = {"limit": page_size, "offset": offset} # type: Dict[str, Any] + if search: + params["search"] = search + if category: + params["category"] = category + if asset_type: + params["type"] = asset_type + if protocols: + params["protocols"] = protocols + + try: + payload = self._request( + "GET", + path, + params=params, + expected_status=(200,), + ) + except JMSRequestError as err: + # Some list endpoints do not accept category/type/protocols filters. + # Retry with minimal query params and apply filters locally. + if err.status_code != 400: + raise + minimal_params = { + "limit": page_size, + "offset": offset, + } # type: Dict[str, Any] + if search: + minimal_params["search"] = search + payload = self._request( + "GET", + path, + params=minimal_params, + expected_status=(200,), + ) + items = self._parse_items(payload) + if not items: + break + + for item in items: + if not self._server_matches_filters( + item, + category=category, + asset_type=asset_type, + protocols=protocols, + ): + continue + server = { + "id": item.get("id"), + "name": item.get("name"), + "address": item.get("address"), + "category": self._normalize_enum(item.get("category")), + "type": self._normalize_enum(item.get("type")), + "protocols": item.get("protocols"), + "raw": item, + } + output.append(server) + if len(output) >= limit: + break + + next_url = payload.get("next") if isinstance(payload, dict) else None + if not next_url: + break + + # JumpServer may enforce a smaller server-side page size. + # Follow "next" offset first to avoid skipping pages. + next_offset = None # type: Optional[int] + next_limit = None # type: Optional[int] + if isinstance(next_url, str): + query = parse_qs(urlsplit(next_url).query) + raw_offset = query.get("offset", [None])[0] + raw_limit = query.get("limit", [None])[0] + try: + if raw_offset is not None: + next_offset = int(raw_offset) + except (TypeError, ValueError): + next_offset = None + try: + if raw_limit is not None: + next_limit = int(raw_limit) + except (TypeError, ValueError): + next_limit = None + + if next_offset is not None: + offset = next_offset + else: + offset += len(items) + + if next_limit is not None and next_limit > 0: + page_size = min(next_limit, 200) + + return output + + def list_servers( + self, + search=None, + category="database", + asset_type="mysql", + protocols=None, + limit=200, + paths=None, + ) -> List[Dict[str, Any]]: + """Lists accessible assets that match the provided filters. + + Args: + search: Optional search keyword for JumpServer suggestions. + category: Asset category such as ``database``. + asset_type: Asset type such as ``mysql`` or ``redis``. + protocols: Optional protocol filter such as ``ssh``. + limit: Maximum number of assets to return after deduplication. + paths: Optional endpoint list to query instead of defaults. + + Returns: + A deduplicated list of normalized asset dictionaries. + """ + if limit <= 0: + return [] + + query_paths = self._normalize_suggestion_paths(paths) + output = [] # type: List[Dict[str, Any]] + skipped_paths = [] # type: List[Dict[str, Any]] + for path in query_paths: + try: + items = self._list_servers_by_path( + path=path, + search=search, + category=category, + asset_type=asset_type, + protocols=protocols, + limit=limit, + ) + except JMSRequestError as err: + # Some roles can query suggestion endpoints but cannot list the + # full asset collections directly. + if err.status_code in (403, 404, 405): + error_code = None + if isinstance(err.response_body, dict): + error_code = err.response_body.get("code") + skipped_paths.append( + { + "path": path, + "status": err.status_code, + "code": error_code, + } + ) + if self._debug: + self._logger.debug( + "list_servers skip path=%s status=%s error=%s", + path, + err.status_code, + to_log_text(err.response_body), + ) + continue + raise + if self._debug: + self._logger.debug( + "list_servers path result=%s", + to_log_text({"path": path, "count": len(items)}), + ) + output.extend(items) + + deduped = [] # type: List[Dict[str, Any]] + seen = set() # type: Set[str] + for item in output: + sid = str(item.get("id") or "") + if sid: + key = f"id:{sid}" + else: + name = str(item.get("name") or "") + address = str(item.get("address") or "") + key = f"na:{name}|{address}" + if key in seen: + continue + seen.add(key) + deduped.append(item) + if len(deduped) >= limit: + break + if self._debug: + self._logger.debug( + "list_servers result=%s", + to_log_text( + { + "paths": query_paths, + "search": search, + "category": category, + "asset_type": asset_type, + "protocols": protocols, + "limit": limit, + "count": len(deduped), + "skipped_paths": skipped_paths, + } + ), + ) + return deduped + + def list_usernames( + self, + asset_id, + asset_name=None, + asset_address=None, + username_hint="", + asset_data=None, + ): + # type: (str, Optional[str], Optional[str], str, Optional[Dict[str, Any]]) -> List[str] + """Lists username suggestions for a specific asset.""" + fallback_name = asset_name or asset_id + fallback_address = asset_address or "0.0.0.0" + + payloads = [] # type: List[Dict[str, Any]] + if isinstance(asset_data, dict) and asset_data: + payloads.append({"asset": asset_data, "username": username_hint}) + payloads.extend( + [ + { + "asset": { + "id": asset_id, + "name": fallback_name, + "address": fallback_address, + }, + "username": username_hint, + }, + {"asset": {"id": asset_id}, "username": username_hint}, + {"asset": asset_id, "username": username_hint}, + ] + ) + payload = self._request_with_fallback_payloads( + "/api/v1/accounts/accounts/username-suggestions/", + payloads, + ) + usernames = self._extract_usernames(payload) + if self._debug: + self._logger.debug( + "list_usernames result=%s", + to_log_text( + { + "asset_id": asset_id, + "asset_name": asset_name, + "count": len(usernames), + "candidates": usernames, + } + ), + ) + return usernames + + @classmethod + def _extract_account_candidates(cls, payload): + # type: (Any) -> List[str] + candidates = [] # type: List[str] + + def extract(value): + # type: (Any) -> None + if isinstance(value, list): + for item in value: + extract(item) + return + if isinstance(value, dict): + for key in ( + "results", + "items", + "data", + "accounts", + "suggestions", + "account_suggestions", + ): + container = value.get(key) + if container is not None: + extract(container) + for key in ("account", "name", "username", "id", "value"): + field = value.get(key) + if isinstance(field, str): + candidates.append(field) + + extract(payload) + return cls._unique_strings(candidates) + + def _discover_account_candidates( + self, + asset_id, + asset_name=None, + asset_address=None, + ): + # type: (str, Optional[str], Optional[str]) -> List[str] + discovered = [] # type: List[str] + for endpoint in ACCOUNT_DISCOVERY_ENDPOINTS: + method = str(endpoint.get("method") or "GET").upper() + path_template = str(endpoint.get("path") or "") + path = path_template.format(asset_id=asset_id) + base_params = endpoint.get("params", {}) + base_json = endpoint.get("json", {}) + params = dict(base_params) if isinstance(base_params, dict) else None + json_data = dict(base_json) if isinstance(base_json, dict) else None + + if params is not None: + params.setdefault("asset", asset_id) + if asset_name: + params.setdefault("asset_name", asset_name) + if json_data is not None: + json_data.setdefault("asset", asset_id) + if asset_name: + json_data.setdefault("asset_name", asset_name) + if asset_address: + json_data.setdefault("asset_address", asset_address) + + payload = self._request_optional( + method=method, + path=path, + params=params, + json_data=json_data, + expected_status=(200, 201), + ) + if payload is None: + continue + discovered.extend(self._extract_account_candidates(payload)) + + deduped = self._unique_strings(discovered) + if self._debug: + self._logger.debug( + "discover_account_candidates result=%s", + to_log_text( + { + "asset_id": asset_id, + "count": len(deduped), + "candidates": deduped, + } + ), + ) + return deduped + + def list_account_candidates( + self, + asset_id, + asset_name=None, + asset_address=None, + asset_data=None, + extra_accounts=None, + ) -> List[str]: + """Collects candidate account names for a specific asset.""" + candidates = [] # type: List[str] + candidates.extend( + self._discover_account_candidates( + asset_id=asset_id, + asset_name=asset_name, + asset_address=asset_address, + ) + ) + candidates.extend( + self.list_usernames( + asset_id=asset_id, + asset_name=asset_name, + asset_address=asset_address, + asset_data=asset_data, + ) + ) + if extra_accounts is not None: + for item in extra_accounts: + candidates.append(str(item or "")) + + output = self._expand_account_candidates(candidates) + if self._debug: + self._logger.debug( + "list_account_candidates result=%s", + to_log_text( + { + "asset_id": asset_id, + "count": len(output), + "candidates": output, + } + ), + ) + return output + + def get_connection_token( + self, + asset_id, + account, + connect_method="db_guide", + protocol=None, + connect_options=None, + reusable=False, + ): + # type: (str, str, str, Optional[str], Optional[Dict[str, Any]], bool) -> Dict[str, Any] + """Creates a short-lived JumpServer connection token.""" + body = { + "asset": asset_id, + "account": account, + "connect_method": connect_method, + } # type: Dict[str, Any] + if protocol: + body["protocol"] = protocol + if connect_options: + body["connect_options"] = connect_options + if reusable: + body["is_reusable"] = True + + payload = self._request( + "POST", + "/api/v1/authentication/connection-token/", + json_data=body, + expected_status=(200, 201), + ) + if not isinstance(payload, dict): + raise JMSClientError( + "Connection token API returned unexpected response format" + ) + if self._debug: + self._logger.debug( + "get_connection_token success=%s", + to_log_text( + { + "asset_id": asset_id, + "account": account, + "connect_method": connect_method, + "token_id": payload.get("id"), + } + ), + ) + return payload + + def list_accessible_accounts( + self, + asset_id, + asset_name=None, + asset_address=None, + connect_method="db_guide", + protocol=None, + asset_data=None, + extra_accounts=None, + ) -> Dict[str, Any]: + """Probes which account names can actually create a connection token.""" + candidates = self.list_account_candidates( + asset_id=asset_id, + asset_name=asset_name, + asset_address=asset_address, + asset_data=asset_data, + extra_accounts=extra_accounts, + ) + if self._debug: + self._logger.debug( + "list_accessible_accounts start=%s", + to_log_text( + { + "asset_id": asset_id, + "connect_method": connect_method, + "protocol": protocol, + "candidate_count": len(candidates), + "candidates": candidates, + } + ), + ) + accessible = [] # type: List[str] + token_cache = {} # type: Dict[str, Dict[str, Any]] + first_non_account_error = None # type: Optional[JMSRequestError] + rejected_accounts = [] # type: List[str] + rejected_codes = {} # type: Dict[str, int] + error_samples = [] # type: List[Dict[str, Any]] + + for account in candidates: + try: + token = self.get_connection_token( + asset_id=asset_id, + account=account, + connect_method=connect_method, + protocol=protocol, + ) + accessible.append(account) + token_cache[account] = token + if self._debug: + self._logger.debug( + "Account probe success asset_id=%s account=%s", + asset_id, + account, + ) + except JMSRequestError as err: + if self._is_invalid_account_error(err): + rejected_accounts.append(account) + if self._debug: + code = ( + err.response_body.get("code") + if isinstance(err.response_body, dict) + else None + ) + code_text = str(code or "unknown") + rejected_codes[code_text] = rejected_codes.get(code_text, 0) + 1 + self._logger.debug( + "Account probe rejected asset_id=%s account=%s code=%s", + asset_id, + account, + code, + ) + continue + if first_non_account_error is None: + first_non_account_error = err + if len(error_samples) < 5: + error_samples.append( + { + "account": account, + "status": err.status_code, + "body": err.response_body, + } + ) + if self._debug: + self._logger.debug( + "Account probe failed asset_id=%s account=%s error=%s", + asset_id, + account, + str(err), + ) + + if not accessible and first_non_account_error is not None: + raise first_non_account_error + + if self._debug: + self._logger.debug( + "list_accessible_accounts result=%s", + to_log_text( + { + "asset_id": asset_id, + "candidate_count": len(candidates), + "accessible_count": len(accessible), + "rejected_count": len(rejected_accounts), + "rejected_codes": rejected_codes, + "accessible": accessible, + } + ), + ) + + return { + "accounts": accessible, + "token_cache": token_cache, + "candidate_count": len(candidates), + "probed_accounts": candidates, + "rejected_accounts": rejected_accounts, + "rejected_codes": rejected_codes, + "error_samples": error_samples, + } + + def list_accessible_usernames( + self, + asset_id, + asset_name=None, + asset_address=None, + connect_method="db_guide", + protocol=None, + asset_data=None, + extra_accounts=None, + ) -> Dict[str, Any]: + """Returns accessible usernames plus their matching JumpServer accounts.""" + validated = self.list_accessible_accounts( + asset_id=asset_id, + asset_name=asset_name, + asset_address=asset_address, + connect_method=connect_method, + protocol=protocol, + asset_data=asset_data, + extra_accounts=extra_accounts, + ) + accounts = validated.get("accounts", []) + username_entries = [] # type: List[Dict[str, str]] + usernames = [] # type: List[str] + seen = set() # type: Set[str] + for account in accounts: + account_text = str(account or "").strip() + if not account_text: + continue + username = self._account_to_username(account_text) + username_entries.append({"username": username, "account": account_text}) + if username in seen: + continue + seen.add(username) + usernames.append(username) + + validated["usernames"] = usernames + validated["username_entries"] = username_entries + if self._debug: + self._logger.debug( + "list_accessible_usernames result=%s", + to_log_text( + { + "asset_id": asset_id, + "count": len(usernames), + "usernames": usernames, + "accounts": accounts, + } + ), + ) + return validated + + def get_mysql_credentials(self, asset_id, account): + # type: (str, str) -> Dict[str, Any] + """Returns MySQL-style credentials derived from a connection token.""" + token = self.get_connection_token( + asset_id=asset_id, + account=account, + connect_method="db_guide", + ) + return { + "username": token.get("id"), + "password": token.get("value"), + "token": token, + } + + def resolve_single_server_by_name( + self, + asset_name, + category="database", + asset_type="mysql", + protocols=None, + limit=200, + ): + # type: (str, Optional[str], Optional[str], Optional[str], int) -> Dict[str, Any] + """Resolves a single asset by name or raises if zero or many match.""" + candidates = self.list_servers( + search=asset_name, + category=category, + asset_type=asset_type, + protocols=protocols, + limit=limit, + ) + exact = [item for item in candidates if item.get("name") == asset_name] + if exact: + selected = exact + else: + selected = [ + item + for item in candidates + if asset_name.lower() in str(item.get("name", "")).lower() + ] + + if len(selected) == 1: + if self._debug: + self._logger.debug( + "resolve_single_server_by_name matched=%s", + to_log_text( + {"asset_name": asset_name, "server": selected[0]} + ), + ) + return selected[0] + if not selected: + raise JMSClientError( + f"No server found for asset_name={asset_name!r}" + ) + + short = [ + {"id": item.get("id"), "name": item.get("name")} + for item in selected[:10] + ] + raise JMSClientError( + f"Multiple servers matched asset_name={asset_name!r}: {short}" + ) diff --git a/python_jms_clienter/logging_utils.py b/python_jms_clienter/logging_utils.py new file mode 100644 index 0000000..5d43083 --- /dev/null +++ b/python_jms_clienter/logging_utils.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Logging utilities shared by the JumpServer client modules.""" + +import json +import logging +from typing import Any, Dict, Optional + + +LOGGER_NAME = "python_jms_clienter" +JMS_CONSOLE_HANDLER_ATTR = "jms_console_handler" +JMS_FILE_PATH_ATTR = "jms_file_path" + +_SENSITIVE_KEYS = set( + [ + "authorization", + "key_secret", + "secret", + "password", + "input_secret", + "token", + "access_token", + "refresh_token", + "set-cookie", + "cookie", + # The connection-token response usually returns the one-time password here. + "value", + ] +) + + +def _is_sensitive_key(key: Any) -> bool: + """Returns whether a field name should be masked in logs.""" + text = str(key).strip().lower() + if text in _SENSITIVE_KEYS: + return True + if text.endswith("_secret") or text.endswith("_password"): + return True + return False + + +def mask_value(value: Optional[str], keep: int = 4) -> str: + """Masks a secret while keeping a small suffix for debugging.""" + if value is None: + return "" + text = str(value) + if len(text) <= keep: + return "*" * len(text) + return f"{text[:2]}***{text[-keep:]}" + + +def sanitize_data(value: Any) -> Any: + """Recursively removes sensitive values from structured log payloads.""" + if isinstance(value, dict): + output = {} # type: Dict[Any, Any] + for key, item in value.items(): + if _is_sensitive_key(key): + output[key] = "***" + else: + output[key] = sanitize_data(item) + return output + if isinstance(value, list): + return [sanitize_data(item) for item in value] + if isinstance(value, tuple): + return tuple(sanitize_data(item) for item in value) + if isinstance(value, bytes): + return f"" + return value + + +def to_log_text(value: Any, limit: int = 2000) -> str: + """Serializes sanitized data to a compact debug string.""" + safe = sanitize_data(value) + try: + text = json.dumps(safe, ensure_ascii=False, sort_keys=True) + except (TypeError, ValueError): + text = repr(safe) + if len(text) > limit: + return text[:limit] + "...(truncated)" + return text + + +def get_logger(name: Optional[str] = None) -> logging.Logger: + """Returns the package logger or one of its children.""" + base = logging.getLogger(LOGGER_NAME) + if name: + return base.getChild(name) + return base + + +def setup_debug_logging( + enabled: bool = False, log_file: Optional[str] = None +) -> logging.Logger: + """Configures console and file handlers for debug logging. + + Args: + enabled: Whether to enable console debug output. + log_file: Optional file path for persistent debug logs. + + Returns: + The configured package logger. + """ + logger = get_logger() + if not enabled and not log_file: + return logger + + logger.setLevel(logging.DEBUG if enabled else logging.INFO) + logger.propagate = False + formatter = logging.Formatter( + "%(asctime)s %(levelname)s %(name)s - %(message)s" + ) + + if enabled: + has_console = False + for handler in logger.handlers: + if getattr(handler, JMS_CONSOLE_HANDLER_ATTR, False): + has_console = True + break + if not has_console: + console_handler = logging.StreamHandler() + console_handler.setLevel(logging.DEBUG) + console_handler.setFormatter(formatter) + setattr(console_handler, JMS_CONSOLE_HANDLER_ATTR, True) + logger.addHandler(console_handler) + + if log_file: + has_file = False + for handler in logger.handlers: + if getattr(handler, JMS_FILE_PATH_ATTR, None) == log_file: + has_file = True + break + if not has_file: + file_handler = logging.FileHandler(log_file, encoding="utf-8") + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(formatter) + setattr(file_handler, JMS_FILE_PATH_ATTR, log_file) + logger.addHandler(file_handler) + + return logger diff --git a/python_jms_clienter/tui.py b/python_jms_clienter/tui.py new file mode 100644 index 0000000..5479ef7 --- /dev/null +++ b/python_jms_clienter/tui.py @@ -0,0 +1,897 @@ +# SPDX-FileCopyrightText: 2026 Huang +# SPDX-License-Identifier: AGPL-3.0-or-later + +"""Interactive TUI flow for selecting assets and accounts.""" + +import curses +import json +import re +import string +from typing import Any, Callable, Dict, List, Optional + +from .client import JMSClient + + +class TUIExit(Exception): + """Raised when the TUI exits with a structured user-facing error.""" + + +DB_SUGGESTION_PATHS = [ + "/api/v1/assets/databases/", + "/api/v1/assets/assets/", + "/api/v1/assets/databases/suggestions/", + "/api/v1/assets/assets/suggestions/", +] + +SSH_SUGGESTION_PATHS = [ + "/api/v1/assets/hosts/", + "/api/v1/assets/gateways/", + "/api/v1/assets/devices/", + "/api/v1/assets/clouds/", + "/api/v1/assets/customs/", + "/api/v1/assets/webs/", + "/api/v1/assets/gpts/", + "/api/v1/assets/assets/", + "/api/v1/assets/hosts/suggestions/", + "/api/v1/assets/devices/suggestions/", + "/api/v1/assets/gateways/suggestions/", + "/api/v1/assets/clouds/suggestions/", + "/api/v1/assets/customs/suggestions/", + "/api/v1/assets/webs/suggestions/", + "/api/v1/assets/gpts/suggestions/", + "/api/v1/assets/assets/suggestions/", +] + +GENERAL_SUGGESTION_PATHS = [ + "/api/v1/assets/assets/", + "/api/v1/assets/databases/", + "/api/v1/assets/hosts/", + "/api/v1/assets/gateways/", + "/api/v1/assets/devices/", + "/api/v1/assets/clouds/", + "/api/v1/assets/customs/", + "/api/v1/assets/webs/", + "/api/v1/assets/gpts/", + "/api/v1/assets/assets/suggestions/", + "/api/v1/assets/databases/suggestions/", + "/api/v1/assets/hosts/suggestions/", + "/api/v1/assets/gateways/suggestions/", + "/api/v1/assets/devices/suggestions/", + "/api/v1/assets/clouds/suggestions/", + "/api/v1/assets/customs/suggestions/", + "/api/v1/assets/webs/suggestions/", + "/api/v1/assets/gpts/suggestions/", + "/api/v1/tickets/apply-assets/suggestions/", +] + +EXPANSION_SEARCH_PATHS = [ + "/api/v1/assets/assets/suggestions/", + "/api/v1/tickets/apply-assets/suggestions/", +] +EXPANSION_SEARCH_SEEDS = list(string.ascii_lowercase) + list(string.digits) +EXPANSION_PRIMER_SEEDS = [ + "re", + "redis", + "mysql", + "mongo", + "postgres", + "oracle", + "sql", + "db", + "test", + "uat", + "prod", + "dev", + "auto", + "router", + "monitor", + "jump", + "ssh", +] +EXPANSION_MAX_SEEDS = 200 +EXPANSION_MAX_REQUESTS = 60 +SEED_TOKEN_PATTERN = re.compile(r"[A-Za-z0-9]{2,}") + + +def _safe_addstr(stdscr, y, x, text, attr=0): + # type: (Any, int, int, str, int) -> None + h, w = stdscr.getmaxyx() + if y < 0 or y >= h: + return + clipped = text[: max(0, w - x - 1)] + stdscr.addstr(y, x, clipped, attr) + + +def _log_tui_debug(client, event, payload): + # type: (JMSClient, str, Dict[str, Any]) -> None + """Writes structured TUI debug events through the client logger.""" + if not bool(getattr(client, "_debug", False)): + return + logger = getattr(client, "_logger", None) + if logger is None: + return + logger.debug( + "tui.%s %s", + event, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ) + + +def _show_notice(stdscr, title, lines): + # type: (Any, str, List[str]) -> bool + while True: + stdscr.erase() + h, _ = stdscr.getmaxyx() + _safe_addstr(stdscr, 0, 0, title, curses.A_BOLD) + viewport = max(1, h - 4) + for idx, line in enumerate(lines[:viewport]): + _safe_addstr(stdscr, idx + 2, 0, line) + _safe_addstr(stdscr, h - 1, 0, "按任意键返回服务器列表,q/Esc 退出") + stdscr.refresh() + key = stdscr.getch() + if key in (ord("q"), 27): + return False + return True + + +def _prompt_search(stdscr): + # type: (Any) -> Optional[str] + h, w = stdscr.getmaxyx() + prompt = "/" + max_len = max(1, w - len(prompt) - 1) + try: + curses.curs_set(1) + except curses.error: + pass + curses.echo() + _safe_addstr(stdscr, h - 1, 0, " " * max(1, w - 1)) + _safe_addstr(stdscr, h - 1, 0, prompt) + stdscr.move(h - 1, len(prompt)) + stdscr.refresh() + try: + raw = stdscr.getstr(h - 1, len(prompt), max_len) + except KeyboardInterrupt: + raw = b"" + finally: + curses.noecho() + try: + curses.curs_set(0) + except curses.error: + pass + if raw is None: + return None + if not isinstance(raw, bytes): + text = str(raw) + else: + text = raw.decode("utf-8", "ignore") + text = text.strip() + if text.startswith("/"): + text = text[1:].strip() + return text + + +def _choose_item( + stdscr, + title, + items, + formatter, + search_loader=None, + item_key=None, +) -> Optional[int]: + if not items: + return None + + selected = 0 + top = 0 + query = "" + while True: + all_indexes = list(range(len(items))) + if query: + needle = query.lower() + visible = [ + idx + for idx in all_indexes + if needle in formatter(items[idx]).lower() + ] + else: + visible = all_indexes + + if not visible: + selected = 0 + top = 0 + else: + if selected >= len(visible): + selected = len(visible) - 1 + if selected < 0: + selected = 0 + if selected < top: + top = selected + + stdscr.erase() + h, _ = stdscr.getmaxyx() + viewport = max(1, h - 4) + if selected >= top + viewport: + top = selected - viewport + 1 + + _safe_addstr(stdscr, 0, 0, title, curses.A_BOLD) + _safe_addstr( + stdscr, + 1, + 0, + ( + "Up/Down or j/k: move PgUp/PgDn or p/n/Space/b: page " + "/: search c: clear Enter: select q/Esc: quit" + ), + ) + total = len(visible) + pages = 1 if total <= 0 else ((total + viewport - 1) // viewport) + current_page = 1 if total <= 0 else ((selected // viewport) + 1) + if query: + _safe_addstr( + stdscr, + 2, + 0, + f"Search: /{query} Page {current_page}/{pages} Items {total}", + curses.A_DIM, + ) + if not visible: + _safe_addstr( + stdscr, + 3, + 0, + "No results, press / to search again or c to clear", + curses.A_DIM, + ) + elif not visible: + _safe_addstr(stdscr, 2, 0, "No results Page 1/1 Items 0", curses.A_DIM) + else: + _safe_addstr( + stdscr, + 2, + 0, + f"Page {current_page}/{pages} Items {total}", + curses.A_DIM, + ) + + for row in range(viewport): + pos = top + row + if pos >= len(visible): + break + idx = visible[pos] + text = formatter(items[idx]) + attr = curses.A_REVERSE if pos == selected else curses.A_NORMAL + _safe_addstr(stdscr, row + 3, 0, text, attr) + + stdscr.refresh() + key = stdscr.getch() + + if key in (ord("q"), 27): + return None + if key in (ord("/"),): + new_query = _prompt_search(stdscr) + if new_query is not None: + query = new_query + if query and callable(search_loader): + try: + loaded = search_loader(query) + except ( + RuntimeError, + ValueError, + TypeError, + KeyError, + ): + loaded = [] + if loaded: + if callable(item_key): + seen_keys = set() # type: set + for item in items: + seen_keys.add(str(item_key(item))) + for item in loaded: + key_text = str(item_key(item)) + if key_text in seen_keys: + continue + seen_keys.add(key_text) + items.append(item) + else: + items.extend(loaded) + selected = 0 + top = 0 + continue + if key in (ord("c"),): + query = "" + selected = 0 + top = 0 + continue + if not visible: + continue + if key in (curses.KEY_ENTER, 10, 13): + return visible[selected] + if key == curses.KEY_UP and selected > 0: + selected -= 1 + if selected < top: + top = selected + elif key == curses.KEY_DOWN and selected < len(visible) - 1: + selected += 1 + if selected >= top + viewport: + top = selected - viewport + 1 + elif key in (ord("k"),) and selected > 0: + selected -= 1 + if selected < top: + top = selected + elif key in (ord("j"),) and selected < len(visible) - 1: + selected += 1 + if selected >= top + viewport: + top = selected - viewport + 1 + elif key in (curses.KEY_PPAGE, ord("p"), ord("b")): + if len(visible) > 0: + selected = max(0, selected - viewport) + top = max(0, top - viewport) + if selected < top: + top = selected + elif key in (curses.KEY_NPAGE, ord("n"), ord(" "), ord("f")): + if len(visible) > 0: + selected = min(len(visible) - 1, selected + viewport) + top = min(max(0, len(visible) - viewport), top + viewport) + if selected < top: + selected = top + + +def _show_json(stdscr, payload): + # type: (Any, Dict[str, Any]) -> None + lines = json.dumps(payload, ensure_ascii=False, indent=2).splitlines() + top = 0 + while True: + stdscr.erase() + h, _ = stdscr.getmaxyx() + viewport = max(1, h - 3) + _safe_addstr( + stdscr, + 0, + 0, + "Token generated. Up/Down/j/k scroll, PgUp/PgDn/p/n/Space/b page, q/Esc exit", + ) + for row in range(viewport): + idx = top + row + if idx >= len(lines): + break + _safe_addstr(stdscr, row + 2, 0, lines[idx]) + stdscr.refresh() + key = stdscr.getch() + if key in (ord("q"), 27, curses.KEY_ENTER, 10, 13): + return + if key == curses.KEY_UP and top > 0: + top -= 1 + elif key == curses.KEY_DOWN and top < max(0, len(lines) - viewport): + top += 1 + elif key in (ord("k"),) and top > 0: + top -= 1 + elif key in (ord("j"),) and top < max(0, len(lines) - viewport): + top += 1 + elif key == curses.KEY_PPAGE: + top = max(0, top - viewport) + elif key == curses.KEY_NPAGE: + top = min(max(0, len(lines) - viewport), top + viewport) + elif key in (ord("p"),): + top = max(0, top - viewport) + elif key in (ord("n"),): + top = min(max(0, len(lines) - viewport), top + viewport) + + +def _normalize_protocols(value): + # type: (Any) -> List[str] + if value is None: + return [] + if isinstance(value, str): + return [item.strip().lower() for item in value.split(",") if item.strip()] + if isinstance(value, list): + output = [] # type: List[str] + for item in value: + if isinstance(item, str): + output.append(item.strip().lower()) + elif isinstance(item, dict): + text = item.get("name") or item.get("value") + if isinstance(text, str): + output.append(text.strip().lower()) + return [it for it in output if it] + return [] + + +def _pick_database_protocol(server_type, protocols): + # type: (str, List[str]) -> Optional[str] + database_types = { + "mysql", + "mariadb", + "postgresql", + "oracle", + "sqlserver", + "redis", + "mongodb", + "clickhouse", + } + if server_type in database_types: + return server_type + for item in protocols: + if item and item != "ssh": + return item + return None + + +def _server_profile(server): + # type: (Dict[str, Any]) -> Dict[str, Any] + source = str(server.get("_matched_protocol") or "").lower() + server_type = str(server.get("type") or "").lower() + category = str(server.get("category") or "").lower() + protocols = _normalize_protocols(server.get("protocols")) + db_protocol = _pick_database_protocol(server_type, protocols) + + if source == "ssh": + return {"kind": "SSH", "connect_method": "ssh_guide", "protocol": "ssh"} + if category == "database" or db_protocol: + return { + "kind": "DATABASE", + "connect_method": "db_guide", + "protocol": db_protocol, + } + if "ssh" in protocols: + return {"kind": "SSH", "connect_method": "ssh_guide", "protocol": "ssh"} + return {"kind": "GENERIC", "connect_method": "db_guide", "protocol": None} + + +def _build_probe_plans(profile): + # type: (Dict[str, Any]) -> List[Dict[str, Optional[str]]] + plans = [ + { + "connect_method": profile.get("connect_method"), + "protocol": profile.get("protocol"), + } + ] # type: List[Dict[str, Optional[str]]] + if profile.get("protocol"): + plans.append( + { + "connect_method": profile.get("connect_method"), + "protocol": None, + } + ) + plans.append({"connect_method": "ssh_guide", "protocol": "ssh"}) + plans.append({"connect_method": "db_guide", "protocol": None}) + + output = [] # type: List[Dict[str, Optional[str]]] + seen = set() # type: set + for item in plans: + method = str(item.get("connect_method") or "") + protocol = item.get("protocol") + key = f"{method}|{protocol}" + if not method or key in seen: + continue + seen.add(key) + output.append({"connect_method": method, "protocol": protocol}) + return output + + +def _merge_servers(primary, secondary): + # type: (List[Dict[str, Any]], List[Dict[str, Any]]) -> List[Dict[str, Any]] + merged = [] # type: List[Dict[str, Any]] + seen = set() # type: set + + for source in (primary, secondary): + for item in source: + sid = str(item.get("id") or "") + if sid: + key = sid + else: + key = f"{item.get('name') or ''}|{item.get('address') or ''}" + if key in seen: + continue + seen.add(key) + merged.append(item) + return merged + + +def _is_supported_server(server): + # type: (Dict[str, Any]) -> bool + address = str(server.get("address") or "").strip().lower() + if address.startswith("http://") or address.startswith("https://"): + return False + kind = str(_server_profile(server).get("kind") or "") + return kind in ("DATABASE", "SSH") + + +def _server_key(item): + # type: (Dict[str, Any]) -> str + sid = str(item.get("id") or "") + if sid: + return f"id:{sid}" + name = str(item.get("name") or "") + address = str(item.get("address") or "") + return f"na:{name}|{address}" + + +def _collect_seed_texts(container, value): + # type: (List[str], Any) -> None + if value is None: + return + if isinstance(value, str): + text = value.strip() + if text: + container.append(text) + return + if isinstance(value, dict): + for key in ("name", "label", "value", "id"): + field = value.get(key) + if isinstance(field, str): + text = field.strip() + if text: + container.append(text) + return + if isinstance(value, list): + for item in value: + _collect_seed_texts(container, item) + + +def _seed_texts_from_server(server): + # type: (Dict[str, Any]) -> List[str] + texts = [] # type: List[str] + for key in ("name", "address", "category", "type", "protocols"): + _collect_seed_texts(texts, server.get(key)) + raw = server.get("raw") + if isinstance(raw, dict): + for key in ( + "name", + "address", + "category", + "type", + "protocols", + "labels", + "nodes", + "nodes_display", + "platform", + ): + _collect_seed_texts(texts, raw.get(key)) + return texts + + +def _seed_candidates_from_text(text): + # type: (str) -> List[str] + candidates = [] # type: List[str] + for token in SEED_TOKEN_PATTERN.findall(text.lower()): + if len(token) > 30: + continue + if token.isdigit(): + # Ignore short IP-like fragments such as 10 or 21, but keep + # meaningful identifiers such as 110 or 3306. + if len(token) < 3: + continue + candidates.append(token) + continue + candidates.append(token) + if len(token) >= 2: + candidates.append(token[:2]) + if len(token) >= 3: + candidates.append(token[:3]) + return candidates + + +def _enqueue_server_seed_candidates(server, enqueue): + # type: (Dict[str, Any], Callable[[str], None]) -> None + for text in _seed_texts_from_server(server): + for seed in _seed_candidates_from_text(text): + enqueue(seed) + + +def _expand_servers_with_seed_queries(client, servers): + # type: (JMSClient, List[Dict[str, Any]]) -> List[Dict[str, Any]] + """Expands the initial asset list with additional suggestion queries.""" + seen = set(_server_key(item) for item in servers) # type: set + output = list(servers) # type: List[Dict[str, Any]] + + seed_queue = [] # type: List[str] + seen_seeds = set() # type: set + + def enqueue(seed): + # type: (str) -> None + text = str(seed or "").strip().lower() + if not text: + return + if text in seen_seeds: + return + if len(seen_seeds) >= EXPANSION_MAX_SEEDS: + return + seen_seeds.add(text) + seed_queue.append(text) + + for seed in EXPANSION_SEARCH_SEEDS: + enqueue(seed) + for seed in EXPANSION_PRIMER_SEEDS: + enqueue(seed) + for item in output: + _enqueue_server_seed_candidates(item, enqueue) + + _log_tui_debug( + client, + "expand.start", + { + "base_count": len(output), + "seed_count": len(seed_queue), + "max_seeds": EXPANSION_MAX_SEEDS, + "max_requests": EXPANSION_MAX_REQUESTS, + }, + ) + + cursor = 0 + request_count = 0 + while cursor < len(seed_queue) and request_count < EXPANSION_MAX_REQUESTS: + seed = seed_queue[cursor] + cursor += 1 + request_count += 1 + found = client.list_servers( + search=seed, + category=None, + asset_type=None, + protocols=None, + paths=EXPANSION_SEARCH_PATHS, + limit=500, + ) + newly_added = [] # type: List[Dict[str, Any]] + for item in found: + wrapped = dict(item, _matched_protocol=None) + if not _is_supported_server(wrapped): + continue + key = _server_key(wrapped) + if key in seen: + continue + seen.add(key) + output.append(wrapped) + newly_added.append(wrapped) + for item in newly_added: + _enqueue_server_seed_candidates(item, enqueue) + _log_tui_debug( + client, + "expand.done", + { + "base_count": len(servers), + "result_count": len(output), + "seed_count": len(seed_queue), + "requests": request_count, + }, + ) + return output + + +def run_tui(client): + # type: (JMSClient) -> Optional[Dict[str, Any]] + """Runs the interactive asset and account selection flow. + + Args: + client: Configured JumpServer client. + + Returns: + A compact token payload, or ``None`` when the user cancels. + """ + result = None # type: Optional[Dict[str, Any]] + + def _main(stdscr): + # type: (Any) -> None + nonlocal result + curses.curs_set(0) + stdscr.keypad(True) + + db_servers_raw = client.list_servers( + category="database", + asset_type=None, + paths=DB_SUGGESTION_PATHS, + limit=20000, + ) + db_servers = [ + dict(item, _matched_protocol="database") for item in db_servers_raw + ] + + ssh_servers_raw = client.list_servers( + category=None, + asset_type=None, + protocols="ssh", + paths=SSH_SUGGESTION_PATHS, + limit=20000, + ) + ssh_servers = [ + dict(item, _matched_protocol="ssh") for item in ssh_servers_raw + ] + + generic_servers_raw = client.list_servers( + category=None, + asset_type=None, + paths=GENERAL_SUGGESTION_PATHS, + limit=20000, + ) + generic_servers = [ + dict(item, _matched_protocol=None) for item in generic_servers_raw + ] + + servers = _merge_servers(db_servers, ssh_servers) + servers = _merge_servers(servers, generic_servers) + servers = [item for item in servers if _is_supported_server(item)] + _log_tui_debug( + client, + "list.base", + { + "db_count": len(db_servers), + "ssh_count": len(ssh_servers), + "generic_count": len(generic_servers), + "base_supported_count": len(servers), + }, + ) + servers = _expand_servers_with_seed_queries(client, servers) + _log_tui_debug( + client, + "list.final", + {"final_supported_count": len(servers)}, + ) + if not servers: + raise TUIExit("No servers found") + + def _load_servers_by_search(query): + # type: (str) -> List[Dict[str, Any]] + if not query: + return [] + + db = client.list_servers( + search=query, + category="database", + asset_type=None, + paths=DB_SUGGESTION_PATHS, + limit=500, + ) + db_items = [dict(item, _matched_protocol="database") for item in db] + ssh = client.list_servers( + search=query, + category=None, + asset_type=None, + protocols="ssh", + paths=SSH_SUGGESTION_PATHS, + limit=500, + ) + ssh_items = [dict(item, _matched_protocol="ssh") for item in ssh] + generic = client.list_servers( + search=query, + category=None, + asset_type=None, + paths=GENERAL_SUGGESTION_PATHS, + limit=500, + ) + generic_items = [dict(item, _matched_protocol=None) for item in generic] + + merged = _merge_servers(db_items, ssh_items) + merged = _merge_servers(merged, generic_items) + return [item for item in merged if _is_supported_server(item)] + + while True: + server_idx = _choose_item( + stdscr, + "选择服务器(数据库 + SSH)", + servers, + lambda item: ( + f"{_server_profile(item).get('kind'):<9} " + f"{item.get('name', '-'):<28} " + f"{item.get('address', '-'):<18} " + f"{item.get('id', '-')}" + ), + search_loader=_load_servers_by_search, + item_key=_server_key, + ) + if server_idx is None: + return + + server = servers[server_idx] + server_profile = _server_profile(server) + validated = None # type: Optional[Dict[str, Any]] + chosen_connect_method = server_profile.get("connect_method") + chosen_protocol = server_profile.get("protocol") + for plan in _build_probe_plans(server_profile): + validated = client.list_accessible_usernames( + str(server.get("id")), + asset_name=str(server.get("name", "")), + asset_address=str(server.get("address", "")), + connect_method=str(plan.get("connect_method") or "db_guide"), + protocol=( + str(plan.get("protocol")) + if plan.get("protocol") is not None + else None + ), + asset_data=server.get("raw"), + ) + accounts = validated.get("accounts", []) + if accounts: + chosen_connect_method = plan.get("connect_method") + chosen_protocol = plan.get("protocol") + break + else: + accounts = [] + + token_cache = ( + validated.get("token_cache", {}) if isinstance(validated, dict) else {} + ) + if not accounts: + candidate_count = ( + int(validated.get("candidate_count", 0)) + if isinstance(validated, dict) + else 0 + ) + rejected_count = ( + len(validated.get("rejected_accounts", [])) + if isinstance(validated, dict) + else 0 + ) + rejected_codes = ( + validated.get("rejected_codes", {}) + if isinstance(validated, dict) + else {} + ) + lines = [ + f"服务器: {server.get('name')} ({server.get('id')})", + "当前 Key 下没有可连接账号。", + f"候选账号: {candidate_count},被拒绝: {rejected_count}", + ] + if rejected_codes: + lines.append( + "拒绝码统计: " + f"{json.dumps(rejected_codes, ensure_ascii=False)}" + ) + lines.append("请在 JumpServer 里确认该资产已授权可连接账号。") + should_continue = _show_notice(stdscr, "该服务器不可连", lines) + if not should_continue: + return + continue + + username_entries = ( + validated.get("username_entries", []) + if isinstance(validated, dict) + else [] + ) + if not username_entries: + username_entries = [ + {"username": str(item), "account": str(item)} for item in accounts + ] + + user_idx = _choose_item( + stdscr, + f"选择账号(仅显示可连接): {server.get('name')}", + username_entries, + lambda item: ( + f"{item.get('username', '')} ({item.get('account', '')})" + if str(item.get("username", "")) != str(item.get("account", "")) + else str(item.get("username", "")) + ), + ) + if user_idx is None: + continue + + selected_entry = username_entries[user_idx] + account = str(selected_entry.get("account") or "") + token = token_cache.get(account) + if token is None: + token = client.get_connection_token( + asset_id=str(server.get("id")), + account=account, + connect_method=str(chosen_connect_method or "db_guide"), + protocol=( + str(chosen_protocol) + if chosen_protocol is not None + else None + ), + ) + token_username = token.get("id") + token_password = token.get("value") + result = { + "ok": True, + "server": str(server.get("name") or server.get("id") or ""), + "account": account, + "connect_method": chosen_connect_method, + "protocol": chosen_protocol, + "token_username": token_username, + "token_password": token_password, + "expire_time": token.get("expire_time"), + } + _show_json(stdscr, result) + return + + curses.wrapper(_main) + return result diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..88d57ae --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +requests>=2.27.1,<2.28; python_version < "3.7" +requests>=2.31.0; python_version >= "3.7"