commit 4c4a1da09bfde5de767a18d5c92123ecdab00889 Author: nvk Date: Fri Feb 14 10:42:15 2020 -0500 make public diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52fd4b9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +ENV +.DS_Store + +*.log +*.swp + +__pycache__/ +*.pyc + +.tags +pp +history.yaml + +bunker.egg-info/ diff --git a/CNAME b/CNAME new file mode 100644 index 0000000..17ae828 --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +ckbunker.com \ No newline at end of file diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..26d5e23 --- /dev/null +++ b/LICENSE @@ -0,0 +1,16 @@ + + (c) Copyright 2017-2019 by Coinkite Inc. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +in the file COPYING. If not, see . + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..19e2fa3 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +all: + @echo "No default" + + +tags: + ctags -f .tags *.py */*.py + diff --git a/README.md b/README.md new file mode 100644 index 0000000..e7024dd --- /dev/null +++ b/README.md @@ -0,0 +1,112 @@ +# CK Bunker + +## What is the Coinkite Bunker? + +It's a python program that you run on a computer attached to a +Coldcard. It will setup and operate the Coldcard in "HSM Mode" where +it signs without a human pressing the OK key. To keep your +funds safe, the Coldcard implements a complex set of spending rules +which cannot be changed once HSM mode is started. + +Using the `tord` (Tor deamon) you already have, the CK Bunker can +make itself available as a hidden service for remote access over +Tor. A pretty website for setup and operation allows access to all +HSM-related Coldcard features, including: + +- transaction signing, by uploading a PSBT; can broadcast signed txn using Blockstream.info (onion) +- define policy rules, spending limits, velocity controls, logging policy +- user setup (TOTP QR scan to enroll on Coldcard, or random passwords (Coldcard) or known password + +The bunker encrypts its own settings and stores the private key for that inside Coldcard's +storage locker (which is inside the secure element). The private key for the onion +service, for example, is held on the bunker's disk encrypted like that. + +## What is Coldcard? + +Coldcard is a Cheap, Ultra-secure & Opensource Hardware Wallet for Bitcoin. +Get yours at [ColdcardWallet.com](http://coldcardwallet.com) + +[Follow @COLDCARDwallet on Twitter](https://twitter.com/coldcardwallet) to keep up +with the latest updates and security alerts. + +## Check-out and Setup + +Do a checkout, recursively to get all the submodules: + + git clone --recursive https://github.com/Coldcard/ck-bunker.git + +Then: + +- `virtualenv -p python3 ENV` (Python 3.7 or higher is required) +- `source ENV/bin/activate` (or `source ENV/bin/activate.csh` based on shell preference) +- `pip install -r requirements.txt` +- `pip install --editable .` + +## Usage + +The executable is called `ck-bunker`: + +```sh +$ ck-bunker --help +Usage: ck-bunker [OPTIONS] COMMAND [ARGS]... + +Options: + -s, --serial HEX Operate on specific unit (default: first found) + --help Show this message and exit. + +Commands: + list List all attached Coldcard devices + example Show an example config file, using the default values + run Start the CK-Bunker for normal operation + setup Configure your transaction signing policy, install it and then... +``` + +There are two modes for the Bunker: "setup" and "run mode". In setup +mode, Tor connections are disabled, as is the login screen. + +You would typically use the setup mode for picking the onion address, the +master login password and all the details of the HSM policy. + +```sh +$ ck-bunker setup +``` + +Open this URL in your local web browser (must be same machine): + + +Once the Coldcard is running in HSM mode, with your policy installed, +it makes sense to operate in normal "run" mode: + +```sh +$ ck-bunker run +``` + +You may also run with remote connections (and login) disabled. This would be useful +if you have some existing web proxy already in place. + +```sh +$ ck-bunker --local run +``` + +## Tor Use + +To access over Tor as a hidden service, you must have `tord` running +on the same machine. For desktop systems, keeping TorBrowser open +is enough to acheive this. On servers, start tord with default options, +and ck-bunker will use the control port (localhost port 9051 or 9151). + +If you use the bunker to broadcast the final (signed) transaction, +the socks proxy of tord (port 9050) will also be used. + + +## Operational Requirements + +You will need: + +- this code +- a Coldcard connected via USB +- `tord` (Tor program) +- Internet connection +- a Tor-capable brwoser, like "Tor Browser" or Tails. +- (optional) a microSD card, for logging of transactions on Coldcard + diff --git a/chain.py b/chain.py new file mode 100644 index 0000000..4fa2d57 --- /dev/null +++ b/chain.py @@ -0,0 +1,68 @@ +# (c) Copyright 2020 by Coinkite Inc. This file is part of Coldcard +# and is covered by GPLv3 license found in COPYING. +# +# chain.py --- API to blockstream stuff +# +import sys, os, asyncio, logging, requests +from objstruct import ObjectStruct +from persist import settings +from status import STATUS +from binascii import b2a_hex, a2b_hex +from utils import json_loads + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +def broadcast_txn(txn): + # take bytes and get them shared over P2P to the world + # - raise w/ text about what happened if it fails + # - limited docs: + ses = requests.session() + ses.proxies = dict(http=settings.TOR_SOCKS) + ses.headers.clear() # hide user-agent + + url = settings.EXPLORA + url += '/api/tx' if not STATUS.is_testnet else '/testnet/api/tx' + + assert '.onion/' in url, 'dude, your privacy' + logging.warning(f"Sending txn via: {url}") + resp = ses.post(url, data=b2a_hex(txn).decode('ascii')) + + msg = resp.text + + if not resp.ok: + # content is like: + # sendrawtransaction RPC error: {"code":-22,"message":"TX decode failed"} + # which is a text thing, including some JSON from bitcoind? + + if '"message":' in msg: + try: + prefix, rest = msg.split(': ', 1) + j = json_loads(rest) + if prefix == 'sendrawtransaction RPC error': + msg = j.message + else: + msg = prefix + ': ' + j.message + except: + pass + + msg = f"Transaction broadcast FAILED: {msg}" + logging.error(msg) + return msg + + # untested + msg = f"Transaction broadcast success: {msg}" + logging.info(msg) + + return msg + +def link_to_txn(txn_hash): + path = '/tx/' if not STATUS.is_testnet else '/testnet/tx/' + assert len(txn_hash) == 64 + return settings.EXPLORA + path + txn_hash + + +if __name__ == '__main__': + # test code + r = broadcast_txn(b'sdhffkhjkdfshdfshjdfshdfkshdfs') + +# EOF diff --git a/chrono.py b/chrono.py new file mode 100644 index 0000000..3bbf626 --- /dev/null +++ b/chrono.py @@ -0,0 +1,37 @@ +# +# Time/data related functions. Trying hard not to rewrite existing things. +# +# Everything should be stored/calculated in UTC. +# +import time, datetime, calendar, pendulum +from email.utils import formatdate as rfc_format + +def NOW(): + # Use this for everything. + return pendulum.now() + +def TIME_AGO(**kws): + # Return a time in past, like TIME_AGO(hours=3) + return pendulum.now() - datetime.timedelta(**kws) + +def TIME_FUTURE(**kws): + # Return a time in future, like TIME_FUTURE(hours=3) + return pendulum.now() + datetime.timedelta(**kws) + +def as_time_t(dt): + " convert datetime into unix timestamp (all UTC)" + if hasattr(dt, 'timestamp'): + # expected case for Pendulum values + return dt.timestamp() + else: + return calendar.timegm(dt.utctimetuple()) + +def from_time_t(time_t): + " convert unix timestamp into datetime (all UTC)" + return pendulum.from_timestamp(time_t) + +def from_iso(s): + # Convert from ISO8601, and capture TZ + return pendulum.parse(s) + +# EOF diff --git a/conn.py b/conn.py new file mode 100644 index 0000000..80fbb20 --- /dev/null +++ b/conn.py @@ -0,0 +1,331 @@ +# (c) Copyright 2020 by Coinkite Inc. This file is part of Coldcard +# and is covered by GPLv3 license found in COPYING. +# +# Connection to Coldcard (and/or simulator). +# +import asyncio, logging, os +from utils import Singleton, xfp2str, json_loads, json_dumps +from status import STATUS +from persist import settings, BP +from binascii import a2b_hex +import policy +from objstruct import ObjectStruct +from hmac import HMAC +from hashlib import sha256 +from concurrent.futures import ThreadPoolExecutor + +from ckcc.protocol import CCProtocolPacker, CCProtocolUnpacker, CCFramingError +from ckcc.protocol import CCProtoError, CCUserRefused, CCBusyError +from ckcc.client import ColdcardDevice, COINKITE_VID, CKCC_PID +from ckcc.constants import (USER_AUTH_TOTP, USER_AUTH_HMAC, USER_AUTH_SHOW_QR, MAX_USERNAME_LEN) +from ckcc.utils import calc_local_pincode + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +executor = ThreadPoolExecutor(max_workers=5) + +# if you see this, it means the USB plug is fell out! +class MissingColdcard(RuntimeError): + pass + +#logging.info("fd = %d" % open('/dev/null').fileno()) + +class Connection(metaclass=Singleton): + + def __init__(self, serial): + self.serial = serial + self.dev = None + self.dev_key = None + self.lock = asyncio.Lock() + self.sign_lock = asyncio.Lock() + self._conn_broken(setup_time=True) + + async def run(self): + # connect to, and maintain a connection to a single Coldcard + + logging.info("Connecting to Coldcard.") + + while 1: + try: + if not self.serial and os.path.exists(settings.SIMULATOR_SOCK): + # if simulator is running, just use it. + sn = settings.SIMULATOR_SOCK + else: + sn = self.serial + + d = ColdcardDevice(sn=sn) + logging.info(f"Found Coldcard {d.serial}.") + + await asyncio.get_running_loop().run_in_executor(executor, d.check_mitm) + + async with self.lock: + self.dev = d + except: + logging.error("Cannot connect to Coldcard (will retry)", exc_info=0) + await asyncio.sleep(settings.RECONNECT_DELAY) + continue + + # stay connected, and check we are working periodically + logging.info(f"Connected to Coldcard {self.dev.serial}.") + + STATUS.connected = True + + # read static info about coldcard + STATUS.xfp = xfp2str(self.dev.master_fingerprint) + STATUS.serial_number = self.dev.serial + STATUS.is_testnet = (self.dev.master_xpub[0] == 't') + STATUS.hsm = {} + STATUS.reset_pending_auth() + STATUS.notify_watchers() + await self.hsm_status() + + while 1: + await asyncio.sleep(settings.PING_RATE) + try: + # use long timeout here, even tho simple command, because the CC may + # we working on something else right now (thinking). + h = await self.send_recv(CCProtocolPacker.hsm_status(), timeout=20000) + logging.info("ping ok") + await self.hsm_status(h) + except MissingColdcard: + self._conn_broken() + break + except: + logging.error("Ping failed", exc_info=1) + + def _conn_broken(self, setup_time=False): + # our connection is lost, so clear/reset system state + if self.dev: + self.dev.close() + self.dev = None + + STATUS.connected = False + STATUS.xfp = None + STATUS.serial_number = None + STATUS.is_testnet = False + STATUS.hsm = {} + STATUS.reset_pending_auth() + + if not setup_time: + BP.reset() + + STATUS.notify_watchers() + + async def activated_hsm(self): + # just connected to a Coldcard w/ HSM active already + # - ready storage locker, decrypt and use those settings + logging.info("Coldcard now in HSM mode. Fetching storage locker.") + + try: + sl = await self.get_storage_locker() + except CCProtoError as exc: + if 'consumed' in str(exc): + import os, sys + msg = "Coldcard refused access to storage locker. Reboot it and enter HSM again" + logging.error(msg) + print(msg, file=sys.stderr) + sys.exit(1) + else: + raise + + try: + import policy + xk = policy.decode_sl(sl) + except: + logging.error("Unable to parse contents of storage locker: %r" % sl) + return + + if BP.open(xk): + # unable to read our settings specific to this CC? Go to defaults + # or continue? + logging.error("Unable to read bunker settings for this Coldcard; forging on") + else: + STATUS.sl_loaded = True + + if BP.get('tor_enabled', False) and not (STATUS.force_local_mode or STATUS.setup_mode): + # get onto Tor as a HS + from torsion import TOR + STATUS.tor_enabled = True + logging.info(f"Starting hidden service: %s" % BP['onion_addr']) + asyncio.create_task(TOR.start_tunnel()) + + STATUS.reset_pending_auth() + STATUS.notify_watchers() + + async def send_recv(self, msg, **kws): + # a more-async version of ColdcardDevice.send_recv? + + if not self.dev or not STATUS.connected: + raise MissingColdcard + + try: + def doit(): + return self.dev.send_recv(msg, **kws) + + # we do need this lock + async with self.lock: + return await asyncio.get_running_loop().run_in_executor(executor, doit) + + except CCFramingError: + self._conn_broken() + raise MissingColdcard + except (CCProtoError, CCUserRefused): + raise + except BaseException as exc: + logging.error(f"Error from Coldcard: {exc} (for msg: {msg!r}") + self._conn_broken() + raise MissingColdcard + + async def hsm_status(self, h=None): + # refresh HSM status + b4 = STATUS.hsm.get('active', False) + + try: + b4_nlc = STATUS.hsm.get('next_local_code') + h = h or (await self.send_recv(CCProtocolPacker.hsm_status())) + STATUS.hsm = h = json_loads(h) + STATUS.notify_watchers() + except MissingColdcard: + h = {} + + if h.get('next_local_code') and STATUS.psbt_hash: + if b4_nlc != h.next_local_code: + STATUS.local_code = calc_local_pincode(a2b_hex(STATUS.psbt_hash), h.next_local_code) + else: + # won't be required + STATUS.local_code = None + + if ('summary' in h) and h.summary and not BP.get('priv_over_ux') and not BP.get('summary'): + logging.info("Captured CC's summary of the policy") + BP['summary'] = h.summary + BP.save() + + # has it just transitioned into HSM mode? + if STATUS.connected and STATUS.hsm.active and not b4: + await self.activated_hsm() + + return STATUS.hsm + + async def hsm_start(self, new_policy=None): + args = [] + if new_policy is not None: + # must upload it first + data = json_dumps(new_policy).encode('utf8') + args = self.dev.upload_file(data) + + # save a trimmed copy of some details, if they want that + bk = policy.desensitize(new_policy) + BP['summary'] = None + if not bk.get('priv_over_ux'): + BP['priv_over_ux'] = False + BP['policy'] = bk # full copy + BP['xfp'] = xfp2str(self.dev.master_fingerprint) + BP['serial'] = self.dev.serial + else: + BP['priv_over_ux'] = True + BP['policy'] = None + BP['xfp'] = None + BP['serial'] = None + + BP.save() + + try: + await self.send_recv(CCProtocolPacker.hsm_start(*args)) + except CCProtoError as exc: + msg = str(exc) + logging.error("Coldcard didn't like policy: %s" % msg) + raise RuntimeError(str(msg)) + + async def delete_user(self, username): + await self.send_recv(CCProtocolPacker.delete_user(username)) + + async def create_user(self, username, authmode, new_pw=None): + # typically we'll let Coldcard pick password + if authmode == USER_AUTH_HMAC and new_pw: + secret = self.dev.hash_password(new_pw.encode('utf8')) + else: + secret = b'' + + await self.send_recv(CCProtocolPacker.create_user(username, authmode, secret)) + + async def user_auth(self, username, token, totp, psbt_hash): + if len(token) == 6 and token.isdigit(): + # assume TOTP if token (password) is 6-numeric digits + totp_time = totp or int(time.time() // 30) + token = token.encode('ascii') + else: + # assume it's a raw password. need to hash it up + # TODO: move this hashing into browser + secret = self.dev.hash_password(token.encode('utf8')) + token = HMAC(secret, msg=psbt_hash, digestmod=sha256).digest() + totp_time = 0 + + await self.send_recv(CCProtocolPacker.user_auth(username.encode('ascii'), token, totp_time)) + + async def get_storage_locker(self): + return await self.send_recv(CCProtocolPacker.get_storage_locker()) + + async def sign_psbt(self, data, finalize=False, flags=0x0): + # upload it first + + async with self.sign_lock: + sz, chk = self.dev.upload_file(data) + assert chk == a2b_hex(STATUS.psbt_hash) + + await self.send_recv(CCProtocolPacker.sign_transaction(sz, chk, finalize, flags)) + + # wait for it to finish + return await self.wait_and_download(CCProtocolPacker.get_signed_txn()) + + async def wait_and_download(self, req, fn=1): + # Wait for user action (sic) on the device... by polling w/ indicated request + # - also download resulting file + + while 1: + await asyncio.sleep(0.250) + done = await self.send_recv(req, timeout=None) + if done == None: + continue + break + + if len(done) != 2: + logging.error('Coldcard failed: %r' % done) + raise RuntimeError(done) + + result_len, result_sha = done + + # download the result. + result = self.dev.download_file(result_len, result_sha, file_number=fn) + + return result + + async def sign_text_msg(self, msg, subpath, addr_fmt): + # send text and path to sign with; no policy check + + msg = msg.encode('ascii') + + async with self.sign_lock: + try: + await self.send_recv(CCProtocolPacker.sign_message(msg, subpath, addr_fmt)) + + while 1: + await asyncio.sleep(0.250) + done = await self.send_recv(CCProtocolPacker.get_signed_msg(), timeout=None) + if done == None: + continue + break + + except CCUserRefused: + raise RuntimeError("Coldcard refused request based on policy.") + + if len(done) != 2: + logging.error('Coldcard failed: %r' % done) + raise RuntimeError(done) + + addr, sig = done + + return sig, addr + + + +# EOF diff --git a/data/.gitignore b/data/.gitignore new file mode 100644 index 0000000..773a6df --- /dev/null +++ b/data/.gitignore @@ -0,0 +1 @@ +*.dat diff --git a/data/README.md b/data/README.md new file mode 100644 index 0000000..1f034b0 --- /dev/null +++ b/data/README.md @@ -0,0 +1,8 @@ + +# Data Files + +- this directory will hold data files for the Bunker +- they are encrypted with a private key held in the "storage locker" of the Coldcard +- contents include Tor hidden service private key and settings +- filename based on key +- default key maps to `bp-1850f665aa1e22c0.dat` diff --git a/example-settings.yaml b/example-settings.yaml new file mode 100644 index 0000000..bfec74e --- /dev/null +++ b/example-settings.yaml @@ -0,0 +1,8 @@ +# Example configuration file. See persist.py for variable names and default values. +# +# Usage: +# +# ck-bunker setup -c example-settings.yaml +# ck-bunker run -c example-settings.yaml +# +PORT_NUMBER: 9800 diff --git a/main.py b/main.py new file mode 100644 index 0000000..34506af --- /dev/null +++ b/main.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python +# +# (c) Copyright 2020 by Coinkite Inc. This file is part of Coldcard +# and is covered by GPLv3 license found in COPYING. +# +# Main entry-point for project. +# +# To use this, install with: +# +# pip install --editable . +# +# That will create the command "ck-bunker" in your path. +# +import os, sys, click, hid, asyncio, logging +from pprint import pformat, pprint + +global force_serial +force_serial = None + +from ckcc.protocol import CCProtocolPacker +from ckcc.protocol import CCProtoError, CCUserRefused, CCBusyError +from ckcc.client import ColdcardDevice, COINKITE_VID, CKCC_PID + + +# Options we want for all commands +@click.group() +@click.option('--serial', '-s', default=None, metavar="HEX", + help="Operate on specific unit (default: first found)") +def main(serial): + global force_serial + force_serial = serial + +@main.command('list') +def _list(): + "List all attached Coldcard devices" + + count = 0 + for info in hid.enumerate(COINKITE_VID, CKCC_PID): + #click.echo("\nColdcard {serial_number}:\n{nice}".format( + # nice=pformat(info, indent=4)[1:-1], **info)) + click.echo(info['serial_number']) + count += 1 + + if not count: + click.echo("(none found)") + +@main.command('example') +def example_config(): + "Show an example config file, using the default values" + + from persist import Settings + + click.echo(Settings.make_sample()) + +@main.command('run') +@click.option('--local', '-l', default=False, is_flag=True, + help="Don't enable Tor (onion) access: just be on localhost") +@click.option('--psbt', '-f', metavar="filename.psbt", + help="Preload first PSBT to be signed", default=None, + type=click.File('rb')) +@click.option('--config-file', '-c', type=click.File('rt'), required=False) +def start_service(local=False, config_file=None, psbt=None): + "Start the CK-Bunker for normal operation" + + if psbt: + psbt = psbt.read() + + asyncio.run(startup(False, local, config_file, psbt), debug=True) + +@main.command('setup') +@click.option('--local', '-l', default=False, is_flag=True, + help="Don't enable Tor (onion) access: just be on localhost") +@click.option('--config-file', '-c', type=click.File('rt'), required=False) +def setup_hsm(local=False, config_file=None): + "Configure your transaction signing policy, install it and then operate." + + asyncio.run(startup(True, local, config_file, None), debug=True) + +async def startup(setup_mode, force_local_mode, config_file, first_psbt): + # All startup/operation code + + loop = asyncio.get_running_loop() + if loop.get_debug(): + # quiet noise about slow stuff + loop.slow_callback_duration = 10 + + from utils import setup_logging + setup_logging() + + from persist import Settings + Settings.startup(config_file) + + aws = [] + + # copy some args into status area + from status import STATUS + STATUS.force_local_mode = force_local_mode + STATUS.setup_mode = setup_mode + + # preload the contents of a PSBT + if first_psbt: + STATUS.import_psbt(first_psbt) + + from torsion import TOR + aws.append(TOR.startup()) + + from conn import Connection + aws.append(Connection(force_serial).run()) + + import webapp + aws.append(webapp.startup(setup_mode)) + + + await asyncio.gather(*aws) + + +# EOF diff --git a/make_captcha.py b/make_captcha.py new file mode 100755 index 0000000..30512ae --- /dev/null +++ b/make_captcha.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# +# Draw a Captchas ... not meant to be hard, but easier to replace out, and challenging +# to read image itself.. +# +import random, os, io +from PIL import Image, ImageDraw, ImageFont + +# Avoid similar-looking letters/numbers. +TOKEN_CHARS = 'abcdefghkmnpqrstuvwxyz23456789' + +class CaptchaMaker: + size = (256, 64) # limited by iphone case. esp. when entering value + + def __init__(self, seed=None): + self.rng = random.Random(seed) + + + def draw(self, token): + # draw some crazy captcha for indicated token and return as a + # tuple: extension, raw_data + raise NotImplementedError + + def get_font(self, size=40, which='nova'): + fn = { 'ransom': 'static/fonts/ransom-note.ttf', + 'nova': 'static/fonts/proximanova-semibold.ttf' + } + return ImageFont.truetype(fn[which], size) + +class RansomCaptcha(CaptchaMaker): + # + # Just the simple ransom note that most people expect today. + # + def draw(self, token, foreground='#000', seed=None): + fn = self.get_font(size=40, which='ransom') + w,h = self.size + dx,dy = fn.getsize('W') + + im = Image.new('RGBA', self.size) + dr = ImageDraw.Draw(im) + + # some of the lower-case letters are confusing, so replace them + remap = dict(x = 'X', s='S', a='A', g='G', q='Q') + + x = 10 + ix = (w - (x*2)) * (len(token)-2) / dx + for ch in token: + ch = remap.get(ch, ch) + y = self.rng.randint(-5, h-dy+5) + dr.text( (x, y), ch, fill=foreground, font=fn) + x += ix + + data = io.BytesIO() + im.save(data, format='png') + + return 'png', data.getvalue() + +class MegaGifCaptcha(CaptchaMaker): + # These are fun, but too large to be practical? Keep in toolbox for later. + + def draw(self, token, foreground='#fff', background='white'): + + token = ' '.join(token.upper()) + + fn = self.get_font(size=30, which='nova') + w,h = self.size + dx,dy = fn.getsize('W') + + randint = self.rng.randint + sample = self.rng.sample + + actual = [] + pass_thru = set() + frames = [] + + ans_y = self.rng.randint(3, h-dy-3) + ans_w = fn.getsize(token)[0] + count = 15 + + for fr_num in range(count): + im = Image.new('P', self.size, background) + dr = ImageDraw.Draw(im) + + # give them noise chars, except they are mostly correct so that + # the order is not so clear at all. don't want to just be able to + # pick the most common chars observed + charset = set(token) + while len(charset) < len(token) + 4: + charset.add(sample(TOKEN_CHARS, 1)[0]) + + for k in range(int(w * 1.5/dx)): + #ch = ''.join(self.rng.sample(TOKEN_CHARS, 1)).upper() + ch = ''.join(sample(charset, 1)).upper() + x = randint(-dx, w) + y = ans_y + randint(-dy*3/4, dy*3/4) + dr.text( (x,y), ch, fill=foreground, font=fn) + + frames.append(im) + + x = (w-ans_w)*fr_num / count + dr.text( (x, ans_y), token, fill=foreground, font=fn) + + data = io.BytesIO() + + frames[0].save(data, format='gif', save_all=True, loop=0, + append_images=frames + list(reversed(frames[1:-1]))) + + return 'gif', data.getvalue() + +# EOF diff --git a/objstruct.py b/objstruct.py new file mode 100644 index 0000000..e5edf2c --- /dev/null +++ b/objstruct.py @@ -0,0 +1,63 @@ +# (c) Copyright 2020 by Coinkite Inc. This file is part of Coldcard +# and is covered by GPLv3 license found in COPYING. +# +# objstruct.py +# + +class ObjectStruct(dict): + '''An object like both a dict and also an object that you can + easily use attr reference to get members. Construct with a + dict or like a dict. + ''' + + def __getattr__(self, name): + if name in self: + return self[name] + else: + # Do not return a default here because it breaks things + raise AttributeError('No such attribute: %s' % name) + + def __setattr__(self, name, value): + self[name] = value + + def __delattr__(self, name): + del self[name] + + def __repr__(self): + ret = '<%s:' % self.__class__.__name__ + for k,v in self.items(): + ret += ' %s=%r' % (k, v) + return ret + '>' + + @classmethod + def promote(cls, x): + # Often I get a dict() from an API wrapper that's taken some json and + # run it thru json.loads(). It would be better to have that as nested + # ObjectStruct (which is easily done with some arguments to loads, but + # usually they don't provide that feature)... so call this function + # + + if isinstance(x, list): + return [cls.promote(i) for i in x] + + if isinstance(x, dict): + x = cls(x) + for k in x: + x[k] = cls.promote(x[k]) + + return x + +class DefaultObjectStruct(ObjectStruct): + ''' Same, but can provide a default value if get_default is overriden''' + def get_default(self, fldname): + # override me + return None + + def __getattr__(self, name): + if name in self: + return self[name] + else: + # sometimes you do want a default. + return self.get_default(name) + +# EOF diff --git a/persist.py b/persist.py new file mode 100644 index 0000000..97e2575 --- /dev/null +++ b/persist.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python +# +# Persistent data for Bunker itself. Trying to minimize this for privacy. +# +import os, yaml, nacl.secret, logging +from utils import Singleton, xfp2str, json_dumps, json_loads, WatchableMixin +from hashlib import sha256 +from objstruct import ObjectStruct + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +# globals, used system-wide +settings = None +BP = None + +# System-wide settings for Bunker itself. +# +class Settings(metaclass=Singleton): + + # web server port + PORT_NUMBER = 9823 + + # session idle time, before we kick you out and require re-auth (seconds) + MAX_IDLE_TIME = 10*60 + + # max time between showing login page, and the would-be user entering something useful (seconds) + MAX_LOGIN_WAIT_TIME = 5*60 + + # bogus fixed password to get started + MASTER_PW = 'test1234' + + # default is harder captcha + EASY_CAPTCHA = False + + # default for "allow reboot of bunker" + # - can you restart the bunker w/o restarting the Coldcard HSM? + ALLOW_REBOOTS = True + + # path to data files + DATA_FILES = './data' + + # used during secret/when we don't have a key yet + # - maps to data/bp-1850f665aa1e22c0.dat + PLACEHOLDER_KEY = b'ab'*16 + + # endpoint to use for sending txn; we assume it's Explora protocol (Blockstream.info) + EXPLORA = 'http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion' + + # port number for local instance of tord + # - will try 9051 and 9151 + # - but first /var/run/tor/control as unix socket + TORD_PORT = 'default' + + # for broadcasting, socks proxy via Tord + TOR_SOCKS = 'socks5h://127.0.0.1:9150' + + # unix pipe for local Coldcard Simulator + SIMULATOR_SOCK = '/tmp/ckcc-simulator.sock' + + # delay between retries connecting to missing/awol Coldcard + RECONNECT_DELAY = 10 # seconds between retries + PING_RATE = 15 # seconds between pings (CC status checks) + + def read(self, fobj): + t = yaml.safe_load(fobj) + if not t: return + + for k,v in t.items(): + if k.upper() != k or k[0]=='_': + logging.error(f"{k}: must be upper case") + continue + if not hasattr(self, k): + logging.error(f"{k}: unknown setting") + continue + + setattr(self, k, v) + + @classmethod + def make_sample(cls): + # produce an example config file + d = {} + x = cls() + for k in dir(x): + if k.upper() != k or k[0]=='_': continue + d[k] = getattr(x, k) + + return yaml.safe_dump(d) + + @classmethod + def startup(cls, config_file=None): + # creates singleton + global settings, BP + + # only safe place to create singletons is here + assert not settings and not BP + + settings = Settings() + if config_file: + settings.read(config_file) + + # load defaults into BP + BP = BunkerPersistance() + BP.reset() + +# Store some state, encrypted. +# - inial values are the settings, but lower case for some reason +# - some are adjustable on "Bunker Setup" page +class BunkerPersistance(WatchableMixin, dict, metaclass=Singleton): + fields = ['tor_enabled', 'onion_pk', 'onion_addr', 'allow_reboots', + 'easy_captcha', 'master_pw'] + + def __init__(self): + super(BunkerPersistance, self).__init__() + self.key = None + self.filename = None + self.set_defaults() + + def reset(self): + self.open(settings.PLACEHOLDER_KEY) + + def set_defaults(self): + # defaults here + for fn in self.fields: + if fn not in self: + self[fn] = getattr(settings, fn.upper(), None) + + def set_secret(self, key): + # setup for reading/writing using indicated key + assert len(key) == 32 + + self.key = key + self.box = nacl.secret.SecretBox(self.key) + + # calc filename + bn = 'bp-%s.dat' % sha256(sha256(b'salty' + self.key).digest()).hexdigest()[-16:].lower() + self.filename = os.path.join(settings.DATA_FILES, bn) + + @staticmethod + def new_secret(): + # rotate key + return os.urandom(32) + + def open(self, key): + # Given a private key (via storage locker) open a Nacl secret box + # and use that for the data. + self.set_secret(key) + + try: + with open(self.filename, 'rb') as fp: + d = self.box.decrypt(fp.read()) + d = json_loads(d) + except FileNotFoundError: + logging.info("%s: not found (probably fine)" % self.filename) + return True + + self.update(d) + + # copy a setting to status (XXX feels wrong) + from status import STATUS + STATUS.tor_enabled = self.get('tor_enabled', False) + + logging.info(f"Got bunker settings from: {self.filename}") + + def save(self): + fn = self.filename + tmp = fn + '.tmp' + with open(tmp, 'wb') as fp: + d = json_dumps(dict(self)).encode('utf8') + d = self.box.encrypt(d) + fp.write(d) + + os.rename(tmp, fn) + logging.info(f"Saved bunker settings to: {fn}") + + self.notify_watchers() + + def delete_file(self): + # useful when changing keys; old file won't be readable + try: + os.unlink(self.filename) + logging.info(f"Deleted bunker settings in: {self.filename}") + except: + pass + + def is_default_secret(self): + return self.key == settings.PLACEHOLDER_KEY + + +# EOF diff --git a/policy.py b/policy.py new file mode 100644 index 0000000..c573760 --- /dev/null +++ b/policy.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python +# +# policy.py -- code which knows various details about HSM policy as defined by Coldcard. +# +import re, logging +from decimal import Decimal +from objstruct import ObjectStruct +from persist import BP, settings +from base64 import b64encode, b64decode + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +def invalid_pincode(code): + return (not code) or (len(code) != 6) or (not code.isdigit()) + +def web_cleanup(p): + # takes policy details from Vue/Semantic/web browser format into proper JSON-able dict + # - final product should serialize into something the Coldcard will accept + + def relist(n): + # split on spaces or commas, assume values don't have either; trim whitespace + if n is None: return n + return [i for i in re.split(r' |,|\n', n) if i] + + for fn in ['msg_paths', 'share_xpubs', 'share_addrs']: + p[fn] = relist(p.get(fn, None)) + + p.period = int(p.period) if p.period else None + + for rule in p.rules: + for fn in ['whitelist', 'users']: + rule[fn] = relist(rule[fn]) + + # change from BTC to satoshis (send as string here) + for fn in ['per_period', 'max_amount']: + if rule[fn] is not None: + v = Decimal(rule[fn]) + rule[fn] = int(v * Decimal('1E8')) + + # text to number + if not rule.users: + rule.pop('min_users') + else: + rule.min_users = len(rule.users) if rule.min_users == 'all' else int(rule.min_users) + + if p.pop('ewaste_enable', False): + p.boot_to_hsm = 'xyzzy' # impossible to enter + assert invalid_pincode(p.boot_to_hsm) + else: + p.boot_to_hsm = p.get('boot_to_hsm') or None + if p.boot_to_hsm: + assert not invalid_pincode(p.boot_to_hsm), \ + "Boot to HSM code must be 6 numeric digits." + + return p + +def web_cookup(proposed): + # converse of above: take Coldcard policy file, and rework it so + # Vue can display on webpage + + p = ObjectStruct.promote(proposed) + + def unlist(n): + if not n: return '' + return ','.join(n) + + for fn in ['msg_paths', 'share_xpubs', 'share_addrs']: + p[fn] = unlist(p.get(fn)) + + for rule in p.rules: + for fn in ['whitelist', 'users']: + rule[fn] = unlist(rule.get(fn)) + + for fn in ['per_period', 'max_amount']: + if rule[fn] is not None: + rule[fn] = str(Decimal(rule[fn]) / Decimal('1E8')) + + if 'min_users' not in rule: + rule.min_users = 'all' + else: + rule.min_users = str(rule.min_users) + + if ('boot_to_hsm' in p) and p.boot_to_hsm and invalid_pincode(p.boot_to_hsm): + p.ewaste_enable = True + else: + p.ewaste_enable = False + + return p + + +def desensitize(policy): + # remove the most sensitive stuff in the policy. + bk = policy.copy() + bk.pop('set_sl', None) + bk.pop('allow_sl', None) + bk.pop('boot_to_hsm', None) + + return bk + +def decode_sl(xk): + # Unpack what we saved into the Storage Locker + # - 32 bytes of nacl secret box for BunkerPersistance, plus "Bunk" prefix => 36 bytes + # - base64 encoded => 48 bytes (and has no padding) + assert len(xk) == 48, repr(xk) + xk = b64decode(xk) + assert xk[0:4] == b'Bunk' + rv = xk[4:] + assert len(rv) == 32 + + return rv + +def update_sl(proposed): + # We control the set_sl/allow_sl values solely for bunker purposes (sl=storage locker) + + # try to use any value already provided (but unlikely) + xk = proposed.get('set_sl', None) or None + if xk: + try: + xk = decode_sl(xk) + except: + logging.error("Unable to decode existing storage locker; replacing", exc_info=1) + xk = None + + if not xk: + if not BP.key or BP.is_default_secret(): + # pick a new key + logging.info("Making new secret for holding Bunker settings") + xk = BP.new_secret() + else: + # keep using same key + xk = BP.key + + assert len(xk) == 32 + proposed['set_sl'] = b64encode(b'Bunk' + xk).decode('ascii') + + if xk != BP.key: + # re-use existing key, and switch over to using new/eixsting key + BP.delete_file() + BP.set_secret(xk) + BP.save() + else: + logging.info("Re-using old secret for holding Bunker settings") + + # simple fixed value for how many times we can re-read the storage locker + proposed['allow_sl'] = 13 if BP.get('allow_reboots', True) else 1 + + +# EOF diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c1062a9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +# See also setup.py install_requires +# +stem==1.8.0 +aiohttp==3.6.2 +aiohttp-jinja2==1.2.0 +ckcc-protocol>=1.0.0 +pynacl==1.3.0 +aiohttp_session +click +pendulum +pyyaml +Pillow +pytest +requests[socks] diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..e4d594e --- /dev/null +++ b/setup.py @@ -0,0 +1,43 @@ +# (c) Copyright 2020 by Coinkite Inc. This file is part of Coldcard +# and is covered by GPLv3 license found in COPYING. +# +# based on +# +# To use this, install with: +# +# pip install --editable . + +from setuptools import setup + +with open("README.md", "r") as fh: + long_description = fh.read() + +setup( + name='bunker', + version='0.1', + python_requires='>=3.7.0', + url='https://github.com/Coldcard/ck-bunker', + author='Coinkite Inc.', + author_email='support@coinkite.com', + description="Submit PSBT files automatically to your Coldcard for signing", + long_description=long_description, + long_description_content_type="text/markdown", + install_requires=[ # see requirements.txt tho. + 'Click', + 'stem', + 'aiohttp', + 'aiohttp-jinja2', + 'ckcc-protocol>=1.0.0', + ], + entry_points=''' + [console_scripts] + ck-bunker=main:main + ''', + classifiers=[ + 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', + 'Operating System :: POSIX :: Linux', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: MacOS :: MacOS X', + ], +) + diff --git a/static/ext/README.md b/static/ext/README.md new file mode 100644 index 0000000..95edb9a --- /dev/null +++ b/static/ext/README.md @@ -0,0 +1,7 @@ + +## Background + +- Semantic UI parts taken from v2.4.1 at + +- one long path is remapped (rather than edit min.css files) + /static/ext/themes/default/assets/fonts/ => /static/semantic-fonts diff --git a/static/ext/base64js.min.js b/static/ext/base64js.min.js new file mode 100644 index 0000000..b0279c0 --- /dev/null +++ b/static/ext/base64js.min.js @@ -0,0 +1 @@ +(function(r){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=r()}else if(typeof define==="function"&&define.amd){define([],r)}else{var e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof self!=="undefined"){e=self}else{e=this}e.base64js=r()}})(function(){var r,e,n;return function(){function d(a,f,i){function u(n,r){if(!f[n]){if(!a[n]){var e="function"==typeof require&&require;if(!r&&e)return e(n,!0);if(v)return v(n,!0);var t=new Error("Cannot find module '"+n+"'");throw t.code="MODULE_NOT_FOUND",t}var o=f[n]={exports:{}};a[n][0].call(o.exports,function(r){var e=a[n][1][r];return u(e||r)},o,o.exports,d,a,f,i)}return f[n].exports}for(var v="function"==typeof require&&require,r=0;r0){throw new Error("Invalid string. Length must be a multiple of 4")}var n=r.indexOf("=");if(n===-1)n=e;var t=n===e?0:4-n%4;return[n,t]}function f(r){var e=c(r);var n=e[0];var t=e[1];return(n+t)*3/4-t}function h(r,e,n){return(e+n)*3/4-n}function i(r){var e;var n=c(r);var t=n[0];var o=n[1];var a=new d(h(r,t,o));var f=0;var i=o>0?t-4:t;var u;for(u=0;u>16&255;a[f++]=e>>8&255;a[f++]=e&255}if(o===2){e=v[r.charCodeAt(u)]<<2|v[r.charCodeAt(u+1)]>>4;a[f++]=e&255}if(o===1){e=v[r.charCodeAt(u)]<<10|v[r.charCodeAt(u+1)]<<4|v[r.charCodeAt(u+2)]>>2;a[f++]=e>>8&255;a[f++]=e&255}return a}function s(r){return u[r>>18&63]+u[r>>12&63]+u[r>>6&63]+u[r&63]}function l(r,e,n){var t;var o=[];for(var a=e;ai?i:f+a))}if(t===1){e=r[n-1];o.push(u[e>>2]+u[e<<4&63]+"==")}else if(t===2){e=(r[n-2]<<8)+r[n-1];o.push(u[e>>10]+u[e>>4&63]+u[e<<2&63]+"=")}return o.join("")}},{}]},{},[])("/")}); diff --git a/static/ext/jquery-3.1.1.min.js b/static/ext/jquery-3.1.1.min.js new file mode 100644 index 0000000..4c5be4c --- /dev/null +++ b/static/ext/jquery-3.1.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v3.1.1 | (c) jQuery Foundation | jquery.org/license */ +!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.1.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,C=/^.[^:#\[\.,]*$/;function D(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):C.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return J(a,"nextSibling")},prev:function(a){return J(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/[^\x20\t\r\n\f]+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(O(a,g.done(h(c)).resolve,g.reject),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener("DOMContentLoaded",R), +a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length\x20\t\r\n\f]+)/i,ka=/^$|\/(?:java|ecma)script/i,la={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};la.optgroup=la.option,la.tbody=la.tfoot=la.colgroup=la.caption=la.thead,la.th=la.td;function ma(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function na(a,b){for(var c=0,d=a.length;c-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=ma(l.appendChild(f),"script"),j&&na(g),c){k=0;while(f=g[k++])ka.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var qa=d.documentElement,ra=/^key/,sa=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ta=/^([^.]*)(?:\.(.+)|)/;function ua(){return!0}function va(){return!1}function wa(){try{return d.activeElement}catch(a){}}function xa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)xa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=va;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(qa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(K)||[""],j=b.length;while(j--)h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||"").match(K)||[""],j=b.length;while(j--)if(h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i\x20\t\r\n\f]*)[^>]*)\/>/gi,za=/\s*$/g;function Da(a,b){return r.nodeName(a,"table")&&r.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a:a}function Ea(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Fa(a){var b=Ba.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ga(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c1&&"string"==typeof q&&!o.checkClone&&Aa.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ia(f,b,c,d)});if(m&&(e=pa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(ma(e,"script"),Ea),i=h.length;l")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=ma(h),f=ma(a),d=0,e=f.length;d0&&na(g,!i&&ma(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ja(this,a,!0)},remove:function(a){return Ja(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.appendChild(a)}})},prepend:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(ma(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!za.test(a)&&!la[(ja.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c1)}});function Ya(a,b,c,d,e){return new Ya.prototype.init(a,b,c,d,e)}r.Tween=Ya,Ya.prototype={constructor:Ya,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=Ya.propHooks[this.prop];return a&&a.get?a.get(this):Ya.propHooks._default.get(this)},run:function(a){var b,c=Ya.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ya.propHooks._default.set(this),this}},Ya.prototype.init.prototype=Ya.prototype,Ya.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Ya.propHooks.scrollTop=Ya.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=Ya.prototype.init,r.fx.step={};var Za,$a,_a=/^(?:toggle|show|hide)$/,ab=/queueHooks$/;function bb(){$a&&(a.requestAnimationFrame(bb),r.fx.tick())}function cb(){return a.setTimeout(function(){Za=void 0}),Za=r.now()}function db(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ba[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function eb(a,b,c){for(var d,e=(hb.tweeners[b]||[]).concat(hb.tweeners["*"]),f=0,g=e.length;f1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?ib:void 0)), +void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),ib={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=jb[b]||r.find.attr;jb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=jb[g],jb[g]=e,e=null!=c(a,b,d)?g:null,jb[g]=f),e}});var kb=/^(?:input|select|textarea|button)$/i,lb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):kb.test(a.nodeName)||lb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function mb(a){var b=a.match(K)||[];return b.join(" ")}function nb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,nb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,nb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,nb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=nb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(nb(c))+" ").indexOf(b)>-1)return!0;return!1}});var ob=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(ob,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:mb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,"events")||{})[b.type]&&V.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var tb=/\[\]$/,ub=/\r?\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)xb(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ia.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,"\r\n")}}):{name:b.name,value:c.replace(ub,"\r\n")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\/\//,Fb={},Gb={},Hb="*/".concat("*"),Ib=d.createElement("a");Ib.href=qb.href;function Jb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:"GET",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Hb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+"").replace(Eb,qb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(K)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+"//"+Ib.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(yb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,"$1"),n=(sb.test(f)?"&":"?")+"_="+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Hb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&"withCredentials"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;if(o.cors||Pb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r(" + diff --git a/static/html5shiv.js b/static/html5shiv.js new file mode 100644 index 0000000..d074da7 --- /dev/null +++ b/static/html5shiv.js @@ -0,0 +1,301 @@ +/** +* @preserve HTML5 Shiv v3.7.0 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed +*/ +;(function(window, document) { +/*jshint evil:true */ + /** version */ + var version = '3.7.0'; + + /** Preset options */ + var options = window.html5 || {}; + + /** Used to skip problem elements */ + var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; + + /** Not all elements can be cloned in IE **/ + var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; + + /** Detect whether the browser supports default html5 styles */ + var supportsHtml5Styles; + + /** Name of the expando, to work with multiple documents or to re-shiv one document */ + var expando = '_html5shiv'; + + /** The id for the the documents expando */ + var expanID = 0; + + /** Cached data for each document */ + var expandoData = {}; + + /** Detect whether the browser supports unknown elements */ + var supportsUnknownElements; + + (function() { + try { + var a = document.createElement('a'); + a.innerHTML = ''; + //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles + supportsHtml5Styles = ('hidden' in a); + + supportsUnknownElements = a.childNodes.length == 1 || (function() { + // assign a false positive if unable to shiv + (document.createElement)('a'); + var frag = document.createDocumentFragment(); + return ( + typeof frag.cloneNode == 'undefined' || + typeof frag.createDocumentFragment == 'undefined' || + typeof frag.createElement == 'undefined' + ); + }()); + } catch(e) { + // assign a false positive if detection fails => unable to shiv + supportsHtml5Styles = true; + supportsUnknownElements = true; + } + + }()); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a style sheet with the given CSS text and adds it to the document. + * @private + * @param {Document} ownerDocument The document. + * @param {String} cssText The CSS text. + * @returns {StyleSheet} The style element. + */ + function addStyleSheet(ownerDocument, cssText) { + var p = ownerDocument.createElement('p'), + parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; + + p.innerHTML = 'x'; + return parent.insertBefore(p.lastChild, parent.firstChild); + } + + /** + * Returns the value of `html5.elements` as an array. + * @private + * @returns {Array} An array of shived element node names. + */ + function getElements() { + var elements = html5.elements; + return typeof elements == 'string' ? elements.split(' ') : elements; + } + + /** + * Returns the data associated to the given document + * @private + * @param {Document} ownerDocument The document. + * @returns {Object} An object of data. + */ + function getExpandoData(ownerDocument) { + var data = expandoData[ownerDocument[expando]]; + if (!data) { + data = {}; + expanID++; + ownerDocument[expando] = expanID; + expandoData[expanID] = data; + } + return data; + } + + /** + * returns a shived element for the given nodeName and document + * @memberOf html5 + * @param {String} nodeName name of the element + * @param {Document} ownerDocument The context document. + * @returns {Object} The shived element. + */ + function createElement(nodeName, ownerDocument, data){ + if (!ownerDocument) { + ownerDocument = document; + } + if(supportsUnknownElements){ + return ownerDocument.createElement(nodeName); + } + if (!data) { + data = getExpandoData(ownerDocument); + } + var node; + + if (data.cache[nodeName]) { + node = data.cache[nodeName].cloneNode(); + } else if (saveClones.test(nodeName)) { + node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); + } else { + node = data.createElem(nodeName); + } + + // Avoid adding some elements to fragments in IE < 9 because + // * Attributes like `name` or `type` cannot be set/changed once an element + // is inserted into a document/fragment + // * Link elements with `src` attributes that are inaccessible, as with + // a 403 response, will cause the tab/window to crash + // * Script elements appended to fragments will execute when their `src` + // or `text` property is set + return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node; + } + + /** + * returns a shived DocumentFragment for the given document + * @memberOf html5 + * @param {Document} ownerDocument The context document. + * @returns {Object} The shived DocumentFragment. + */ + function createDocumentFragment(ownerDocument, data){ + if (!ownerDocument) { + ownerDocument = document; + } + if(supportsUnknownElements){ + return ownerDocument.createDocumentFragment(); + } + data = data || getExpandoData(ownerDocument); + var clone = data.frag.cloneNode(), + i = 0, + elems = getElements(), + l = elems.length; + for(;i " + action); + + window.WEBSOCKET('api', req); + }); + + $('.js-api-clear-all').on('click', function() { + $('input[type=checkbox].js-api-picker').prop('checked', false); + }); + $('.js-api-set-all').on('click', function() { + $('input[type=checkbox].js-api-picker').prop('checked', true); + }); + + $('body').on('click', '.js-clickable', function(evt) { + var el = $(this) + var target = el.data("href"); + if(!target) return; + + + // special case cell, probably has input + var cell = $(evt.target); + if(cell.hasClass('js-not-clickable')) return; + var td = $(evt.target).parents('td'); + if(td && td.hasClass('js-not-clickable')) return; + + var tabname = el.data("tabname"); + if(tabname) { + window.open(target, tabname); + } else { + window.location = target; + } + }); + + + // Semantic UI modules that we use + $('.ui.dropdown').dropdown({fullTextSearch: true}); + $('.ui.checkbox').checkbox(); + $('.ui.accordion').accordion(); + $('.ui.popup').popup(); + $('.js-long-popup').popup({ inline: true }); + + $('.message .close').on('click', function() { + $(this) + .closest('.message') + .transition('slide down') + ; + }); + + + if(window.WEBSOCKET_URL) { + + var WS = new WebSocket( (location.protocol == 'http:' ? 'ws://' : 'wss://') + + location.host + window.WEBSOCKET_URL); + var keepalive = 0; + + WS.onopen = function(e) { + + console.log("websocket ready"); + keepalive = window.setInterval(function() { + WS.send(JSON.stringify({_ping: 1})); + }, 10000); + + + WS.send(JSON.stringify({action: '_connected', args: [window.location.pathname]})); + } + + WS.onmessage = function(e) { + var r = JSON.parse(e.data); + if(r.keepalive) return; + + if(r.show_modal) { + // show a modal + var el = $(r.selector); + el.find('.content').html(r.html); + el.modal('show'); + } else if(r.html && r.selector) { + // XXX bad idea, delete? + var el = $(r.selector); + if(el) el.html(r.html); + } + if(r.show_flash_msg) { + // update content in a message and show it + var el = $('#js-flash-msg'); + + el.find('.js-content').text(r.show_flash_msg); + + if(!el.transition('is visible')) { + el.transition('slide down'); + } + } + if(r.redirect) { + location.href = r.redirect; + } + if(r.reload) { + setTimeout(function() { location.reload() }, 100); + } + if(r.local_download) { + // trigger download/save-as to user's system + data = r.local_download.data + if(r.is_b64) { + data = base64js.fromByteArray(data); + } + download(r.local_download.filename, data) + } + + // send data back to VUE code + if(r.vue_app_cb) { + window.vue_app_cb(r.vue_app_cb) + } + + if(r.cb) { + // obsolete + window.ws_cb(r) + } + }; + function done(e) { + // show we are broken. + console.log("websocket broken"); + window.clearInterval(keepalive); + $('#ws_fail_msg').show(); + $('.ui.main.container input,select').attr('disabled', true); + $('.field').addClass('disabled'); + } + WS.onerror = done; + WS.onclose = done; + + window.WEBSOCKET = function(action) { // accepts varargs + let args = Array.prototype.slice.call(arguments, 1); + WS.send(JSON.stringify({action: action, args: args})); + } + } + +}); + +function download(filename, text) { +// from + + var element = document.createElement('a'); + element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); + element.setAttribute('download', filename); + + element.style.display = 'none'; + document.body.appendChild(element); + + element.click(); + + document.body.removeChild(element); +} + diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..451288f --- /dev/null +++ b/static/style.css @@ -0,0 +1,142 @@ +body { + background-color: #FFFFFF; + display: flex; + min-height: 100vh; + flex-direction: column; +} +.ui.menu .item img.logo { + margin-right: 1.5em; +} + +.main.container { + margin-top: 6em; +} + +@media only screen and (max-width: 767px) { + .main.container { + margin-top: 13em; + } +} + +.main-content-wrapper { + margin-top: 7em; + flex: 1; +} +.ui.menu .item img.logo { + margin-right: 1.5em; +} + +.ui.footer.segment { + margin: 9em 0em 0em; +} + +/* mobile hacks */ +@media only screen and (max-width: 767px) { + .seg7-container { + } + .seg7-row { + font-size: 2.5em; + } + .indicators { + font-size: 0.5em; + width: 2em; + margin-top: -5.5em; + } +} + +.js-expr-help-btn { + margin-left: 0.10em; + cursor: pointer; +} + +/* compress search results */ +.js-key-search-results { + overflow-y: auto; + max-height: 500px; +} + +.ui.category.search >.results .category .result { + padding: 2px 12px; +} +.ui.search>.results .result .title { + padding: 0px; +} + +a.extlink { + color: #4d4d4d; +} +.inverted a.extlink { + color: #eee; +} + +/* accordion headings, make big, more like H2 they are */ +.ui.accordion .title.bigger { + font-size: 1.8em !important; +} +.ui.accordion span.my_sub { + font-size: 60%; + margin-left: 2em; + float: right; + margin: 9px 0 0 0 ; +} + +hr.my_hr { + border-color: rgba(255,255,255,.5); +} + +input.inputfile { + width: 0.1px; + height: 0.1px; + opacity: 0; + overflow: hidden; + position: absolute; + z-index: -1; +} + + +.tt-font { + font-family: courier !important; +} + +.tt-font-small { + font-family: courier !important; + font-size: 13px !important; +} + + +pre.wordwrap { + white-space: pre-wrap; +} + +/* keep at bottom */ +/* see https://stackoverflow.com/questions/36186831 */ +[v-cloak] { + display: none !important; +} + +.bignum { + font-size: 180%; + line-height: 160%; +} + +.btcnum { + font-size: 120%; + line-height: 150%; +} + +code.sha256 { + /*border: #ccc solid 0.5px; + border-radius: 3px; */ + padding: 2px 6px; + font-weight: 600; +} + +input.width-fix { + width: 12em !important; +} + +/* Firefox bugfixes */ +.ui.toggle.checkbox label { + cursor: pointer; +} + diff --git a/status.py b/status.py new file mode 100644 index 0000000..c83f76f --- /dev/null +++ b/status.py @@ -0,0 +1,116 @@ +# +# Store and watch all **status** values in system. +# +import sys, logging, asyncio +from pprint import pprint, pformat +from decimal import Decimal +from chrono import NOW +from objstruct import ObjectStruct +from hashlib import sha256 +from copy import deepcopy +from utils import WatchableMixin + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +class SystemStatus(WatchableMixin, ObjectStruct): + + def __init__(self): + # define all values here. keep simple, small! + # - values must be JSON-able. + super(SystemStatus, self).__init__() + + self.connected = False + self.serial_number = None + + #self.xfp = None + + self.hsm = dict(users=[], wallets=[]) # short for "hsm_status" + self.is_testnet = False + + # storage locker has been read ok. + self.sl_loaded = False + + # user doesn't want Tor regardless of other settings (also disables login process) + self.force_local_mode = False + + # we are in setup mode + self.setup_mode = False + + # PSBT related + self._pending_psbt = None # raw binary + self.psbt_hash = None # hex digits (sha256) + self.psbt_size = None # size of binary + self.local_code = None # string of 6 digits + self.psbt_preview = None # text + self.busy_signing = False + + # tor related + self.tord_good = False # local tord control connection good + self.onion_addr = None # our present onion addr, if any + self.tor_enabled = False # config calls for tor (ie. BP['tor_enabled']) + + # list of structs about creditials given by remote users + self.pending_auth = [] + + def reset_pending_auth(self): + # clear and setup pending auth list + from persist import BP + + # make a list of users that might need to auth + ul = self.hsm.get('users') + if not ul: + if BP.get('policy'): + ul = set() + for r in BP['policy'].rules: + ul.union(r.users) + ul = list(sorted(ul)) + + # they might have picked privacy over UX, so provide some "slots" + # regardless of above. + if not ul: + ul = ['' for i in range(5)] + + # construct an obj for UX purposes, but keep the actual secrets separate + self.pending_auth = [ObjectStruct(name=n, has_name=bool(n), + has_guess='', totp=0) for n in ul] + self._auth_guess = [None]*len(ul) + + + def clear_psbt(self): + # wipe knowledge of PSBT + self._pending_psbt = None + self.psbt_hash = None + self.psbt_size = None + self.local_code = None + self.psbt_preview = None + + def import_psbt(self, psbt): + from ckcc.utils import calc_local_pincode + from utils import cleanup_psbt + from binascii import b2a_hex + + self.clear_psbt() + + self._pending_psbt = cleanup_psbt(psbt) + + self.psbt_size = len(self._pending_psbt) + + hh = sha256(self._pending_psbt).digest() + self.psbt_hash = b2a_hex(hh).decode('ascii') + + # local PIN code will be wrong/stale now. + if self.hsm and self.hsm.get('next_local_code'): + self.local_code = calc_local_pincode(hh, self.hsm.next_local_code) + + logging.info("Imported PSBT with hash: " + self.psbt_hash) + + def as_dict(self): + # we stream changes to web clients, so provide JSON + return dict((k, deepcopy(self[k])) + for k in self.keys() if k[0] != '_' and not callable(self[k])) + + +# singleton +STATUS = SystemStatus() + +# EOF diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..f96202f --- /dev/null +++ b/templates/base.html @@ -0,0 +1,70 @@ + + + + + + + + + {% block page_title %} + CK Bunker + {% endblock page_title %} + + +{% block extra_page_meta %} +{% endblock extra_page_meta %} + +{# TODO: add integretry values to these, "just in case" #} +{# #} + + + + + + {# leave in dev mode #} + +{% block extra_head_code %} +{% endblock extra_head_code %} + + + + + + +{% block head_style %} +{% endblock head_style %} + + + + +{% block body %}{% endblock body %} + + +{% if ws_url %} + + + + + +{% endif %} + +{% block even_more_js %}{% endblock %} +{% block endscript %}{% endblock %} + + diff --git a/templates/basic.html b/templates/basic.html new file mode 100644 index 0000000..5cb6467 --- /dev/null +++ b/templates/basic.html @@ -0,0 +1,2 @@ +{% extends "base.html" %} + diff --git a/templates/bunker/index.html b/templates/bunker/index.html new file mode 100644 index 0000000..c1ea101 --- /dev/null +++ b/templates/bunker/index.html @@ -0,0 +1,182 @@ +{% extends "navpage.html" %} + +{% from "macros.html" import message_box, bool_choice, amount, info_hover, + text_field, bool_choice, wrap_field %} + +{% block main_body %} +
+ + {% call message_box('Tor Daemon Missing', '!STATUS.tord_good && !force_local_mode', + icon='warning sign') %} + The Bunker cannot communicate with tord (Tor daemon) which we need. It should + be available on ports 9051 and 9151 of localhost. + {% endcall %} + +

Bunker Setup & Configuration

+ +
+ + + + {% call bool_choice('allow_reboots', None) %} + + {% endcall %} + +
+ + +
+
+
+ +
+
+ +   + +
+
+ + + {% call message_box('Write These Down!', '!force_local_mode', icon='edit', closable=1) %} + We recommend you make note of the the onion address and/or master password. + {% endcall %} + + {% if STATUS.setup_mode and not STATUS.force_local_mode %} + {% call message_box('No Tor Connections during Setup Mode', 'tor_enabled && !STATUS.onion_addr && STATUS.tor_enabled', closable=1) %} +
+
+ To enable Tor (onion) connections, either + restart bunker in normal mode (it is in 'setup mode' now) or use this button. +
+
+ +
+
+ {% endcall %} + {% endif %} + + {% call message_box('Visit on Tor', '!using_onion && STATUS.onion_addr', icon='external link', closable=1) %} + {% raw %} + Go to {{STATUS.onion_addr}} + {% endraw %} + {% endcall %} + + +
+{% endblock main_body %} + + +{% block endscript %} + + + + +{% endblock %} diff --git a/templates/help.html b/templates/help.html new file mode 100644 index 0000000..8f5a8b4 --- /dev/null +++ b/templates/help.html @@ -0,0 +1,9 @@ +{% extends "navpage.html" %} + +{% block main_body %} + +

Help

+ +

Background

+ +{% endblock %} diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..60eda0f --- /dev/null +++ b/templates/login.html @@ -0,0 +1,2 @@ +{% extends "basic.html" %} + diff --git a/templates/macros.html b/templates/macros.html new file mode 100644 index 0000000..aad3280 --- /dev/null +++ b/templates/macros.html @@ -0,0 +1,221 @@ + +{% macro ws_fail_message() %} + +{% endmacro %} + +{% macro flash_msg_holder() %} + + +{% endmacro %} + +{# these values are mirroring real config values, must share same name; use in JS #} +{% macro cfg_mirrors(fld_names) %} + {% for fn in fld_names %} + {{fn}}: {{ CFG.get(fn)|tojson }}, + {% endfor %} +{% endmacro %} + +{% macro select_field(title, cfgname, values, labels, default_idx=0, numeric=False, width='eight', hide_label=False) %} +
+ {% if not hide_label %}{% endif %} + +
+{% endmacro %} + + +{% macro needs_coldcard_message() %} +
+
+ +
+
+ Coldcard USB Not Connected +
+

This feature needs a USB connection to the Coldcard. Please + check the USB cable is connected, and verify the Coldcard + is unlocked with the master PIN code.

+
+
+
+{% endmacro %} + +{% macro message_box(title, show_if, icon='warning sign', closable=False) %} +
+ {% if closable %} {% endif %} + +
+
{{ title }}
+

{{ caller() }}

+
+
+{% endmacro %} + +{% macro needs_coldcard_callout(dir='left') %} +
+ Coldcard not connected +
+{% endmacro %} + +{% macro select_field(title, cfgname, values, labels, default_idx=0, numeric=False, width='eight', hide_label=False) %} +
+ {% if not hide_label %}{% endif %} + +
+{% endmacro %} + +{% macro wrap_field(fldname, label, desc, disabled_if=None) %} +
+ {% if label %} + + {% endif %} + {{ caller() }} +
+{% endmacro %} + +{% macro amount(fldname, label, desc, placeholder="(any amount)", disabled_if=None) %} + {% call wrap_field(fldname, label, desc, disabled_if) %} +
+ +
{% raw %}{{ chain }}{% endraw %}
+
+ {% endcall %} +{% endmacro %} + +{% macro text_field(fldname, label, desc, placeholder="(not used)", extras="", rhs_label="tbd", disabled_if=None) %} + {% call wrap_field(fldname, label, desc, disabled_if) %} +
+ +
+ {{rhs_label|safe}} +
+
+ {% endcall %} +{% endmacro %} + +{% macro textarea(fldname, label, desc, placeholder, disabled_if=None, rows=1) %} + {% call wrap_field(fldname, label, desc, disabled_if) %} + + {% endcall %} +{% endmacro %} + +{% macro choice(fldname, label, desc, values=None, extras=[], multi=False, disabled_if=None, default_text='') %} + {% call wrap_field(fldname, label, desc, disabled_if) %} + + {% endcall %} +{% endmacro %} + +{% macro bool_choice(fldname, desc, disabled_if=None, style="toggle", fld_kls="field", readonly_if=None) %} +
+
+ + {% if not caller %} + + {% else %} + {{ caller() }} + {% endif %} +
+
+{% endmacro %} + + +{% macro subhead(tt) %} +

{{tt}}

+{% endmacro %} + +{% macro HR() %} +
+{% endmacro %} + +{% macro fileupload(label, change, kls="ui large button") %} + + +{% endmacro %} + +{% macro info_hover(msg) %} + + + +{% endmacro %} + +{% macro info_hover_long(pos=None) %} + + + + +{% endmacro %} diff --git a/templates/navpage.html b/templates/navpage.html new file mode 100644 index 0000000..e84831d --- /dev/null +++ b/templates/navpage.html @@ -0,0 +1,57 @@ +{% extends "base.html" %} +{% from "macros.html" import ws_fail_message, flash_msg_holder %} + +{% block body %} + + +{% block uncontained_body %} + {% block pre_main_body %}{% endblock %} + +
+ {{ flash_msg_holder() }} + {{ ws_fail_message() }} + + {% block main_body %}{% endblock %} +
+{% endblock %} + +{% block footer %} +
+
+
+
+ © 2020 by  {{ "https://coinkite.com" | extlink("Coinkite Inc.") }} +
+
+ {{ ''|link_to_explorer }} +
+
+ {{ "https://coldcardwallet.com/" | extlink("Coldcard Website") }} +
+
+
+
+{% endblock footer %} + + +{% endblock body %} diff --git a/templates/setup/hsm-rule-component.html b/templates/setup/hsm-rule-component.html new file mode 100644 index 0000000..70f4d0f --- /dev/null +++ b/templates/setup/hsm-rule-component.html @@ -0,0 +1,50 @@ +{# implement a "vue component" for individual HSM rules + +limitation: + - dropdown's do not track changes to the data, but the other direction (user makes choice) + does get into the vue data model + - other controls are bi-directional +#} + + + + + diff --git a/templates/setup/hsm-rule.html b/templates/setup/hsm-rule.html new file mode 100644 index 0000000..456ad56 --- /dev/null +++ b/templates/setup/hsm-rule.html @@ -0,0 +1,39 @@ +{% from "macros.html" import amount, textarea, choice, bool_choice %} + +{% macro mu_radio(label, desc) %} + {{ choice('rule.min_users', label, desc, extras=[('', "(n/a)"), (1, 'Any One'), (2, 'Two Users'), (3, 'Three Users'), ('all', 'All Users')], disabled_if="rule.users.length == 0") }} +{% endmacro %} + + +
+
+ {{amount('rule.max_amount', "Max Amount", + "Max amount allowed per single transaction. Leave blank for no limit.")}} + {{amount('rule.per_period', "Per-Period Amount", + "Max amount in one period. Leave blank for no period limit.", + disabled_if="no_period")}} +
+ +
+ {{textarea('rule.whitelist', "Destination Whitelist", + "Can only send to these specific payment addresses.", + "(base58 or segwit addresses)")}} + {{ choice('rule.wallet', "Multisig Wallet Name", + "Rule only applies to a specific multisig wallet, or only single-signer (not multisig), or all wallets.", + "wallet_list", + extras = [('', '(any wallet)'), ('1', '(single signer wallet)')], + disabled_if="wallet_list.length==0") }} +
+ +
+ {{ choice('rule.users', "Authorizing Users", + "These users must authenticate to allow the transaction, or blank for no user auth.", + "user_list", multi=1, default_text="(no user auth)")}} + {{ mu_radio("Minimum Users Needed", "How many of those users are required?") }} +
+ + {{ bool_choice('rule.local_conf', "Unique 6-digit code (per transaction) must be entered on Coldcard keypad.") }} + +
+ + diff --git a/templates/setup/index.html b/templates/setup/index.html new file mode 100644 index 0000000..b2e9048 --- /dev/null +++ b/templates/setup/index.html @@ -0,0 +1,268 @@ +{% extends "navpage.html" %} +{% from "macros.html" import needs_coldcard_callout %} +{% from "macros.html" import fileupload, bool_choice %} + +{% macro accord(title, subtitle, active=False, pill=None) %} +
+ + {{ title }} + + {% if pill %} +
{{pill}}
+ {% endif %} + + {{subtitle}} +    +
+
+
+
+ {{ caller() }} +
+{% endmacro %} + + + +{% block main_body %} +{% raw %} +
+ +
+ +
+
+ HSM Already Enabled +
+

+ Further changes to the policy are not possible, because + the Coldcard is already in HSM mode. +

+ To exit HSM mode, the Coldcard must be power-cycled. +

+
+
+ +
+ +
+
+ Existing Policy +
+ +

+ Your Coldcard already holds a policy file from a previous setup. Click here + to enable that policy and start the Coldcard in HSM mode. On-device + confirmation will be required. +

+ +

+ +

+
+
+{% endraw %} + +
+ +{% include 'setup/rules.html' with context %} +{% include 'setup/users.html' with context %} +{% include 'setup/paths.html' with context %} +{% include 'setup/misc.html' with context %} +{# include 'setup/onion.html' with context #} + +
+ +
+
+ +
+ + {{ needs_coldcard_callout() }} +
+ {{ bool_choice('wants_copy', "Download (sanitized) copy", style="") }} +
+
+ +
+
+ + {{ fileupload("Import Policy", 'import_policy($event)', 'ui large button') }} +
+

+ These policy files (JSON) contain sensitive information, including private key + for onion server and boot-to-HSM unlock code, when enabled. +

+
+
+ + +{% endblock main_body %} + + +{% block endscript %} + +{% include "setup/hsm-rule-component.html" with context %} + + + + +{% endblock %} diff --git a/templates/setup/misc.html b/templates/setup/misc.html new file mode 100644 index 0000000..9248e54 --- /dev/null +++ b/templates/setup/misc.html @@ -0,0 +1,58 @@ +{% from "macros.html" import bool_choice, textarea, subhead, text_field, HR %} + +{% call accord('Other Policy', 'Logging and other system-wide rules') %} +
+

Logging

+
+ {{ bool_choice('POLICY.must_log', "Fail transactions if we cannot log to MicroSD") }} + {{ bool_choice('POLICY.never_log', "Do not log anything, even if MicroSD is inserted") }} +
+ +{{HR()}} + +

Warnings

+ + {{ bool_choice('POLICY.warnings_ok', "Permit signing of transactions (PSBT) which have warnings (default: does not).") }} + +{{HR()}} + +

Privacy Vs. Easy of Use

+ {{ bool_choice('POLICY.priv_over_ux', "If you prefer privacy over convenience, this causes Coldcard to be more secretive and makes the Bunker harder to use, because both will store less data about policy, usernames, and derivation paths.") }} + +{{HR()}} +

Boot To HSM

+ +
+ {{ text_field('POLICY.boot_to_hsm', + "Coldcard will reboot directly to HSM mode, but will accept this 6-digit code to escape, if provided immediately.", + placeholder="(optional)", extras='pattern="[0-9]{6}" required minlength=6 maxlength=6 ', + rhs_label="6-digit code", disabled_if="POLICY.ewaste_enable") }} + {{ bool_choice('POLICY.ewaste_enable', "Do not accept any code. Always boot to HSM mode.") }} + {# bool_choice('POLICY.ewaste_enable', "Do not accept any code. Always stay in HSM mode and there is no way out. CAUTION: Even master PIN holder cannot change HSM policy nor escape HSM mode! Firmware upgrades are not possible.") #} +
+ +
+ +
+
+ Warning +
+

+ This setting is irreversible. + No changes to firmware, HSM policy, Coldcard settings will be possible—ever again. +
+ Not even the master PIN holder can change HSM policy nor escape HSM mode! Firmware upgrades are not possible. +

+
+
+ + + +{{HR()}} +

Notes

+ + {{ textarea('POLICY.notes', "Free-form text shown on Coldcard when approving HSM Policy.", + placeholder="(optional)", rows=3) }} +
+{% endcall %} + diff --git a/templates/setup/onion.html b/templates/setup/onion.html new file mode 100644 index 0000000..f814bb9 --- /dev/null +++ b/templates/setup/onion.html @@ -0,0 +1,36 @@ +{% from "macros.html" import amount, text_field, bool_choice, wrap_field %} + +{% call accord('Onion Address', 'Enable Tor access to the Bunker') %} +
+ +
+
+
+ + +
+
+ + {% call wrap_field(None, 'Tor Login Password', disabled_if="!enable_onion") %} +
+ + +
+ {% endcall %} + +
+ +
+{% raw %} + http://{{onion_addr}} +{% endraw %} + +
+ +
+ +
+ +{% endcall %} + diff --git a/templates/setup/paths.html b/templates/setup/paths.html new file mode 100644 index 0000000..008cc7c --- /dev/null +++ b/templates/setup/paths.html @@ -0,0 +1,50 @@ +{% from "macros.html" import textarea, subhead %} +{% call accord('Derivation Paths', 'For message signing & address generation', pill="ADVANCED") %} + +
+
+ + {{ subhead("Derivation Path Whitelists") }} + +

+ You may limit text message signing to specific derivation paths. Similarly, the Coldcard will + not share calculated addresses or derived XPUB values, unless whitelisted here. +

+ Leave blank to block corresponding feature. Multiple values maybe be given, + separated by spaces or commas. +

+ + + {{ textarea('POLICY.msg_paths', "Will only sign messages using indicated path(s)", + placeholder="(signing not be allowed)") }} +
+ +
+ + + +
Special Values +
any Allow any path. +
m/1/2/3/* Require that path but the last position is any value. +
m/1/2/3/*' Last position must be hardened. +
p2sh Allow P2SH (script) addresses for multisig wallets. +
+
+
+ +
+
+ {{ subhead("Other Whitelisted Derivation Paths") }} + +
+ + {{ textarea('POLICY.share_xpubs', "Share derived XPUB values on these paths (master xpub is always shared)", + placeholder="(xpub derivation not allowed)") }} + + {{ textarea('POLICY.share_addrs', "Share these derived addresses (ie. deposit addresses)", + placeholder="(address derivation not allowed)") }} +
+
+
+{% endcall %} + diff --git a/templates/setup/rules.html b/templates/setup/rules.html new file mode 100644 index 0000000..a0d70a9 --- /dev/null +++ b/templates/setup/rules.html @@ -0,0 +1,96 @@ +{% call accord('Spending Rules', 'When and how much can be sent out') %} + +{% from "macros.html" import subhead %} + +
+ + {{ subhead("Velocity Time Period") }} + +
+
+
+ +
+ minutes +
+
+
+ +{% raw %} +
+
+ = {{ period_hrs }} hours +
+
+{% endraw %} + +
+
+ + + + + + + + + +
+
+
+ +

+ Time period starts as soon as rule with a velocity limit is applied. + The total amount sent is tracked, for each rule independently, until the period ends. + All rules share the same time period for these velocity calculations. +

+ + {{ subhead("Rules") }} + +

+ Multiple spending rules can be defined. The first matching rule is applied + when a PSBT is considered, and its velocity limit is the one affected, so place + more restrictive rules first. All elements of the specific rule must be met + before it is applied. +

+

+ +

+ +
+

NOTE: You have no rules defined. It will not be possible to authorize transactions. +

+ + + +
+{% endcall %} + + + + + diff --git a/templates/setup/users.html b/templates/setup/users.html new file mode 100644 index 0000000..9528313 --- /dev/null +++ b/templates/setup/users.html @@ -0,0 +1,94 @@ +{% call accord('Users', 'Add and remove Coldcard users', active=False) %} + +
+
+
+ +

Add New Users

+

+ Add up to 30 user names here. These users can authorize + spending based on the specific rules where they are named. Verification of the user is + done via 2FA or passwords. +

+ +{% raw %} +
+
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + +
+ +
+ + {% endraw %} + {{ needs_coldcard_callout() }} + {% raw %} +
+
+ +
+ + + + + + + +
Existing Coldcard Users +
+    + {{name}} +
No users yet. +
+
+
+
+{% endraw %} +{% endcall %} + diff --git a/templates/tools/index.html b/templates/tools/index.html new file mode 100644 index 0000000..b869654 --- /dev/null +++ b/templates/tools/index.html @@ -0,0 +1,164 @@ +{% extends "navpage.html" %} +{% from "macros.html" import needs_coldcard_callout %} +{% from "macros.html" import needs_coldcard_message, subhead, bool_choice %} + +{% block main_body %} +
+ +{# needs_coldcard_message() #} + +
+

Text Message Signing

+ +
+ Message signing is disabled by your HSM policy so it's not possible to sign messages. +
+ +
+
+ + +
+ +
+
+ + + + {% if msg_paths %} + + {% endif %} +
+ +
+ +
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+ + {{ needs_coldcard_callout('top') }} +
+ + +
+ Signature & Address +
+ +
+ {# #} + +
+ +
+
+ +
+

Recovery Tool

+ +

This will provide a means for you to construct a PSBT + which moves all the funds the system can find on the blockchain + to a new address.

+ +
WIP
+
+ +
+

Address Generator

+ +

Use this tool to make deposit addresses for your Coldcard's wallets.

+ +
WIP
+
+ +
+{% endblock %} + +{% block endscript %} + +{% endblock %} diff --git a/templates/txn/index.html b/templates/txn/index.html new file mode 100644 index 0000000..616f5f0 --- /dev/null +++ b/templates/txn/index.html @@ -0,0 +1,380 @@ +{% extends "navpage.html" %} +{% from "macros.html" import needs_coldcard_message, subhead, bool_choice, info_hover, info_hover_long %} + +{% macro status_value(hdr) %} + {{hdr}} + + {{ caller() }} + + +{% endmacro %} + +{% block main_body %} +
+ +
+ +
+
+ HSM Not Enabled +
+

+ The Coldcard is not in HSM mode. + Typically, you should enable a spending policy before using this page, + but it is possible to upload and sign PSBT files as it is now. You will need to + approve each transaction on the Coldcard's screen. +

+
+
+ +{{ needs_coldcard_message() }} + +
+ +
+ + + + + + + + + +{% raw %} + + + + + + +
+ Approvals + + Refusals + + Period Ends + + Amount Spent +
+ {{ STATUS.hsm.approvals || 0 }} + + {{ STATUS.hsm.refusals || 0}} + + + + + {{ total_spent || '—' }} +{% endraw %} + {% call info_hover_long('bottom right') %} + {% raw %} +

+ No amounts spent in current period. +

+ + + + + +
Rule + Amount Spent +
#{{idx+1}} + {{ amt | btc_value }} +
+ {% endraw %} + {% endcall %} +
+ +
+
+ +

Transaction Signing

+ +
+ +
+
+ + +
+
+{% raw %} +
PSBT File
+ +

+ {{STATUS.psbt_size }} bytes, with + SHA256: {{STATUS.psbt_hash.substr(0, 6) }}⋯{{STATUS.psbt_hash.substr(64-6) }} +

+ +{% endraw %} + +
+ Transaction Preview +
+ + + {% raw %} + + +
{{STATUS.psbt_preview }}
+ + {% endraw %} + +
+ + +
+ +
+ + + + {% raw %} + + + + + + + + + {% endraw %} +
Authorizing User + One-Time Code or Password + {% call info_hover_long('top center') %} + Depending on your spending policy rules, all or none of these users may be + required to authorize spending. Leave blank those you are not using. + {% endcall %} +
Local Code + + {{STATUS.local_code}} + TBD — need PSBT first +{% endraw %} + {% call info_hover_long('top center') %} + When required, the local Coldcard operator should enter this 6-digit code, + before you press the button on this page. + {% endcall %} +{% raw %} +
{{pa.name}} + + + +
+
+ + +
+
+
No user authorization needed. +
+
+
+ + + +
+
+ + {{ subhead('Coldcard HSM Policy Summary') }} + + {% if policy_summary %} +

+ For your reference, here is the Coldcard's interpretation of + the HSM policy when it was approved and installed. +

+ +
{{- policy_summary -}}
+ {% else %} +

Not available. You have chosen privacy over user-experience.

+ {% endif %} +
+
+ + +
+{% endblock main_body %} + +{% block endscript %} + +{% endblock %} + +{% block extra_head_code %} + + +{% endblock extra_head_code %} diff --git a/torsion.py b/torsion.py new file mode 100644 index 0000000..7113f73 --- /dev/null +++ b/torsion.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python +# +# Interface to STEM and from that to Tord and the Tor network. +# +# Refs: +# - +# +import logging, asyncio +from utils import json_loads, json_dumps, Singleton +from concurrent.futures import ThreadPoolExecutor +from persist import settings +from status import STATUS + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +executor = ThreadPoolExecutor(max_workers=10) + +class TorViaStem(metaclass=Singleton): + def __init__(self): + self.controller = None + self.service = None + + async def startup(self): + # just test if we can see tord + await self.connect(raise_on_error=False) + + def get_current_addr(self): + # return onion address we are currently on, or None + if not self.service: + return None + return self.service.service_id + '.onion' + + async def connect(self, raise_on_error=True): + from stem.connection import connect + + if self.controller: + return self.controller + + def doit(): + self.controller = connect(control_port=('127.0.0.1', settings.TORD_PORT)) + + if self.controller: + logging.info("Tord version: " + str(self.controller.get_version())) + else: + logging.error("Unable to connect to local 'tord' server") + if raise_on_error: + raise RuntimeError("No local 'tord' server") + + + return self.controller + + loop = asyncio.get_running_loop() + rv = await loop.run_in_executor(executor, doit) + + STATUS.tord_good = bool(rv) + STATUS.notify_watchers() + + async def pick_onion_addr(self): + + c = await self.connect() + + def doit(): + # let Tor pick the key, since they don't document their tricky stuff + s = self.controller.create_ephemeral_hidden_service({80: 1}, + detached=False, + await_publication=False, key_content='ED25519-V3') + + rv = (s.service_id+'.onion', s.private_key) + + # kill it immediately + self.controller.remove_ephemeral_hidden_service(s.service_id) + + return rv + + loop = asyncio.get_running_loop() + return await loop.run_in_executor(executor, doit) + + async def stop_tunnel(self): + # hang up if running + if not self.service: + return + + def doit(): + if self.service: + logging.info(f"Disconnecting previous service at: {self.service.service_id}.onion") + self.controller.remove_ephemeral_hidden_service(self.service.service_id) + self.service = None + + STATUS.onion_addr = None + STATUS.notify_watchers() + + loop = asyncio.get_running_loop() + return await loop.run_in_executor(executor, doit) + + async def start_tunnel(self): + from persist import BP, settings + + c = await self.connect() + + def doit(): + if self.service: + logging.info(f"Disconnecting previous service at: {self.service.service_id}.onion") + self.controller.remove_ephemeral_hidden_service(self.service.service_id) + self.service = None + + # give Tor the key from earlier run + k = BP['onion_pk'] + s = self.controller.create_ephemeral_hidden_service({80: settings.PORT_NUMBER}, + detached=False, discard_key=True, + await_publication=True, key_type='ED25519-V3', key_content=k) + + addr = s.service_id+'.onion' + assert addr == BP['onion_addr'], f"Mismatch, got: {addr} not {BP.onion_addr} expected" + + self.service = s + + return addr + + loop = asyncio.get_running_loop() + addr = await loop.run_in_executor(executor, doit) + + STATUS.onion_addr = addr + STATUS.notify_watchers() + + +TOR = TorViaStem() + + +if __name__ == '__main__': + controller = connect() + + if not controller: + sys.exit(1) # unable to get a connection + + print('Your tord is version: %s' % controller.get_version()) + + #d = controller.get_hidden_service_descriptor('explorernuoc63nb.onion') + d = controller.get_hidden_service_descriptor('explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion') + print("obj = %r" % d) + print("pubkey = %r" % d.permanent_key) + print("published = %r" % d.published) + + service = controller.create_ephemeral_hidden_service({80: 5000}, await_publication = True, key_content = 'ED25519-V3') + print("Started a new hidden service with the address of %s.onion" % service.service_id) + + print('%s %s' % (service.private_key_type, service.private_key)) + + + controller.close() + +# EOF diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..0289158 --- /dev/null +++ b/utils.py @@ -0,0 +1,119 @@ +# (c) Copyright 2020 by Coinkite Inc. This file is part of Coldcard +# and is covered by GPLv3 license found in COPYING. +# +# utils.py +# +import json, struct, logging, asyncio +from binascii import b2a_hex +from objstruct import ObjectStruct +from decimal import Decimal + +B2A = lambda x: b2a_hex(x).decode('ascii') + +def xfp2str(xfp): + # Standardized way to show an xpub's fingerprint... it's a 4-byte string + # and not really an integer. Used to show as '0x%08x' but that's wrong endian. + return b2a_hex(struct.pack(' +# use like this: +# class Foo(metaclass=Singleton): ... +# +class Singleton(type): + _instances = {} + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] + +def setup_logging(level=logging.INFO, debug=True, syslog=False): + # get logging working for simple test code + # - also used for normal logging + + handlers = None + if syslog: + # this shows up in /var/log/user.log + from logging.handlers import SysLogHandler + handlers = [ SysLogHandler('/dev/log')] + + logging.basicConfig(format="%(asctime)-11s %(message)s", + datefmt="[%d/%m/%Y-%H:%M:%S]", level=level, handlers=handlers) + + # maybe? + #import warnings + #warnings.simplefilter("ignore") + + # kill log noise about _UnixReadPipeTransport + logging.getLogger('asyncio').setLevel(level=logging.WARN) + + # kill noise from STEM (tor wrapper) + from stem.util.log import get_logger as sgl + sgl().setLevel(level=logging.WARN) + + if 0: + # disable access logging + logging.getLogger('aiohttp.access').setLevel(level=logging.WARN) + +def cleanup_psbt(psbt): + from base64 import b64decode + from binascii import a2b_hex + import re + from hashlib import sha256 + + # we have the bytes, but might be encoded as hex or base64 inside + taste = psbt[0:10] + if taste.lower() == b'70736274ff': + # Looks hex encoded; make into binary again + hx = ''.join(re.findall(r'[0-9a-fA-F]*', psbt.decode('ascii'))) + psbt = a2b_hex(hx) + elif taste[0:6] == b'cHNidP': + # Base64 encoded input + psbt = b64decode(psbt) + + if psbt[0:5] != b'psbt\xff': + raise ValueError("File does not have PSBT magic number at start.") + + return psbt + +class WatchableMixin: + # add a consistent way to block for changes on an object + + def __init__(self, *a, **k): + self._update_event = asyncio.Event() + super(WatchableMixin, self).__init__(*a,**k) + + def notify_watchers(self): + # unblock anyone watching us + + self._update_event.set() + self._update_event.clear() + + async def wait(self): + await self._update_event.wait() + return self + + +# EOF diff --git a/version.py b/version.py new file mode 100644 index 0000000..c86c9e1 --- /dev/null +++ b/version.py @@ -0,0 +1,3 @@ + +VERSION = 'v0.9' + diff --git a/webapp.py b/webapp.py new file mode 100755 index 0000000..bc10379 --- /dev/null +++ b/webapp.py @@ -0,0 +1,881 @@ +#!/usr/bin/env python +# +# A web server. +# +import sys, os, asyncio, logging, aiohttp_jinja2, jinja2, time, weakref, re +from aiohttp import web +from yarl import URL +from conn import Connection, MissingColdcard +from ckcc.protocol import CCProtocolPacker +from utils import pformat_json, json_loads, json_dumps, cleanup_psbt +from objstruct import ObjectStruct +from aiohttp.web_exceptions import HTTPMovedPermanently, HTTPNotFound, HTTPBadRequest, HTTPFound +from decimal import Decimal +import aiohttp_session +from aiohttp_session import get_session, new_session +from base64 import b32encode, b64decode, b64encode +from binascii import b2a_hex, a2b_hex +from status import STATUS +from persist import settings, BP +from hashlib import sha256 +from chain import broadcast_txn +from version import VERSION +from jinja2 import Markup +import policy + +from ckcc.constants import USER_AUTH_TOTP, USER_AUTH_HMAC, USER_AUTH_SHOW_QR, MAX_USERNAME_LEN +from ckcc.constants import STXN_VISUALIZE, STXN_SIGNED, AF_P2WPKH, AF_CLASSIC +from ckcc.protocol import CCUserRefused + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +routes = web.RouteTableDef() + +web_sockets = weakref.WeakSet() + +class HTMLErrorMsg(ValueError): + def __init__(self, html): + super(HTMLErrorMsg, self).__init__(Markup(html)) + +APPROVE_CTA = '''\ +Please consult the Coldcard screen and review the HSM policy shown there. If you \ +are satisfied it does what you need, approve the policy and the Coldcard will enter HSM mode. +''' + +def default_context(): + # + # Put values you want in every template here. They cannot vary per-request. + # + rv = ObjectStruct(VERSION=VERSION) + + # this defines the nav menu in top bar + rv.PAGES = [ ('/', 'Sign Transaction'), + ('/tools', 'Tools'), + ('/setup', 'Coldcard Setup'), + ('/bunker', 'Bunker Setup'), + #('/help', 'Help') + ] + + rv['zip'] = zip + + return rv + +async def add_shared_ctx(request, **rv): + # add ctx vars needed to support fancy Vue.js stuff on logged-in pages + + ses = await get_session(request) + + + rv.update(dict( + ws_url = '/websocket/' + ses.get('ws_token'), + STATUS=STATUS.as_dict(), + )) + + rv['CUR_PAGE'] = '/' + request.path.split('/')[-1] + + return rv + +@routes.get('/') +@aiohttp_jinja2.template('txn/index.html') +async def homepage(request): + + # may take some details from the policy, and cook up into more useful forms + + ss = BP.get('summary', None) if STATUS.hsm.get('active') else None + + # coldcard tells us when we'll need a local code, by providing seed value + nl = bool('next_local_code' in STATUS.hsm) + + return await add_shared_ctx(request, policy_summary=ss, needs_local=nl) + +@routes.get('/setup') +@aiohttp_jinja2.template('setup/index.html') +async def setup_page(request): + # HSM policy setup + + # get latest status + dev = Connection() + await dev.hsm_status() + + return await add_shared_ctx(request) + +@routes.get('/bunker') +@aiohttp_jinja2.template('bunker/index.html') +async def bunker_page(request): + + # Bunker config and setup + + # get latest status + dev = Connection() + await dev.hsm_status() + + from torsion import TOR + + return await add_shared_ctx(request, BP=BP, force_local_mode=STATUS.force_local_mode) + + +@routes.get('/tools') +@aiohttp_jinja2.template('tools/index.html') +async def tools_page(request): + # various random things I've been talked into + # - message signing useul tho + if BP.get('policy'): + paths = BP['policy'].get('msg_paths') or [] + paths = set(i.replace('*', '999') for i in paths if i != 'any') + else: + # priv_over_ux: we don't know, but some useful ones + paths = ['m', "m/0/0", "m/44'/0'/0'/0/0", "m/49'/0'/0'/0/0", + "m/84'/0'/0/0" ] + + paths = list(sorted(paths, key=lambda x: (len(x.split('/')), x.split('/')))) + + return await add_shared_ctx(request, msg_paths=paths) + +@routes.get('/help') +@aiohttp_jinja2.template('help.html') +async def help_page(request): + return await add_shared_ctx(request) + + +_static_html_cache = dict() +def send_static_html(fname, disable_cache=True): + # just return the contents of an HTML file, and cache it along the way + # - can't use web.StaticFileResponse because want set-cookies to happen + global _static_html_cache + + if not disable_cache and (fname in _static_html_cache): + page_html = _static_html_cache[fname] + else: + _static_html_cache[fname] = page_html = open(fname, 'rt').read() + + return web.Response(text=page_html, content_type='text/html') + +@routes.get('/logout') +async def logout_page(request): + # do a logout + ses = await get_session(request) + if ses and not ses.new: + logging.warn("Logout of user.") + + # This clears cookie, but if they come back to any page on our site, + # they will get a new one, so we can't redirect them to any other page + # here + ses.invalidate() + + return send_static_html('static/html/logout.html') + +@routes.get('/login') +async def login_page(request): + # Completely static and plain. + # thanks to + + # Create a session, if they don't have one. Need this + # to establish timing/authencity of login data when its posted + ses = await get_session(request) + if not ses: + ses = await new_session(request) + else: + if ses.get('login_ok'): + # they are already logged in, so send them to homepage + return HTTPFound('/') + + # - cannot leave session empty, so put anything in there. + ses['j'] = True + ses.changed() + + return send_static_html('static/html/login.html') + + +def accept_user_login(ses): + # setup session for good user + ses['login_ok'] = True + ses['active'] = time.time() + ses['ws_token'] = str(b32encode(os.urandom(15)), 'ascii') + ses.pop('captcha', None) + +@routes.post('/login') +async def login_post(request): + + # they must have a current session already + # - hope this is enough against CSRF + # - TODO: some rate limiting here, without DoS attacks + ses = await get_session(request) + form = await request.post() + ok = False + + if ses.new: + logging.warn("Bad login attempt (no cookie)") + + elif (time.time() - ses.created) > settings.MAX_LOGIN_WAIT_TIME: + ses.invalidate() + logging.warn("Stale login attempt (cookie too old)") + + elif ses.get('kiddie', 0): + logging.warn("Keeping the kiddies at bay") + + else: + captcha = form.get('captcha', '').lower() + pw = form.get('password', None) + + if not captcha or not pw: + # keep same captcha; they just pressed enter + ok = False + + else: + expect = BP.get('master_pw', settings.MASTER_PW) # XXX scrypt(pw) + expect_code = ses.pop('captcha', None) + + ok = (pw == expect) and (captcha == expect_code) + + if not ok: + # fail; do nothing visible (but they will get new captcha) + dest = URL(request.headers.get('referer', '/login')) + return HTTPFound(dest) + + # SUCCESS + accept_user_login(ses) + + # try to put them back where they were before + try: + dest = URL(request.headers.get('referer', '')).query.get('u', '/') + except: + dest = '/' + + logging.warn(f"Good login from user, sending to: {dest}") + + return HTTPFound(dest) + +@routes.get('/captcha') +async def captcha_image(request): + # make a captcha image, but always the same one per session + + ses = await get_session(request) + if ses.new: + return HTTPNotFound() + + from make_captcha import RansomCaptcha, MegaGifCaptcha, TOKEN_CHARS + import random + + if 'captcha' in ses: + # dont let them retry? + code = ses['captcha'] + else: + code = ''.join(random.sample(TOKEN_CHARS, 8)) + ses['captcha'] = code + + easy = BP.get('easy_captcha', settings.EASY_CAPTCHA) + if easy: + itype, data = RansomCaptcha(seed=code).draw(code, foreground='#444') + else: + itype, data = MegaGifCaptcha(seed=code).draw(code, foreground='#444') + + return web.Response(body=data, content_type='image/'+itype, + headers = {'Cache-Control': 'no-cache'}) + + +async def rx_handler(ses, ws, orig_request): + # Block on receive, handle each message as it comes in. + # see pp/aiohttp/client_ws.py + + async def tx_resp(_ws=ws, **resp): + logging.debug(f"Send resp: {resp}") + await _ws.send_str(json_dumps(resp)) + + + async for msg in ws: + if msg.type != web.WSMsgType.TEXT: + raise TypeError('expected text') + + try: + assert len(msg.data) < 20000 + req = json_loads(msg.data) + + if '_ping' in req: + # connection keep alive, simple + await tx_resp(_pong=1) + continue + + # Caution: lots of sensitive values here XXX + #logging.info("WS api data: %r" % req) + + except Exception as e: + logging.critical("Junk data on WS", exc_info=1) + break # the connection + + # do something with the request + failed = True + try: + await ws_api_handler(ses, tx_resp, req, orig_request) + failed = False + except SystemExit: + raise + except KeyboardInterrupt: + break + except HTMLErrorMsg as exc: + # pre-formated text for display + msg = exc.args[0] + except RuntimeError as exc: + # covers CCProtoError and similar + msg = str(exc) or str(type(exc).__name__) + except BaseException as exc: + logging.exception("API fail: req=%r" % req) + msg = str(exc) or str(type(exc).__name__) + + if failed: + # standard error response + await tx_resp(show_modal=True, html=jinja2.escape(msg), selector='.js-api-fail') + +async def push_status_updates_handler(ws): + # block for a bit, and then send display updates (and all other system status changes) + + # - there is no need for immediate update because when we rendered the HTML on page + # load, we put in current values. + await asyncio.sleep(0.250) + + last = None + while 1: + # get latest state + now = STATUS.as_dict() + + if last != now: + # it has changed, so send it. + await ws.send_str(json_dumps(dict(vue_app_cb=dict(update_status=now)))) + last = now + + # wait until next update, or X seconds max (for keep alive/just in case) + try: + await asyncio.wait_for(STATUS._update_event.wait(), 120) + except asyncio.TimeoutError: + # force an update + last = None + +async def ws_api_handler(ses, send_json, req, orig_request): # handle_api + # + # Handle incoming requests over websocket; send back results. + # req = already json parsed request coming in + # send_json() = means to send the response back + # + action = req.action + args = getattr(req, 'args', None) + + #logging.warn("API action=%s (%r)" % (action, args)) # MAJOR info leak XXX + logging.debug(f"API action={action}") + + if action == '_connected': + logging.info("Websocket connected: %r" % args) + + # can send special state update at this point, depending on the page + + elif action == 'start_hsm_btn': + await Connection().hsm_start() + await send_json(show_flash_msg=APPROVE_CTA) + + elif action == 'delete_user': + name, = args + assert 1 <= len(name) <= MAX_USERNAME_LEN, "bad username length" + await Connection().delete_user(name.encode('utf8')) + + # assume it worked, so UX updates right away + try: + STATUS.hsm.users.remove(name) + except ValueError: + pass + STATUS.notify_watchers() + + elif action == 'create_user': + name, authmode, new_pw = args + + assert 1 <= len(name) <= MAX_USERNAME_LEN, "bad username length" + assert ',' not in name, "no commas in names" + + if authmode == 'totp': + mode = USER_AUTH_TOTP | USER_AUTH_SHOW_QR + new_pw = '' + elif authmode == 'rand_pw': + mode = USER_AUTH_HMAC | USER_AUTH_SHOW_QR + new_pw = '' + elif authmode == 'give_pw': + mode = USER_AUTH_HMAC + else: + raise ValueError(authmode) + + await Connection().create_user(name.encode('utf8'), mode, new_pw) + + # assume it worked, so UX updates right away + try: + STATUS.hsm.users = list(set(STATUS.hsm.users + [name])) + except ValueError: + pass + STATUS.notify_watchers() + + elif action == 'submit_policy': + # get some JSON w/ everything the user entered. + p, save_copy = args + + proposed = policy.web_cleanup(json_loads(p)) + + policy.update_sl(proposed) + + await Connection().hsm_start(proposed) + + STATUS.notify_watchers() + + await send_json(show_flash_msg=APPROVE_CTA) + + if save_copy: + d = policy.desensitize(proposed) + await send_json(local_download=dict(data=json_dumps(d, indent=2), + filename=f'hsm-policy-{STATUS.xfp}.json.txt')) + + elif action == 'download_policy': + + proposed = policy.web_cleanup(json_loads(args[0])) + await send_json(local_download=dict(data=json_dumps(proposed, indent=2), + filename=f'hsm-policy-{STATUS.xfp}.json.txt')) + + elif action == 'import_policy': + # they are uploading a JSON capture, but need values we can load in Vue + proposed = args[0] + cooked = policy.web_cookup(proposed) + await send_json(vue_app_cb=dict(update_policy=cooked), + show_flash_msg="Policy file imported.") + + elif action == 'pick_onion_addr': + from torsion import TOR + addr, pk = await TOR.pick_onion_addr() + await send_json(vue_app_cb=dict(new_onion_addr=[addr, pk])) + + elif action == 'pick_master_pw': + pw = b64encode(os.urandom(12)).decode('ascii') + pw = pw.replace('/', 'S').replace('+', 'p') + assert '=' not in pw + + await send_json(vue_app_cb=dict(new_master_pw=pw)) + + elif action == 'new_bunker_config': + from torsion import TOR + # save and apply config values + nv = json_loads(args[0]) + + assert 4 <= len(nv.master_pw) < 200, "Master password must be at least 4 chars long" + + # copy in simple stuff + for fn in [ 'tor_enabled', 'master_pw', 'easy_captcha', 'allow_reboots']: + if fn in nv: + BP[fn] = nv[fn] + + + # update onion stuff only if PK is known (ie. they changed it) + if nv.get('onion_pk', False) or False: + for fn in [ 'onion_addr', 'onion_pk']: + if fn in nv: + BP[fn] = nv[fn] + + BP.save() + + await send_json(show_flash_msg="Bunker settings encrypted and saved to disk.") + + STATUS.tor_enabled = BP['tor_enabled'] + STATUS.notify_watchers() + + if not BP['tor_enabled']: + await TOR.stop_tunnel() + elif BP.get('onion_pk') and not (STATUS.force_local_mode or STATUS.setup_mode): + # connect/reconnect + await TOR.start_tunnel() + + elif action == 'sign_message': + # sign a short text message + # - lots more checking could be done here, but CC does it anyway + msg_text, path, addr_fmt = args + + addr_fmt = AF_P2WPKH if addr_fmt != 'classic' else AF_CLASSIC + + try: + sig, addr = await Connection().sign_text_msg(msg_text, path, addr_fmt) + except: + # get the spinner to stop: error msg will be "refused by policy" typically + await send_json(vue_app_cb=dict(msg_signing_result='(failed)')) + raise + + sig = b64encode(sig).decode('ascii').replace('\n', '') + + await send_json(vue_app_cb=dict(msg_signing_result=f'{sig}\n{addr}')) + + elif action == 'upload_psbt': + # receiving a PSBT for signing + + size, digest, contents = args + psbt = b64decode(contents) + assert len(psbt) == size, "truncated/padded in transit" + assert sha256(psbt).hexdigest() == digest, "corrupted in transit" + + STATUS.import_psbt(psbt) + STATUS.notify_watchers() + + elif action == 'clear_psbt': + STATUS.clear_psbt() + STATUS.notify_watchers() + + elif action == 'preview_psbt': + STATUS.psbt_preview = 'Wait...' + STATUS.notify_watchers() + try: + txt = await Connection().sign_psbt(STATUS._pending_psbt, flags=STXN_VISUALIZE) + txt = txt.decode('ascii') + # force some line splits, especially for bech32, 32-byte values (p2wsh) + probs = re.findall(r'([a-zA-Z0-9]{36,})', txt) + for p in probs: + txt = txt.replace(p, p[0:30] + '\u22ef\n\u22ef' + p[30:]) + STATUS.psbt_preview = txt + except: + # like if CC doesn't like the keys, whatever .. + STATUS.psbt_preview = None + raise + finally: + STATUS.notify_watchers() + + elif action == 'auth_set_name': + idx, name = args + + assert 0 <= len(name) <= MAX_USERNAME_LEN + assert 0 <= idx < len(STATUS.pending_auth) + + STATUS.pending_auth[idx].name = name + STATUS.notify_watchers() + + elif action == 'auth_offer_guess': + idx, ts, guess = args + assert 0 <= idx < len(STATUS.pending_auth) + STATUS.pending_auth[idx].totp = ts + STATUS.pending_auth[idx].has_guess = 'x'*len(guess) + STATUS._auth_guess[idx] = guess + STATUS.notify_watchers() + + elif action == 'submit_psbt': + # they want to sign it now + expect_hash, send_immediately, finalize, wants_dl = args + + assert expect_hash == STATUS.psbt_hash, "hash mismatch" + if send_immediately: assert finalize, "must finalize b4 send" + + logging.info("Starting to sign...") + STATUS.busy_signing = True + STATUS.notify_watchers() + + try: + dev = Connection() + + # do auth steps first (no feedback given) + for pa, guess in zip(STATUS.pending_auth, STATUS._auth_guess): + if pa.name and guess: + await dev.user_auth(pa.name, guess, int(pa.totp), a2b_hex(STATUS.psbt_hash)) + + STATUS.reset_pending_auth() + + try: + result = await dev.sign_psbt(STATUS._pending_psbt, finalize=finalize) + logging.info("Done signing") + + msg = "Transaction signed." + + if send_immediately: + msg += '

' + broadcast_txn(result) + + await send_json(show_modal=True, html=Markup(msg), selector='.js-api-success') + + result = (b2a_hex(result) if finalize else b64encode(result)).decode('ascii') + fname = 'transaction.txt' if finalize else ('signed-%s.psbt'%STATUS.psbt_hash[-6:]) + + if wants_dl: + await send_json(local_download=dict(data=result, filename=fname, + is_b64=(not finalize))) + + await dev.hsm_status() + except CCUserRefused: + logging.error("Coldcard refused to sign txn") + await dev.hsm_status() + r = STATUS.hsm.get('last_refusal', None) + if not r: + raise HTMLErroMsg('Refused by local user.') + else: + raise HTMLErrorMsg(f"Rejected by Coldcard.

{r}") + + finally: + STATUS.busy_signing = False + STATUS.notify_watchers() + + elif action == 'shutdown_bunker': + await send_json(show_flash_msg="Bunker is shutdown.") + await asyncio.sleep(0.25) + logging.warn("User-initiated shutdown") + asyncio.get_running_loop().stop() + sys.exit(0) + + elif action == 'leave_setup_mode': + # During setup process, they want to go Tor mode; which I consider leaving + # setup mode ... in particular, logins are required. + # - button label is "Start Tor" tho ... so user doesn't see it that way + assert STATUS.setup_mode, 'not in setup mode?' + assert BP['tor_enabled'], 'Tor not enabled (need to save?)' + addr = BP['onion_addr'] + assert addr and '.onion' in addr, "Bad address?" + + STATUS.setup_mode = False + await send_json(show_flash_msg="Tor hidden service has been enabled. " + "It may take a few minutes for the website to become available") + STATUS.notify_watchers() + + from torsion import TOR + logging.info(f"Starting hidden service: %s" % addr) + asyncio.create_task(TOR.start_tunnel()) + + elif action == 'logout_everyone': + # useful for running battles... + # - changes crypto key for cookies, so they are all invalid immediately. + from aiohttp_session.nacl_storage import NaClCookieStorage + import nacl + + logging.warning("Logout of everyone!") + + # reset all session cookies + storage = orig_request.get('aiohttp_session_storage') + assert isinstance(storage, NaClCookieStorage) + storage._secretbox = nacl.secret.SecretBox(os.urandom(32)) + + # kick everyone off (bonus step) + for w in web_sockets: + try: + await send_json(redirect='/logout', _ws=w) + await w.close() + except: + pass + + else: + raise NotImplementedError(action) + + +@routes.get('/websocket/{token}') +async def api_websocket(request): + ''' + Stream display activity as HTML fragments + - accept config changes + - and more? + ''' + + try: + ses = await get_session(request) + assert not ses.new + assert ses['login_ok'] + token = request.match_info['token'] + assert token == ses['ws_token'], ses.get('ws_token') + except: + logging.exception("Bad websocket link") + raise web.HTTPForbidden + + # begin a streaming response + ws = web.WebSocketResponse() + await ws.prepare(request) + web_sockets.add(ws) + + try: + api_rx = asyncio.create_task(rx_handler(ses, ws, request)) + dis_tx = asyncio.create_task(push_status_updates_handler(ws)) + + await asyncio.gather(api_rx, dis_tx) + finally: + api_rx.cancel() + dis_tx.cancel() + await ws.close() + + return ws + + +@routes.get('/{fname}.php') +@routes.get('/{path}/{fname}.php') +@routes.get('/admin') +async def kiddie_traps(request): + # I hate skill-less people running burpsuite! Track them + ses = await get_session(request) + + ses['kiddie'] = ses.get('kiddie', 0) + 1 + + return HTTPFound("/login") + +@routes.get('/favicon.ico') +@routes.get('/robots.txt') +@routes.get('/humans.txt') +async def expected_404s(request): + # we are expecting these URL's to 404 + # - don't redirect to login + return HTTPNotFound() + + +@routes.get('/static/ext/themes/default/assets/fonts/{fname}') +async def remap_fonts(request): + fn = request.match_info['fname'] + # remap some links so we don't need to edit Semantic files. + return HTTPMovedPermanently('/static/ext/semantic-fonts/' + fn) + +def extra_filters(app): + + def my_time(dt): + if dt is None: return None + try: + dt = pendulum.instance(dt) + except ValueError: + return repr(dt) + return dt.in_tz('local').strftime('%l:%M%p').lower() + + def my_date(dt): + if dt is None: return None + try: + dt = pendulum.instance(dt) + except ValueError: + return repr(dt) + return dt.in_tz('local').strftime('%b %e') + + def duration(i): + if i < 90: + return '%d seconds' % i + else: + return '%d:%02d minutes' % (i//60, i%60) + + def extlink(url, label=None): + + # in the templates, use like this: + # {{ "http://sdfsfd/sdf/sdf/" | extlink( "Hello") }} + if not label: + from urllib.parse import urlparse + label = urlparse(url).netloc.lower() + if label[0:4] == 'www.': + label = label[4:] + + rv = f''\ + f'{label} ' + + return Markup(rv) + + def link_txn(txn_hash): + from chain import link_to_txn + url = link_to_txn(txn_hash) + return extlink(url, label=txn_hash) + + def link_to_explorer(unused): + url = settings.EXPLORA + label = 'Bitcoin Explorer' + if STATUS.is_testnet: + label = 'Testnet Explorer' + url += '/testnet' + return extlink(url, label=label) + + def slugify(t): + return t.lower().strip().replace('&', 'and').replace(' ', '-') + + rv = locals().copy() + + return rv + +@web.middleware +async def auth_everything(request, handler): + + # during setup, no login needed + if STATUS.force_local_mode or STATUS.setup_mode: + # bypass security completely + ses = await get_session(request) + if not ses: + ses = await new_session(request) + accept_user_login(ses) + return await handler(request) + + # whitelist of pages that do not need login + # all other requests will need auth + if handler in { login_page, login_post, captcha_image, kiddie_traps, expected_404s }: + return await handler(request) + + # verify auth + ses = await get_session(request) + if ses: + active = ses.get('active', 0) + idle = time.time() - active + if idle > settings.MAX_IDLE_TIME: + # stale / idle timeout + logging.warn("Idle timeout") + ses.invalidate() + ses = None + + if not ses: + # no cookie/stale cookie, so send them to logout/in page + u = URL("/login") + target = request.path[1:] + if target and target != 'logout': + u = u.update_query(u=target) + + return HTTPFound(u) + + # normal path: continue to page + + ses['active'] = time.time() + + resp = await handler(request) + + # clearly an HTML request, so force no caching + if '/static/' not in request.path: + resp.headers['Cache-Control'] = 'no-cache' + + return resp + +def startup(setup_mode): + # Entry point. Return an awaitable to be run. + + # encrypted cookies for session logic + from aiohttp_session.nacl_storage import NaClCookieStorage + from aiohttp_session import session_middleware + todays_key = os.urandom(32) + sml = session_middleware(NaClCookieStorage(todays_key, cookie_name='X')) + + # create app: order of middlewares matters + app = web.Application(middlewares=[sml, auth_everything]) + app.add_routes(routes) + app.router.add_static('/static', './static') + + # hack to obfuscate our identity a little + # - from 23% market share + import aiohttp.web_response as ht + ht.SERVER_SOFTWARE = 'nginx/1.14.1' + + j_env = aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'), + filters=extra_filters(app)) + j_env.globals.update(default_context()) + j_env.policies['json.dumps_function'] = json_dumps + + my_url = f"http://localhost:{settings.PORT_NUMBER}" + ('/setup' if setup_mode else '') + logging.info(f"Web server at: {my_url}") + + # meh; kinda annoying. + if 0: + def popup(): + try: + # see + # if this doesn't happen on MacOS + from webbrowser import open as open_browser + open_browser(my_url) + except: + logging.error("Unable to pop browser open", exc_info=1) + asyncio.get_running_loop().call_later(3, popup) + + from aiohttp.abc import AbstractAccessLogger + class AccessLogger(AbstractAccessLogger): + def log(self, request, response, time): + self.logger.info(f'{response.status} <= {request.method} {request.path}') + + return web._run_app(app, port=settings.PORT_NUMBER, print=None, access_log_class=AccessLogger) + +if __name__ == "__main__": + from utils import setup_logging + setup_logging() + dev = Connection(None) # won't do anything tho, because async dev.run not called + asyncio.run(startup()) + +# EOF