[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Cross domain Single sign-on with Json Web Tokens (JWT)\n> Federate your websites using only javascript\n\nAccess to several web sites with a unique identification. Uses JSON Web Tokens (RFC7519) to represent the information exchanged between the identification provider (IDP) and service provider (SP). The JWT is shared and synchronized among all your websites through the browser local storage without need of server session\n\n![alt tag](https://produccion.sslsignature.com/web/images/ssoiframe.png)\n\n\n## How does it work\nYou have an excellent introduction to JWT in (https://jwt.io/introduction/) and single sign-on (SSO) on our website (spanish) (https://produccion.sslsignature.com/web/sso.html)\n\n## Getting started\n> With hosted version (it is free)\n\nDefine on page a `<meta>` field to indicate the sslsignature accountId\n```\n<meta name=\"ssls.accountId\" content=\"5995a3c9-678b-4338-a674-362af68b9ef9\" />\n```\nInclude javascript\n```\n<script src=\"https://produccion.sslsignature.com/sso/resources/js/sslssso.js\"></script>\n```\nCreate a function to receive the authenticated user\n```\nfunction onIdentification(operation){\n    console.log(\"eidentifier: \"+ operation.eIdentifier);\n    console.log(\"name: \"+ operation.name);\n    console.log(\"jwt: \"+ operation.jwt);\n}\n```\nNow, we are going to see it in action (download the demo for the third step)\n\n1. Create a JWT [here](https://produccion.sslsignature.com/sso/hosted/jwtcreator.html). This would be done in your login form\n2. Open a new tab in your browser with [this URL](https://produccion.sslsignature.com/sso/hosted/sso.html). You will see that you are logged in and the content of the JWT token\n3. Now, here is the magic, download [sso.html](/test/web/hosted/sso.html) and open from your computer, and you will see that you are registered with the same user. Try to logout and see the opened page in second step (do not use IE11 at this moment, please...)\n\n##Install\n### Content of the repository\n* /backend  -->The sample server\n* /build    -->Build scripts\n* /client   -->Javascript library for your pages\n* /dist     -->Precompiled sso.war to deploy javascript, sample server and demos on a container like tomcat\n* /test     -->Demo pages (hosted and standalone) and a java sample client to issue/validate tokens\n\n### Javascript library\nSimply copy the library 'sslssso.js' and its dependencies on a web server. \n{yourserver.com}/{ssopath}/js/sslssso.js\n{yourserver.com}/{ssopath}/html/sso.html\nsslssso will access sso.html and related .js, therefore expect to find this structure\n\nInclude a javascript reference in your page to sslssso.js\n```\n<script src=\"{yourserver.com}/{ssopath}/js/sslssso.js\"></script>\n```\nor use hosted\n```\n<script src=\"https://produccion.sslsignature.com/sso/resources/js/sslssso.js\"></script>\n```\n### Backend server\nThe signature key to issue tokens (and validate) must be well protected, usually on the server. You can use a hosted account from SSLSignature (free of charges) or issue tokens from your own server. The project includes a sample server with autogenerated HMAC keys\n\n####Use your own server\nYo need to provide a REST service to validate the JWT from the client side. If you plan to do it only on server side, move on to the next section\n```\nPOST /{ssoValidationUri} HTTPS\nContent-Type=application/x-www-form-urlencoded\nHost: yourserver.com\njwt={jwt}\n```\nThe answer must have code 200, status = FAILED / SUCCESS, and the JWT parsed fields in JSON format\n```\n{\n    \"status\": \"SUCCESS\",       //SUCCESS, FAIL. Mandatory\n    \"sub\": \"123456\",            //User unique identifier. Recommended\n    \"eidentifier\":\"john.smith\"  //username,Recommended\n    \"name\": \"John Smith\",       //User Full Name. Recommended\n    \"other\": \"value\",           //More fields (email, phone, etc). Optional\n    \"jwt\": \"eyJhbGciOiJIUzI...\"  //JWT new token if necessary. Optional\n}\n\n```\n\n\n####Use the sample server\nTake care that it is only an example and it is not intended for a production system\n\nDeploy sso.war in a J2EE container like tomcat. The first time you run the HMAC signing key will be created in a file called jwt.hmac (configure location in WEB-INF/web.xml)\n\nThe JWT validation service will be available on {yourserver.com}/sso/jwt\nThe sample server also allow you to issue JWT. Invoke the service providing the fields to be included in JWT\n```\nPOST /sso/jwt HTTPS\nContent-Type=application/x-www-form-urlencoded\nHost: yourserver.com\nsub=123456&eidentifier=john.smith&name=John+Smith&phone=34+661661661&email=john.smith%40mycompany.com&other=...\n```\nThe response will be the JWT string\n```\neyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTYiLCJpc3MiOiJKV1QgU0FNUExFIElTU1VFUiIsImlhdCI6MTQ2MzU4MTg4MSwiZXhwIjoxNDYzNjY4MjgxLCJwaG9uZSI6IjM0IDY2MTY2MTY2MSIsIm90aGVyIjoiLi4uIiwiZWlkZW50aWZpZXIiOiJqb2huLnNtaXRoIiwiZW1haWwiOiJqb2huLnNtaXRoQG15Y29tcGFueS5jb20iLCJuYW1lIjoiSm9obiBTbWl0aCJ9.eaihxfyO8zWJJm0o97T6p-Cql9oe6n_3SLj0MphGbBA\n```\nConfigure expiration or issuer in JWTServlet class. \n\n####Use the hosted server\nThe SSLSignature could issue and validate the JWT for your system. You need an account. After that, the configuration is simple as shown in 'Getting started'.\n\nAfter a successful authentication in your system, invoke this service to issue a new token . Provide a JSON with your required fields.\n\n```\nPOST /sslsignature/account/jwt HTTPS\nAuthorization=Basic YWNjb3VudElkOmFwaUtleQ==\nContent-Type=application/json\nHost: produccion.sslsignature.com\n{\n   sub: \"yourInternalId\",\n   eidentifier: \"yourUserIdentifier\",\n   name: \"user name\",\n   other: \"other...\"\n}\n```\nAlso is needed an authorization header (basic http auth) in the way `Basic Base64(accountId:apiKey)`. The string 'Basic' followed by the base64 encoding of the provided accountId, ':' and apiKey\n\n##Usage\n### Page configuration\n\nConfigure the accountId and custom validation URL in the <meta> tags of the page or using javascript. The accountId will reference the identifier that will take the token in the local storage.\n```\n<meta name=\"ssls.accountId\" content=\"myTokenId\" />\n<meta name=\"ssls.validationUrl\" content=\"{yourserver.com}/{ssoValidationUri}\" />\n<meta name=\"ssls.validate\" content=\"true\"/>\n<script src=\"https://produccion.sslsignature.com/sso/resources/js/sslssso.js\"></script>\n\n//Optional javascript config\nvar ssls_accountId=myTokenId;\nvar ssls_validationUrl={yourserver.com}/{ssoValidationUri};\n```\n\n### SSO Events\nThe sso generates events for onload, onIdentification and onLogout. Simply create a function on the page with these names.\n```\n// Invoked after page load if you have a valid token or after new JWT correct identification (if page is still loaded)\n// If you do not have identification token, this function is not executed\nfunction onIdentification(operation){\n    console.log(operation.sub);  //Your User internal ID\n    console.log(operation.eidentifier);  //Your user unique identifier (for example the username)\n    console.log(operation.name); //User full name\n    console.log(\"operation.jwt);  //The token itself\n}\n//Invoked when  the script finish loading the SSO. It is always after onIdentification\nfunction onLoad(){\n}\n//Invoked when user logs out\nfunction onLogout(){\n}\n```\nIn you need several event listeners use\n```\nsslssso.listen (\"sso.onload\", function (observable, eventType, data) {});\n```\n### JWT Validation\nThe token is validated during script execution to check that has been issued by the server and has not been altered. The electronic signature is verified cryptographically on the server. If the token is correct will occur a call to onIdentification. If the validation is unsuccessful, the token is deleted and acts as if there had been token.\n\nValidation URL is configured with `<meta name=\"ssls.validationUrl\">` (see server instalation). If you do not want the tokens are validated on the client side, set `validate = false` (default is true). Then no server configuration is needed, and `sslssso.js` only will decode jwt token and check expiration on the client side.\n\nOn hosted version, use the provided accountId and do not set the validationUrl\n\n### Login\nIn a standard authentication flow, when an identification is required, the website redirects the user to the IDP (identification provider). The IDP authenticates user with the organization defined method, for example, and username/password form. After successful authentication, the IDP server returns a valid JWT that includes the identification information and the electronic signature. The JWT is stored locally on the browser\n![alt tag](https://produccion.sslsignature.com/web/images/ssoflow.png)\n\nCalls SSO to store the jwt issued token on localStorage of browser. An `onIdentification` event will be fired on all tabs\n```\nsslssso.login(jwt);\n```\n\n\n### Logout\n```\nsslssso.logout();\n```\nThe token will be cleaned and an `onLogout` event will be fired on all tabs\n\n##Known issues\n###IE11 & Edge\nJWT update events do not syncronize tabs. See [Microsoft doc](https://connect.microsoft.com/IE/feedback/details/812563/ie-11-local-storage-synchronization-issues)\n\n## Support\nhttps://soporte.aralink.com\nhttps://github.com/Aralink/ssojwt/issues\n"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/AuthenticationOperation.java",
    "content": "package com.aralink.sslsignature.sso.jwt;\n\nimport java.io.StringReader;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.jsonwebtoken.Claims;\n\n\n\npublic class AuthenticationOperation {\n\t\n\tprivate Map<String,String> params = new HashMap<String,String>();\n\t\n\t/**\n\t * FAIL operation\n\t * @param e error produced parsing or validating JWT\n\t */\n\tpublic AuthenticationOperation(Exception e){\n\t\tparams.put(\"status\", \"FAIL\");\n\t\tparams.put(\"error\", e.getMessage());\n\t}\n\t\n\t/**\n\t * Success operation.\n\t * Return all fields parsed\n\t * @param the body of JWT\n\t */\n\tpublic AuthenticationOperation(Claims body){\n\t\tparams.put(\"status\", \"SUCCESS\");\n\t\t\n\t\tfor (String key: body.keySet()){\n\t\t\tObject value = body.get(key);\n\t\t\tif (value instanceof String){\n\t\t\t\tparams.put(key, (String)value);\n\t\t\t}\t\n\t\t}\n\t}\n\t\n\t/**\n\t * JSON Coder. \n\t * Use jackson or your preferred dependendy \n\t * @return\n\t */\n\tpublic String toJSON(){\n\t\t\n\t\tStringBuffer buf = new StringBuffer();\n\t\tbuf.append(\"{\");\n\t\tString prefix = \"\";\n\t\tfor (String key:params.keySet()){\n\t\t\tbuf.append(prefix).append(\"\\\"\").append(key).append(\"\\\":\\\"\").append(params.get(key)).append(\"\\\"\");\n\t\t\tprefix=\",\";\n\t\t}\n\t\t\n\t\tbuf.append(\"}\");\n\t\treturn buf.toString();\n\t}\n\t\n}\n"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/HMACKeyContainer.java",
    "content": "package com.aralink.sslsignature.sso.jwt;\n\n\nimport io.jsonwebtoken.impl.crypto.MacProvider;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.security.Key;\n\nimport javax.crypto.spec.SecretKeySpec;\n\n\n\npublic class HMACKeyContainer {\n\n\t\n\tprivate Key key;\n\t\n\tpublic HMACKeyContainer()throws IOException{\n\t\tthis(null);\n\t}\n\tpublic HMACKeyContainer(String keyFile) throws IOException{\n\t\tif (keyFile == null || keyFile.length()==0){\n\t    \t keyFile = \"jwthmac.key\";\n\t    }\n\t\t\n\t\tPath path = Paths.get(keyFile);\n\t\tif (!path.toFile().exists()){\n\t\t\t//File not exists. Create new File\n\t\t\tgenerateKey(path);\n\t\t} else  {\n\t\t\t//Reads the HMAC key from file\n\t\t\tbyte[] data = Files.readAllBytes(path);\t\n\t\t\tkey = hmacKeyFromEncoded(data);\n\t\t\tSystem.out.println(\"init HMAC key from file: \"+path.toAbsolutePath());\n\t\t}\t\t\n\t\t\n\t}\n\tpublic Key getHmacKey(){\n\t\treturn key;\n\t}\n\tprivate Key generateKey(Path path) throws IOException{\n\t\t//path..createNewFile();\n\t\tkey = MacProvider.generateKey(JWTManager.DEFAULT_HMAC_KEY_ALGORITHM);\n\t\tbyte data[] = key.getEncoded();\n\t\tFiles.write(path, data);\n\t\tSystem.out.println(\"created new HMAC key in file: \"+path.toAbsolutePath());\n\t\treturn key;\n\t}\t\n\t\n\tpublic static Key hmacKeyFromEncoded(byte encodedHmacKey[]){\n\t\tif (encodedHmacKey != null && encodedHmacKey.length>0){\n\t\t\tKey key = new SecretKeySpec(encodedHmacKey,JWTManager.DEFAULT_HMAC_KEY_ALGORITHM.getJcaName());\n\t\t\treturn key;\n\t\t}\n\t\treturn null;\n\t}\n\t\n}\n"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/JWTManager.java",
    "content": "package com.aralink.sslsignature.sso.jwt;\n\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.ExpiredJwtException;\nimport io.jsonwebtoken.JwtBuilder;\nimport io.jsonwebtoken.Jwts;\nimport io.jsonwebtoken.MalformedJwtException;\nimport io.jsonwebtoken.SignatureAlgorithm;\nimport io.jsonwebtoken.SignatureException;\nimport io.jsonwebtoken.UnsupportedJwtException;\n\n\n\nimport java.security.Key;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\n\nimport java.util.Map;\n\n\n\npublic class JWTManager {\n\tpublic final static  SignatureAlgorithm DEFAULT_HMAC_SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;\n\tpublic final static  SignatureAlgorithm DEFAULT_HMAC_KEY_ALGORITHM = SignatureAlgorithm.HS512;\n\n\tprivate HMACKeyContainer hmacKeyContainer;\n\tprivate String issuer = \"JWT SAMPLE ISSUER\";\n\tprivate int expirationTimeInHours = 24;\n\t\n\tpublic JWTManager(HMACKeyContainer hmacKeyContainer){\n\t\tthis.hmacKeyContainer = hmacKeyContainer;\n\t}\n\t\n\tpublic String getIssuer() {\n\t\treturn issuer;\n\t}\n\n\tpublic void setIssuer(String issuer) {\n\t\tthis.issuer = issuer;\n\t}\n\n\tpublic int getExpirationTimeInHours() {\n\t\treturn expirationTimeInHours;\n\t}\n\n\tpublic void setExpirationTimeInHours(int expirationTimeInHours) {\n\t\tthis.expirationTimeInHours = expirationTimeInHours;\n\t}\n\n\n\n\tprivate  Date exp (int calendar,int len){\n\t\tGregorianCalendar gc = new GregorianCalendar();\n\t\tgc.add(calendar,len);\n\t\tDate expires = gc.getTime();\n\t\treturn expires;\n\t}\n\n\tprivate boolean isExpired(Claims body, Date actual){\n\t\treturn body.getExpiration().before(actual);\n\t}\n\n\n\tprivate boolean isExpired(Claims body){\n\t\treturn isExpired(body,new Date());\n\t}\n\t\n\t\n\tpublic String issueJWT(@SuppressWarnings(\"rawtypes\") Map extra){\n\n\t\t//get hmac signature key \n\t\tKey key = hmacKeyContainer.getHmacKey();\n\n\t\tString subject = \"none\";\n\t\t//Get required subject ID\n\t\tif (extra.get(\"sub\") != null)\n\t\t\tsubject = ((String[])extra.get(\"sub\"))[0];\n\t\t\n\t\t//Build token\n\t\tJwtBuilder builder =  Jwts.builder()\n\t\t\t\t.setSubject(subject)\n\t\t\t\t.setIssuer(getIssuer())\n\t\t\t\t.setIssuedAt(new java.util.Date())\n\t\t\t\t.setExpiration(exp (Calendar.HOUR,getExpirationTimeInHours()));\n\t\t\t\t\n\t\t\n\t\t//Body with extra fields\n\t\tfor (Object extKey: extra.keySet()){\n\t\t\tif (!extKey.equals(\"sub\"))\n\t\t\t\tbuilder.claim((String)extKey,((String[])extra.get(extKey))[0]);\n\t\t}\t\t\n\n\t\tString token = builder.signWith(JWTManager.DEFAULT_HMAC_SIGNATURE_ALGORITHM, key).compact();\n\n\t\treturn token;\n\t}\n\n\t\n\t\n\n\tpublic Claims validateJWT ( String jwtToken)throws Exception{\n\n\t\t//Get signature key\n\t\tKey key = hmacKeyContainer.getHmacKey();\n\n\t\ttry{\n\t\t\t//Check signature and parse body\n\t\t\tClaims body = Jwts.parser().setSigningKey(key).parseClaimsJws(jwtToken).getBody();\n\n\t\t\t//Check expiration\n\t\t\tif (isExpired(body))\n\t\t\t\tthrow new Exception ( \"key expired\");\n\n\t\t\treturn body;\n\t\t}catch \t(UnsupportedJwtException e){\n\t\t\tSystem.err.println(\"Bad JWT token: \"+e.getMessage());\n\t\t\tthrow new Exception ( \" Bad JWT token\");\n\t\t}catch \t(MalformedJwtException e){\n\t\t\tSystem.err.println(\"Bad JWT token: \"+e.getMessage());\n\t\t\tthrow new Exception ( \" Bad JWT token\");\n\t\t}catch \t(IllegalArgumentException e){\n\t\t\tSystem.err.println(\"Bad JWT token: \"+e.getMessage());\n\t\t\tthrow new Exception ( \" Bad JWT token\");\n\t\t}catch \t(SignatureException e){\n\t\t\tSystem.err.println(\" BAD PUBLIC KEY\");\n\t\t\tthrow new Exception ( \"Bad signature in JWT token\");\n\t\t} catch (ExpiredJwtException e){\n\t\t\tSystem.err.println(\"Expired JWT token: \"+e.getMessage());\n\t\t\tthrow new Exception ( \"Expired JWT token: \"+e.getMessage());\n\t\t}\n\n\t}\n\t\n}\n"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/JWTServlet.java",
    "content": "package com.aralink.sslsignature.sso.jwt;\n\nimport io.jsonwebtoken.Claims;\n\nimport java.io.IOException;\n\nimport javax.servlet.ServletConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n\n@SuppressWarnings(\"serial\")\npublic class JWTServlet extends HttpServlet {\n\n\tprivate HMACKeyContainer hmacKeyContainer;\n\tprivate JWTManager jwtManager;\n\n\tpublic void init(ServletConfig config) throws ServletException {\n\t\tsuper.init(config);\n\t\tString keyFile = config.getInitParameter(\"keyFile\");\n//\t\tString issuer = config.getInitParameter(\"issuer\");\n\t\t\n\t\ttry{\n\t\t\t//Init HMAC key from file. If it not exists, creates a new one\n\t\t\thmacKeyContainer = new HMACKeyContainer(keyFile);\n\t\t\tjwtManager = new JWTManager (hmacKeyContainer);\n\t\t\t\n\t\t}catch (IOException e){\n\t\t\tthrow new ServletException(e);\n\t\t} \n\n\t\tSystem.out.println(\"servlet init: \"+keyFile);\n\t}\n\n\tpublic void doOptions(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException  {\n\t\tSystem.out.println(\"OPTIONS REQUESTS \");\n\t\tresponse.addHeader(\"Access-Control-Allow-Origin\", \"*\");\n\t}\n\t\n\tpublic void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException  {\n\t\tdoPost(request,response);\n\t}\n\n\tpublic void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException  {\n\n\t\tString jwt = request.getParameter(\"jwt\");\n\t\tif (jwt != null){\n\t\t\tAuthenticationOperation result = null;\n\t\t\t//validateToken\n\t\t\ttry{\n\t\t\t\tClaims body = jwtManager.validateJWT(jwt);\n\t\t\t\t//Validation successful\n\t\t\t\tresult = new AuthenticationOperation(body);\n\t\t\t\tSystem.out.println(\"JWT validation SUCCESS for SUB: \"+body.getSubject());\n\t\t\t}catch (Exception e){\n\t\t\t\t//Validation fail\n\t\t\t\tresult = new AuthenticationOperation(e);\n\t\t\t\tSystem.err.println(\"JWT validation failed: \"+e.getMessage());\n\t\t\t}\n\t\t\t\n\t\t\t//Response JSON & enable CORS \n\t\t\tresponse.setContentType(\"application/json\");\n\t\t\tresponse.addHeader(\"Access-Control-Allow-Origin\", \"*\");\n\t\t\tSystem.out.println(result.toJSON());\n\t\t\tresponse.getWriter().print(result.toJSON());\n\t\t} else {\n\t\t\t\n\t\t\t//Issue new token\n\t\t\tjwt = jwtManager.issueJWT(request.getParameterMap());\n\t\t\tSystem.out.println(\"Issued new JWT \"+jwt);\n\t\t\t\n\t\t\t//Response TEXT & enable CORS\n\t\t\tresponse.setContentType(\"text/html\");\t\n\t\t\tresponse.addHeader(\"Access-Control-Allow-Origin\", \"*\");\n\t\t\tresponse.getWriter().print(jwt);\n\t\t}\n\t}\n\t\n\tpublic void destroy()  {\n\t\t// do nothing.\n\t}\n\t\n\n}"
  },
  {
    "path": "backend/src/web/WEB-INF/web.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n\tid=\"WebApp_ID\" version=\"2.5\">\n  <display-name>SSLSIGNATURE {env.SVN_REVISION} </display-name>\n  <session-config>\n    <session-timeout>300</session-timeout>\n  </session-config>\n \n  <servlet>\n\t<servlet-name>jwt</servlet-name>\n\t<servlet-class>com.aralink.sslsignature.sso.jwt.JWTServlet</servlet-class>\n\t<init-param>\n            <param-name>keyFile</param-name>\n            <param-value>jwt.hmac</param-value>\n    </init-param>\n  </servlet>\n  <servlet-mapping>\n\t<servlet-name>jwt</servlet-name>\n\t<url-pattern>/jwt</url-pattern>\n  </servlet-mapping>\n</web-app>"
  },
  {
    "path": "build/build.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<project name=\"SSO SSLSignature GIT\" default=\"\" basedir=\"..\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n    \n    <property name=\"version\" value=\"1.0.0\" />\n    <property name=\"builddir\" value=\"${basedir}/build\" />\n    <property name=\"buildlibdir\" value=\"${basedir}/backend/build-lib\" />\n\t<property name=\"libdir\" value=\"${builddir}/lib\" />\n\t<property name=\"compilation\" value=\"${builddir}/bin\" />\n\t<property name=\"distdir\" value=\"${basedir}/dist\" />\n\t\n\t<property name=\"jssource\" value=\"${basedir}/client\" />\n\t<property name=\"javasource\" value=\"${basedir}/backend/src/java\" />\n\t<property name=\"websource\" value=\"${basedir}/backend/src/web\" />\n\t<property name=\"testsource\" value=\"${basedir}/test/web\" />\n        \n\t<property name=\"ivy.dep.file\" value=\"${builddir}/ivy.xml\" />\n\t<target name=\"RESOLVE\" description=\"retrieve dependencies with ivy\" >\n\t\t<ivy:retrieve pattern=\"${libdir}/[artifact].[ext]\" />\n\t</target>\n\t\n\t\n\t\n\t<target name=\"init\">\n\t\t<mkdir dir=\"${builddir}\" />\n\t\t<mkdir dir=\"${libdir}\" />\n\t\t<delete dir=\"${compilation}\" />\n\t\t<mkdir dir=\"${compilation}\" />\t\t\n\t</target>\n\t\n\t<target name=\"backend\" description=\"\" depends=\"init\">\n\t    <path id=\"libraries\">\n\t\t\t<fileset dir=\"${libdir}\" includes=\"*.jar\" />\t\n\t\t\t<fileset dir=\"${buildlibdir}\" includes=\"*.jar\" />\t\t\t\t\t\t\t\n\t\t</path>\n\t    <javac destdir=\"${compilation}\" classpathref=\"libraries\" source=\"1.5\" target=\"1.5\" debug=\"on\" includeantruntime=\"true\">\n\t\t\t<src path=\"${javasource}\" />\n\t\t</javac>\n\t\t\t\t\n\t\t<war destfile=\"${builddir}/sso.war\" webxml=\"${websource}/WEB-INF/web.xml\" update=\"true\">\n\t\t\t<fileset dir=\"${jssource}\" />\n\t\t    <fileset dir=\"${websource}\" />\n\t\t\t<fileset dir=\"${testsource}\" />\t\t\t\n\t\t\t<classes dir=\"${compilation}\" />\n\t\t\t<lib dir=\"${libdir}\" includes=\"**\" />\n\t\t</war>\n\t</target>\n\t\n</project>"
  },
  {
    "path": "build/gruntfile.js",
    "content": "module.exports = function(grunt) {\n\n  // Project configuration.\n  grunt.initConfig({\n    pkg: grunt.file.readJSON('package.json'),\n    uglify: {\n      options: {\n        banner: '/*! <%= pkg.name %> <%= grunt.template.today(\"yyyy-mm-dd\") %> */\\n'\n      },\n      build: {\n        src: '../client/resources/js/<%= pkg.name %>*.js',\n        dest: '<%= pkg.name %>.min.js'\n      }\n    },\n\tuglify: {\n      build: {\n        src: '../client/resources/html/*.js',\n        dest: 'sso.min.js'\n      }\n    }\n  });\n\n  // Load the plugin that provides the \"uglify\" task.\n  grunt.loadNpmTasks('grunt-contrib-uglify');\n\n  // Default task(s).\n  grunt.registerTask('default', ['uglify']);\n\n};"
  },
  {
    "path": "build/ivy.xml",
    "content": "<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. \n\tSee the NOTICE file distributed with this work for additional information regarding copyright ownership. \n\tThe ASF licenses this file to you under the Apache License, Version 2.0 (the \"License\"); you may not \n\tuse this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 \n\tUnless required by applicable law or agreed to in writing, software distributed under the License is \n\tdistributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n\tSee the License for the specific language governing permissions and limitations under the License. -->\n<ivy-module version=\"2.0\">\n\t<info organisation=\"com.aralink\" module=\"sslssso\" />\n\t<dependencies>\n\t\t<dependency org=\"io.jsonwebtoken\" name=\"jjwt\" rev=\"0.6.0\" conf=\"default\"/>\n\t</dependencies>\n</ivy-module>\n"
  },
  {
    "path": "build/package.json",
    "content": "{\n  \"name\": \"sslssso\",\n  \"version\": \"1.0.0\",\n  \"devDependencies\": {\n    \"grunt\": \"~0.4.5\",\n    \"grunt-contrib-jshint\": \"~0.10.0\",\n    \"grunt-contrib-nodeunit\": \"~0.4.1\",\n    \"grunt-contrib-uglify\": \"~0.5.0\"\n  }\n}"
  },
  {
    "path": "client/resources/html/sso.html",
    "content": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>SSLSignature SSO IFRAME</title>\n\t\t<!-- <script src=\"../js/jquery-1.7.1.min.js\"></script> -->\n\t\t<script src=\"sso_common.js\"></script>\n\t\t<script src=\"sso_rest.js\"></script>\n\t\t<script src=\"sso.js\"></script>\n\t\t<script>\n\t\t\t//GET your params from sslssso.js config or generate this page dynamically on server\n\t\t\t\n\t\t\tvar accountId = getGetParam(\"accountId\");\n\t\t\tvar domain = getGetParam(\"domain\");\n\t\t\tvar validationUrl = getGetParam(\"validationUrl\");\n\t\t\tvar validate = !(getGetParam(\"validate\") == 'false'); \n\t\t\tif (validate && !validationUrl)\n\t\t\t\tvalidationUrl = getOrigin() + '/sslsignature/sso/' + accountId + '/jwt';\n\t\t\t\n\t\t\t\n\t\t\tvar config = {\n\t\t\t\tvalidationUrl: validationUrl,\n                accountId: accountId,\n                apiKey: '',\n                domain: domain,\n                tokenId: 'ssls.sso.jwt.' + accountId,\n                validate: validate\n\t\t\t}    \n\t\t\tinit(config);\n\t\t\t\n\t\t</script>\n\t</head>\n</html>"
  },
  {
    "path": "client/resources/html/sso.js",
    "content": "var validationUrl;\nvar validate;\nvar accountId;\nvar tokenId;\nvar apiKey;\n\t\t\t\nfunction onIdentification(operation){\n\tlog(LogLevels.INFO ,\"[SSO IFRAME] fire event onidentification jwt: \"+ operation.jwt);\n\t\n\t//var domain = getGetParam2(\"domain\");\n\t//if (!domain || domain==\"\")\n\t\tdomain = \"*\";\n\t\n\tpostMessageToListeners (operation,domain);\n}\n\nfunction onLogout(){\n\tlog(LogLevels.INFO ,\"[SSO IFRAME] fire event onlogout \");\n\n\t//var domain = getGetParam2(\"domain\");\n\t//if (!domain || domain==\"\")\n\tdomain = \"*\";\n\tlog(LogLevels.DEBUG,\"[SSO IFRAME] postMessage to: \"+ domain);\n\tvar operation = {action:\"sso.onlogout\"};\n\t\n\tpostMessageToListeners (operation,domain);\n}\n\nfunction onLoad(){\n\tlog(LogLevels.INFO ,\"[SSO IFRAME] fire event onload \");\n\n\t//var domain = getGetParam2(\"domain\");\n\t//if (!domain || domain==\"\")\n\t\tdomain = \"*\";\n\tlog(LogLevels.DEBUG,\"[SSO IFRAME] postMessage to: \"+ domain);\n\tvar operation = {action:\"sso.onload\"};\n\n\tpostMessageToListeners (operation,domain);\n}\n\nfunction postMessageToListeners (operation, domain){\n\tlog(LogLevels.DEBUG,\"[SSO IFRAME] postMessage \"+operation.action+\" to: \"+ domain);\n\tif (window.attachEvent) {   // IE before version 9\n\t\twindow.parent.postMessage(JSON.stringify(operation), domain);\t\n\t} else {\n\t\twindow.parent.postMessage(operation, domain);\t\n\t}\n}\n\n\n\nfunction doLogout(){\n\tlog(LogLevels.INFO,\"[SSO IFRAME] logout \");\n\tlocalStorage.removeItem(tokenId);\n\t\n\tonLogout();\n}\n\nfunction doLogin(jwt){\n\tlog(LogLevels.INFO,\"[SSO IFRAME] login :\"+jwt);\n\tlocalStorage.setItem(tokenId,jwt);\n\t/*if (isIE()){\n\t\t//Mas mierda de IE. En el caso de IE11 no sincroniza entre pestaas si no haces esta guarrera. Y tampoco va\n\t\tlocalStorage.setItem('dummy', 'dummyvalue');\n\t\tlocalStorage.removeItem('dummy');\n\t}\t*/\n}\n\nfunction localStorageHandler(e) {\n\t\n  \tlog(LogLevels.DEBUG,'[SSO IFRAME] Successfully communicate with other tab');\n  \tlog(LogLevels.DEBUG,'[SSO IFRAME] Received data: ' + localStorage.getItem(tokenId));\n  \tvar jwtsso = localStorage.getItem(tokenId);\n  \tif (jwtsso){\n\t\tvalidateJWT (jwtsso);\n\t} else {\n\t\tonLogout();\n\t}\n}\nfunction localStorageHandlerIE8(e) {\n  \tlog(LogLevels.DEBUG,'[SSO IFRAME] Successfully communicate with other tab IE8');\n  \t\n\t// var jwtsso = localStorage.getItem(tokenId); ->  old value in IE\n\t// timeout waiting IE8 browser to update the new value\n\tsetTimeout(function(){\n\t\t\tvar jwtsso = localStorage.getItem(tokenId); // new value\n\t\t\tif (jwtsso){\n\t\t\tvalidateJWT (jwtsso);\n\t\t} else {\n\t\t\tonLogout();\n\t\t}\n\t }, 1); // delay\n}\n\n\nfunction listener(event){\n\t//if ( event.origin !== \"https://pfb.sslsignature.com\" ){\n\t//\treturn;\n\t//}\t \n\tlog(LogLevels.DEBUG,\"[SSO IFRAME] received event \");  \n\n\tvar data = event.data; //Chrome, firefox, IE11 , etc\n\tif (event.data && !event.data.action){ //<=IE8 & IE9 porque no soporta JSON en objetos de mensaje\n\t\tdata  =  eval('(' + event.data+ ')');\n\t}  \n\t\t\t\n\t\n\tif(data.hasOwnProperty('action'))\t{\n\t\tlog(LogLevels.DEBUG,\"[SSO IFRAME] received event \"+data.action);\n\t\tvar action = data.action;\n\t\tif (action == 'logout'){\n\t\t\tdoLogout();\n\t\t} else if (action == 'login'){\n\t\t\tif (data.hasOwnProperty('jwt')){\n\t\t\t\tdoLogin(data.jwt);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog(LogLevels.WARN,\"[SSO IFRAME] received unknown event \");\n\t}\n\t\n}\n\n\nfunction validateJWT(jwtsso){\n\tif (validate && validationUrl){\n\t\t//Invoke server to get remote validation of token signature, parse and return extra data if necessary\n\t\tvalidateJWTRemote(jwtsso);\n\t} else {\n\t\t//Do not validate. Expected token validation on first usage of jwt\n\t\tparseJWTLocal(jwtsso);\n\t}\n\t\n}\n\nfunction validateJWTRemote(jwtsso){\n\tlog(LogLevels.DEBUG,\"[SSO IFRAME] Remote validation of JWT with url: \"+validationUrl+ \" accountId:\"+ accountId+ \" apiKey:\"+apiKey);\n\t\n\tjwt = new JWT(jwtsso);\n\tlog(LogLevels.DEBUG,jwt.payload());\n\tvar rest = new RestClient(validationUrl,accountId,apiKey);\n\t\n\t/*\n\t POST validationUrl\n\t jwt={jwtsso}\n\t \n\t Expected JSON response {status:SUCCESS,sub:yourUserId, jwt:newTokenIfNeeded, eidentifier:username, name:fullname, email:useremail, ... }\n\t or {AuthenticationOperation: {status:SUCCESS,sub:...} }\n\t */\n\trest.validateJWT(jwtsso, \n\t   function (obj){\n\t\t\tvar operation = obj;\n\t\t\tif (obj.AuthenticationOperation){\n\t\t\t\toperation = obj.AuthenticationOperation;\n\t\t\t}\n\t\t\tlog(LogLevels.DEBUG,\"[SSO IFRAME] Validating token \"+operation.status);\n\t\t\t\n\t\t\tif (operation.status == 'SUCCESS') {\n\t\t\t\tlog(LogLevels.INFO,\"[SSO IFRAME] token is valid \");\n\t\t\t\tif (operation.jwt && operation.jwt != jwtsso){\n\t\t\t\t\tlog(LogLevels.INFO,\"[SSO IFRAME] Backend issued a new JWT. Replace current token\");\n\t\t\t\t\tdoLogin(operation.jwt);\n\t\t\t\t} else  {\n\t\t\t\t\toperation.jwt = jwtsso;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\toperation.action = \"sso.onidentification\";\n\t\t\t\t\n\t\t\t\t//Identification successful. Fire onIdentification event\n\t\t\t\tonIdentification(operation);\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tlocalStorage.removeItem(tokenId);\n\t\t\t\tlog(LogLevels.ERROR,\"[SSO IFRAME] invalid token: \"+operation.error);\n\t\t\t}\n\t\t\t//Authentication process finish. //fire onload event\n\t\t\tonLoad();\n\t  },\n\t  function(err) {\n\t\tlog(LogLevels.DEBUG,err);\n\t  });\n\n}\n\nfunction parseJWTLocal(jwtsso){\n\tlog(LogLevels.INFO,\"[SSO IFRAME] Local parse of JWT (no signature validation)\");\n\ttry{\n\t\tvar jwt = new JWT(jwtsso);\n\t\tvar payload = jwt.payload();\n\t\tlog(LogLevels.DEBUG,payload);\n\t\t\n\t\tif (jwt.isExpired())\n\t\t\tthrow (\"JWT expired\");\n\t\t\n\t\t//We have not validated. So UNKNOWN\n\t\tpayload.status = 'UNKNOWN';\n\t\tpayload.action = \"sso.onidentification\";\n\t\tpayload.jwt = jwtsso;\n\t\t\n\t\t//Identification finished. Fire onIdentification event\n\t\tonIdentification(payload);\n\t\n\t} catch (err){\n\t\t//Bad token. remove it\n\t\tlocalStorage.removeItem(tokenId);\n\t\tlog(LogLevels.ERROR,\"[SSO IFRAME] invalid token: \"+err);\n\t}\t\n\t//Authentication process finish. //fire onload event\n\tonLoad();\n}\n\nfunction ready(){\n\tvar jwtsso = localStorage.getItem(tokenId);\n\tlog(LogLevels.INFO,\"[SSO IFRAME] ready\");\n\tlog(LogLevels.DEBUG,\"[SSO IFRAME] \" + tokenId + \" = \"+jwtsso);\n\tif (jwtsso){\n\t\tvalidateJWT (jwtsso);\n\t} else {\n\t\t//OnLoad must be the last method invocation. Invoked head or from validateJWT after token validation \n\t\tonLoad();\n\t}\t\n}\t\n\nfunction init(config){\n\t//Listener for localStorage changes of ssls.sso.jwt.[accountId] tokens\n\tif (window.addEventListener) {\n\t\t// Normal browsers\n\t\twindow.addEventListener(\"storage\", localStorageHandler, false);\n\t} else {\n\t  \t// for IE (why make your life more difficult)\n\t\t//Adems hay que suscribierse al documento y no al windows\n\t\t//Y para acabar de tocar los huevos, localStorage.getItem devuelve el valor viejo y no el nuevo. Por supuesto el evento no lleva la informacion\n\t\t//window.attachEvent(\"onstorage\", localStorageHandlerIE8);\n\t\tdocument.attachEvent(\"onstorage\", localStorageHandlerIE8);\n\t\t\n\t};\t\t\n\t\n\t//Iframe message listener from SSO clients\n\tif (window.addEventListener){\n\t\taddEventListener(\"message\", listener, false);\n\t} else {\n\t\tattachEvent(\"onmessage\", listener);\n\t}\n\t\n\t//onLoad document listener\n\tif (window.addEventListener) {\n\t\t// W3C standard\n\t  window.addEventListener('load', ready, false); // NB **not** 'onload'\n\t} else if (window.attachEvent){\n\t\t // Microsoft\n\t  window.attachEvent('onload', ready);\n\t}\n\t\n\tvalidationUrl = config.validationUrl;\n\tvalidate = config.validate;\n\taccountId = config.accountId;\n\ttokenId = config.tokenId;\n\tapiKey = config.apiKey;\n\tlog(LogLevels.INFO,\"[SSO IFRAME] inited\");\n}\n\n//init();\n\t\t"
  },
  {
    "path": "client/resources/html/sso_common.js",
    "content": "\nvar LogLevels = {DEBUG:0, INFO:1, WARN:2, ERROR:3};\nvar logLevel = LogLevels.DEBUG;\nvar console = window.console || { log: function() {} };\nvar Base64={_keyStr:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",encode:function(e){var t=\"\";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t=\"\";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,\"\");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,\"n\");var t=\"\";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t=\"\";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}\n\nfunction log(level, object){\n\tif (level >= logLevel){\n\t\tconsole.log (object);\n\t}\t\n}\n\nfunction getOrigin(){\n\tif (!window.location.origin) {\n\t\twindow.location.origin = window.location.protocol + \"//\" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');\n\t}\n\treturn window.location.origin;\n}\n\nfunction getGetParam (vr){\n    var src = String( window.location.href ).split('?')[1];\n        \n    if (src != null) {\n      \tvar vrs = src.split('&');\n \n       \tfor (var x = 0, c = vrs.length; x < c; x++)\t{\t\n        \t\tif (vrs[x].indexOf(vr) == 0){\n        \t\t\treturn decodeURI( vrs[x].split('=')[1] );\n        \t\t\tbreak;\n        \t\t};\n        \t};\n    } else {\n      \t return \"\";\n    }\n};\n\n\nfunction JWT (jwt){\n\t\"use strict\";\n\t this.header = function() {\n\t\t var headerB64u = jwt.substring(0,jwt.indexOf('.')); \n\t\t var headerB64 = _b64utob64(headerB64u);\n\t\t var headerJSON = Base64.decode(headerB64);\n\t\t var header = JSON.parse( headerJSON );\n\t\t return header;\n\t };\t\n\t this.payload = function() {\n\t\t var payloadB64u = jwt.substring(jwt.indexOf('.') + 1, jwt.lastIndexOf('.')); \n\t\t var payloadB64 = _b64utob64(payloadB64u);\n\t\t var payloadJSON = Base64.decode(payloadB64);\n\t\t var payload = JSON.parse( payloadJSON );\n\t\t return payload;\n\t };\t\n\t \n\t this.isExpired = function(){\n\t\t var body = this.payload();\n\t\t if (body.exp){\n\t\t\t return body.exp <= Date.now()/1000;\n\t\t } else {\n\t\t\t return true;\n\t\t }\n\t\t \t \n\t };\n\t \n\t \n\n\tfunction _b64tob64u(a){\n\t\ta=a.replace(/\\=/g,\"\");\n\t\ta=a.replace(/\\+/g,\"-\");\n\t\ta=a.replace(/\\//g,\"_\");\n\t\treturn a;\n\t};\n\t\n\tfunction _b64utob64(a){\n\t\tif(a.length%4==2){\n\t\t\ta=a+\"==\";\n\t\t}else{\n\t\t\tif(a.length%4==3){\n\t\t\t\ta=a+\"=\";\n\t\t\t}\n\t\t}\n\t\ta=a.replace(/-/g,\"+\");\n\t\ta=a.replace(/_/g,\"/\");\n\t\treturn a;\n\t};\n};\n"
  },
  {
    "path": "client/resources/html/sso_rest.js",
    "content": "\t\nfunction RestClient (host,accountId,apiKey,scheme){\n\t\"use strict\";\n\t\n    //this.host = host;\n    //this.accountId = accountId;\n\t//this.apiKey = apiKey;\n\tscheme = _validateScheme(scheme);\n\n\t\n\t\n\t\n\tthis.validateJWT = function (jwt,fulfill,reject){\n\t\t//var uri = host+'/sso/' + accountId + '/jwt';\n\t\tvar uri = host;\n\t\tvar request = {'jwt':jwt};\n\t\treturn _postFormNoJQuery(uri,request,fulfill,reject);\n\t};\n\t\n\tfunction _validateScheme(scheme){\n\t\tif (!scheme)\n\t\t\tscheme = \"Basic\";\n\n\t\tif ( !(scheme == 'Basic' || scheme == 'JWT' || scheme == 'CJWT' ))\n\t\t\tthrow \"Scheme \" + scheme + \"not valid\";\n\t\t\n\t\treturn scheme;\n\t}\n\t\n\tfunction _makeAuth(scheme, user, password) {\n\t\tvar tok = user + ':' + password;\n\t\tvar hash;\n\t\tif (window.btoa){\n\t\t\thash = btoa(tok);\n\t\t} else  {\n\t\t\thash = Base64.encode(tok);\n\t\t}\t\n\t\treturn scheme + \" \" + hash;\n\t}\n\t\n\tfunction _get(url,fulfill,reject){\n\t\t\tvar contentType = \"application/json; charset=utf-8\";\t\t\n\t\t\t\n\t\t\tlog(LogLevels.INFO, \"GET \"+url+ \" \"+contentType);\n\t\t\t\n\t\t\t$.support.cors = true;\n\t\t\t$.ajax({\n\t\t\t\ttype: \"GET\", //GET or POST or PUT or DELETE verb\n\t\t\t\turl: url, // Location of the service\t\n\t\t\t\tcrossdomain: true,\n\t\t\t\tcontentType: contentType,\t\t\n\t\t\t\taccepts: { text: \"application/json\" },\n\t\t\t\tdataType: \"json\",\n\t\t\t\tbeforeSend: function (xhr) {\n\t\t\t\t\txhr.setRequestHeader(\"Authorization\", _makeAuth(scheme, accountId,apiKey));\n\t\t\t\t}\n\t\t\t}).done(function (response)\t{\t\n\t\t\t\tresponse = _decodeJson(response);\n\t\t\t\tfulfill(response);\n\t\t\t}).fail(function (err)\t{\n\t\t\t\treject(err);\n\t\t\t});\n\t}\n\t\n\t\n\t\n\tfunction _post(url, request,fulfill,reject){\n\t\t\n\t\t\tvar contentType = \"application/json; charset=utf-8\";\n\t\t\tvar jsondata = null;\n\t\t\tif (request)\n\t\t\t\tjsondata = JSON.stringify(request, null, 4);\n\t\t\t\n\t\t\tlog(LogLevels.INFO, \"POST \"+url+ \" \"+contentType);\n\t\t\tlog(LogLevels.DEBUG, \"  Request: \"+jsondata);\n\t\t\n\t\t\t$.support.cors = true;\n\t\t\t$.ajax({\n\t\t\t\ttype: \"POST\", //GET or POST or PUT or DELETE verb\n\t\t\t\turl: url, // Location of the service\n\t\t\t\tdata: jsondata, //Data sent to server\n\t\t\t\tcontentType: contentType,\t\t\t\n\t\t\t\tcrossdomain: true,\n\t\t\t\tbeforeSend: function (xhr) {\n\t\t\t\t\txhr.setRequestHeader(\"Authorization\", _makeAuth(scheme, accountId,apiKey));\n\t\t\t\t}\n\t\t\t}).done(function (response)\t{\n\t\t\t\t\n\t\t\t\tresponse = _decodeJson(response);\n\t\t\t\tfulfill(response);\n\t\t\t}).fail(function (err)\t{\n\t\t\t\treject(err);\n\t\t\t});\n\t\t\n\t\t\n\t}\n\t\n\tfunction _postForm(url, request,fulfill,reject){\n\t\t//return new Promise(function(fulfill, reject) {\n\t\t\t//var contentType = \"application/json; charset=utf-8\";\n\t\t\tvar contentType = \"application/x-www-form-urlencoded\";\n\t\t\tvar jsondata = null;\n\t\t\tif (request)\n\t\t\t\tjsondata = JSON.stringify(request, null, 4);\n\t\t\t\n\t\t\tlog(LogLevels.INFO, \"POST \"+url+ \" \"+contentType);\n\t\t\tlog(LogLevels.DEBUG, \"  Request: \"+jsondata);\n\t\t\n\t\t\t$.support.cors = true;\n\t\t\t$.ajax({\n\t\t\t\ttype: \"POST\", //GET or POST or PUT or DELETE verb\n\t\t\t\turl: url, // Location of the service\n\t\t\t\tdata: request, //Data sent to server\n\t\t\t\tcontentType: contentType,\t\t\t\n\t\t\t\tcrossdomain: true,\n\t\t\t\tbeforeSend: function (xhr) {\n\t\t\t\t\txhr.setRequestHeader(\"Authorization\", _makeAuth(scheme, accountId,apiKey));\n\t\t\t\t}\n\t\t\t}).done(function (response)\t{\n\t\t\t\t\n\t\t\t\tresponse = _decodeJson(response);\n\t\t\t\tfulfill(response);\n\t\t\t}).fail(function (err)\t{\n\t\t\t\treject(err);\n\t\t\t});\n\t\t//});\n\t\t\n\t}\n\t\n\tfunction _postFormNoJQuery(url, request,fulfill,reject){\n\t\t\n\t\t\tvar contentType = \"application/x-www-form-urlencoded\";\n\t\t\tvar jsondata = null;\n\t\t\tif (request)\n\t\t\t\tjsondata = JSON.stringify(request, null, 4);\n\t\t\t\n\t\t\tlog(LogLevels.INFO, \"POST \"+url+ \" \"+contentType);\n\t\t\tlog(LogLevels.DEBUG, \"  Request: \"+jsondata);\n\t\t\t\n\t\t\t_ajax.post(\n\t\t\t\t\turl,\n\t\t\t\t\trequest,\n\t\t\t\t\tfunction (response)\t{\n\t\t\t\t\t\t\n\t\t\t\t\t\tresponse = _decodeJson(response);\n\t\t\t\t\t\tfulfill(response);\n\t\t\t\t\t});\n\t}\n\t\n\tfunction _delete(url,fulfill,reject){\n\t\t\n\t\t\tvar contentType = \"application/json; charset=utf-8\";\n\t\t\tvar jsondata = null;\n\n\t\t\tlog(LogLevels.INFO, \"DELETE \"+url+ \" \"+contentType);\n\t\t\n\t\t\t$.support.cors = true;\n\t\t\t$.ajax({\n\t\t\t\ttype: \"DELETE\", //GET or POST or PUT or DELETE verb\n\t\t\t\turl: url, // Location of the service\n\t\t\t\tdata: jsondata, //Data sent to server\n\t\t\t\tcontentType: contentType,\t\t\t\n\t\t\t\tcrossdomain: true,\n\t\t\t\tbeforeSend: function (xhr) {\n\t\t\t\t\txhr.setRequestHeader(\"Authorization\", _makeAuth(scheme, accountId,apiKey));\n\t\t\t\t}\n\t\t\t}).done(function (response)\t{\n\t\t\t\tresponse = _decodeJson(response);\n\t\t\t\tfulfill(response);\n\t\t\t}).fail(function (err)\t{\n\t\t\t\treject(err);\n\t\t\t});\n\t}\n\t\n\t\n\tfunction _isAbv(value) {\n\t\tvar ArrayBufferView = Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;\n\t    return value instanceof ArrayBufferView;\n\t}\n\tfunction _isAb(value) {\n\t    return value && value instanceof ArrayBuffer && value.byteLength;\n\t}\n\t\n\tfunction _postStream(url, data,fulfill,reject){\n\t\t\n\t\t\tvar contentType = \"application/octet-stream\";\n\t\t\n\t\t\tlog(LogLevels.INFO, \"POST \"+url+ \" \"+contentType);\n\t\t\tlog(LogLevels.DEBUG, data);\n\t\t\t\n\t\t\tif (!_isAbv(data) &&  !_isAb(data))\n\t\t\t\tthrow \"data is not an ArrayBuffer\";\n\t\t\t\n\t\t\t$.support.cors = true;\n\t\t\t$.ajax({\n\t\t\t\ttype: \"POST\", //GET or POST or PUT or DELETE verb\n\t\t\t\turl: url, // Location of the service\n\t\t\t\tdata: data, //Data sent to server\n\t\t\t\tcontentType: contentType,\n\t\t\t\tprocessData: false,\n\t\t\t\tcrossdomain: true,\n\t\t\t\tbeforeSend: function (xhr) {\n\t\t\t\t\txhr.setRequestHeader(\"Authorization\", _makeAuth(scheme, accountId,apiKey));\n\t\t\t\t}\n\t\t\t}).done(function (response)\t{\n\t\t\t\tresponse = _decodeJson(response);\n\t\t\t\tfulfill(response);\n\t\t\t}).fail(function (err)\t{\n\t\t\t\treject(err);\n\t\t\t});\n\t\t\n\t}\n\t\n\tfunction _decodeJson(response) {\n\t\tif (response){\n\t\t\tvar jsonresponse = response; \n\t\t\tif (typeof response === 'object')\n\t\t\t\tjsonresponse = JSON.stringify(response, null, 4);\n\t\t\tlog(LogLevels.DEBUG, \"  Response: \"+jsonresponse);\n\t\t\tvar obj = JSON.parse( jsonresponse );\n\t\t\treturn obj;\n\t\t}else {\n\t\t\tlog(LogLevels.DEBUG, \"  Response: NULL\");\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tfunction _convertMimetype(mimetype){\n\t\tif (mimetype == 'gallery/manual')\n\t\t\treturn 'application/pdf';\n\t\telse if (mimetype == 'application/binary')\n\t\t\treturn 'application/pdf';\n\t\treturn mimetype;\n\t }\n\t\n\tvar _ajax = {};\n\t_ajax.x = function () {\n\t    if (typeof XMLHttpRequest !== 'undefined') {\n\t        return new XMLHttpRequest();\n\t    }\n\t    var versions = [\n\t        \"MSXML2.XmlHttp.6.0\",\n\t        \"MSXML2.XmlHttp.5.0\",\n\t        \"MSXML2.XmlHttp.4.0\",\n\t        \"MSXML2.XmlHttp.3.0\",\n\t        \"MSXML2.XmlHttp.2.0\",\n\t        \"Microsoft.XmlHttp\"\n\t    ];\n\n\t    var xhr;\n\t    for (var i = 0; i < versions.length; i++) {\n\t        try {\n\t            xhr = new ActiveXObject(versions[i]);\n\t            break;\n\t        } catch (e) {\n\t        }\n\t    }\n\t    return xhr;\n\t};\n\n\t_ajax.send = function (url, callback, method, data, async) {\n\t    if (async === undefined) {\n\t        async = true;\n\t    }\n\t    var x = _ajax.x();\n\t    x.open(method, url, async);\n\t    x.onreadystatechange = function () {\n\t        if (x.readyState == 4) {\n\t            callback(x.responseText);\n\t        }\n\t    };\n\t    if (method == 'POST') {\n\t        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n\t    }\n\t    x.send(data);\n\t};\n\n\t_ajax.get = function (url, data, callback, async) {\n\t    var query = [];\n\t    for (var key in data) {\n\t        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));\n\t    }\n\t    _ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async);\n\t};\n\n\t_ajax.post = function (url, data, callback, async) {\n\t    var query = [];\n\t    for (var key in data) {\n\t        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));\n\t    }\n\t    _ajax.send(url, callback, 'POST', query.join('&'), async);\n\t};\n\t\n\t\n\n};\n\n\n"
  },
  {
    "path": "client/resources/js/sslssso.js",
    "content": "sslssso = new sslssso();\nvar console = window.console || { log: function() {} };\n\nfunction Observable(){\n\t\n    this.listen = function(type, method, scope, context) {\n        var listeners, handlers;\n        if (!(listeners = this.listeners)) {\n            listeners = this.listeners = {};\n        }\n        if (!(handlers = listeners[type])){\n            handlers = listeners[type] = [];\n        }\n        scope = (scope ? scope : window);\n        handlers.push({\n            method: method,\n            scope: scope,\n            context: (context ? context : scope)\n        });\n    }\n    this.fireEvent =  function(type, data, context) {\n        var listeners, handlers, i, n, handler, scope;\n        if (!(listeners = this.listeners)) {\n            return;\n        }\n        if (!(handlers = listeners[type])){\n            return;\n        }\n        for (i = 0, n = handlers.length; i < n; i++){\n            handler = handlers[i];\n            if (typeof(context)!==\"undefined\" && context !== handler.context) continue;\n            if (handler.method.call(\n                handler.scope, this, type, data\n            )===false) {\n                return false;\n            }\n        }\n        return true;\n    }\n};\n\nfunction sslssso (){\n\t//\"use strict\";\n\t \n   \n    var DEFAULT_IFRAME_URI = \"../html/sso.html\";\n    \n    var obs = new Observable();\n    var config = {};\n    /*\n    obs.listen(\"sso.onload\", function(observable, eventType, data){\n        console.log(\"----------------\");\n        console.log(\"sso.onload\");\n        console.log(\"----------------\");\n    });\n    */\n    this.listen = function(type, method, scope, context){\n    \tobs.listen(type,method,scope,context);\n    }\n    \n    this.logout = function (){\n\t\tvar message = {action: \"logout\"};\n\t\tpostSSOMessage(message, _getUrl());\n\t}\n\t\n    this.login = function (jwt){\n\t\tvar message = {action: \"login\",jwt:jwt};\n\t\tpostSSOMessage(message, _getUrl());\n\t}\n    \n\n\tfunction _getMeta(name){\n\t\tvar metas = document.getElementsByTagName('meta'); \n\t\t\n\t\tfor (var i=0; i<metas.length; i++) { \n\t\t     if (metas[i].getAttribute(\"name\") == name) { \n\t\t        return metas[i].getAttribute(\"content\"); \n\t\t     } \n\t\t}\n\t\treturn null;\n\t}\t\n\t\n\tfunction _getAccountId() { \n\t\tif (config.accountId){\n\t\t\treturn config.accountId;\n\t\t} else if (_getMeta(\"ssls.accountId\")){\n\t\t\treturn _getMeta(\"ssls.accountId\");\n\t\t} else if (typeof ssls_accountId !== 'undefined' && ssls_accountId) {\n\t\t   return ssls_accountId;\n\t\t}\t\n\t\t\n\t    return null;\n\t}\n\tfunction _getValidationUrl() { \n\t\tif (config.validationUrl){\n\t\t\treturn config.validationUrl;\n\t\t} else if (_getMeta(\"ssls.validationUrl\")){\n\t\t\treturn _getMeta(\"ssls.validationUrl\");\n\t\t} else if (typeof ssls_validationUrl !== 'undefined' && ssls_validationUrl) {\n\t\t   return ssls_validationUrl;\n\t\t}\n\t\t\n\t    return null;\n\t}\n\t\n\tfunction _getValidate() { \n\t\tif (config.validate){\n\t\t\treturn config.validate;\n\t\t} else if (_getMeta(\"ssls.validate\")){\n\t\t\treturn _getMeta(\"ssls.validate\");\n\t\t} \n\t\t\n\t    return null;\n\t}\n    \n\t var _getScriptURL = (function() {\n\t        var scripts = document.getElementsByTagName('script');\n\t        var index = scripts.length - 1;\n\t        var myScript = scripts[index];\n\t        return function() { return myScript.src; };\n\t })();\n\t \n\t\n\tfunction _getIframeUrl(){\n\t\tvar parser = document.createElement('a');\n    \tparser.href = _getScriptURL();   \t\n\n    \tvar pathname = parser.pathname.substring(0, parser.pathname.lastIndexOf(\"/\"));\n    \tvar url = parser.protocol + \"//\"+ parser.host + \"/\" + pathname + \"/\" + DEFAULT_IFRAME_URI;\n    \t\n    \tvar origin = document.location.origin;\n    \tvar accountId = _getAccountId();\n    \tvar validationUrl = _getValidationUrl();\n    \tvar validate = _getValidate();\n    \t\n    \turl = url + \"?domain=\"+origin;\n    \tif (accountId){\n    \t\turl = url + \"&accountId=\"+accountId;\n    \t}\n    \t\n    \tif (validationUrl){\n    \t\turl = url + \"&validationUrl=\"+validationUrl;\n    \t}\n    \t\n    \tif (validate != null){\n    \t\turl = url + \"&validate=\"+validate;\n    \t}\n    \treturn url;\n\t}\t\n\t\n    function _getUrl(){\n    \t\n    \t//https://gist.github.com/jlong/2428561\n    \tvar parser = document.createElement('a');\n    \tparser.href = _getScriptURL();\n    \treturn parser.protocol + \"//\"+ parser.host\n\n       /*\n    \tvar metas = document.getElementsByTagName('meta'); \n    \t\n \t   for (var i=0; i<metas.length; i++) { \n \t\t  \n \t      if (metas[i].getAttribute(\"name\") == \"ssls.url\") { \n \t         return metas[i].getAttribute(\"content\"); \n \t      } \n \t   }\n \t  if (typeof ssls_url !== 'undefined' && ssls_url) {\n\t\t   return ssls_url;\n\t  }\n \t  return DEFAULT_URL;\n \t  */\n    }\n    \n    function postSSOMessage(message,domain){\n    \tvar win = document.getElementById(\"ssls.sso.iframe\").contentWindow;\n    \tconsole.log(\"[SSLS SSO] postMessage \"+message.action+\" to \"+_getUrl());\n    \tif (window.attachEvent) {   // IE before version 9\n\t\t\t//TODO No acaba de funcionar en ie8\n  \t\t\twin.postMessage(JSON.stringify(message), \"*\");\t\n\t\t} else {\n\t\t\twin.postMessage(message, _getUrl());\n\t\t}\n    }\n    \n    function dispatchEvent(eventName, detail){\n    \tconsole.log (\"[SSLS SSO] dispatchEvent \"+eventName);\n    \tobs.fireEvent(eventName, detail);\n    }\n\n\tfunction _listener(event){\n\t\t\n\t\tif (  _getUrl().lastIndexOf(event.origin ) == -1){\n\t\t\treturn;\n\t\t}\n\n\t\tvar data = event.data; //Chrome, firefox, IE11 , etc\n\t\tif (event.data && !event.data.action){ //<=IE8 & IE9 porque no soporta JSON en objetos de mensaje\n\t\t\tdata  =  eval('(' + event.data+ ')');\n\t\t} \n\t\t\t\t\n\t\t\n\t\tif (data && data .action == \"sso.onlogout\"){\n\t\t\tconsole.log(\"[SSLS SSO] received event onlogout\");\n\t\t\tif (typeof(onLogout) == \"function\")\n\t\t\t\tonLogout();\n\t\t\tdispatchEvent('sso.onlogout'); \n\t\t} else if (data && data.action == \"sso.onload\") {\n\t\t\tconsole.log(\"[SSLS SSO] received event onload \");\n\t\t\tif (typeof(onLoad) == \"function\")\n\t\t\t\tonLoad();\n\t\t\tdispatchEvent('sso.onload'); \n\t\t\t\n\t\t}else if (data && data.action == \"sso.onidentification\") {\n\t\t\tconsole.log(\"[SSLS SSO] received event onidentification \");\n\t\t\tif (typeof(onIdentification) == \"function\")\n\t\t\t\tonIdentification(data);\n\t\t\tdispatchEvent('sso.onidentification',data);\n\t\t}\t\n\t}\n\t\n\t\n\t\n\tfunction _init(){\n\t\t\n\t\t\n\t\tvar accountId = _getAccountId();\n\t\tconsole.log (\"[SSLS SSO] accountId = \"+accountId + \" SSOServerUrl= \" +_getUrl());\n\t\t\n\t\t//Message listener for SSO events (created by the SSO iframe)\n\t\tif (window.addEventListener){\n\t\t\taddEventListener(\"message\", _listener, false)\n\t\t} else {\n\t\t\tattachEvent(\"onmessage\", _listener)\n\t\t}\n\t\t\t\t\t\n\t\t//Creates the iframe with reference to server SSO functions\n\t\tvar iframeUrl = _getIframeUrl()\n\t\tconsole.log (\"[SSLS SSO] create iframe: \"+ iframeUrl);\n\t    var iframe = document.createElement('iframe');\n\t\tiframe.style.display = \"none\";\n\t\tiframe.src = iframeUrl;\n\t\tiframe.id = 'ssls.sso.iframe';\n\t\tdocument.body.appendChild(iframe);\n\t}\n\t\n\tfunction init(conf){\n\t\tif (conf){\n\t\t\tconfig = conf;\n\t\t}\t\n\t}\n\t\n\tif (window.addEventListener) {\n\t\t// W3C standard\n\t  window.addEventListener('load', _init, false); // NB **not** 'onload'\n\t} else if (window.attachEvent){\n\t\t // Microsoft\n\t  window.attachEvent('onload', _init);\n\t}\n\n}\t\n\t\n\t\n\n\n\n\n"
  },
  {
    "path": "test/java/com/aralink/sslsignature/sso/jwt/test/JWTTest.java",
    "content": "package com.aralink.sslsignature.sso.jwt.test;\n\n\nimport io.jsonwebtoken.Jwts;\nimport io.jsonwebtoken.impl.crypto.MacProvider;\n\nimport java.security.Key;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\n\n\n\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.aralink.sslsignature.sso.jwt.JWTManager;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n\npublic class JWTTest {\n\tRestClient client;\n\t\n\t@BeforeClass\n\tpublic static void setUpBeforeClass() throws Exception {\n\t}\n\n\t@AfterClass\n\tpublic static void tearDownAfterClass() throws Exception {\n\n\t}\n\n\t@Before\n\tpublic void setUp() throws Exception {\n\t\tclient = new RestClient(\"https://pfb.sslsignature.com\");\n\t}\n\n\t@After\n\tpublic void tearDown() throws Exception {\n\t}\n\n\n\t@Test\n\tpublic void issueAndValidateJWT() throws Exception {\n\t\tMap<String,String> jwtInfo = new HashMap<String,String>();\n\t\tjwtInfo.put(\"sub\", \"theSub\");\n\t\tjwtInfo.put(\"eidentifier\", \"theEidentifier\");\n\t\tjwtInfo.put(\"name\", \"theName\");\n\t\tjwtInfo.put(\"phone\", \"thePhone\");\n\t\tjwtInfo.put(\"other\", \"theOther\");\n\t\t\n\t\t//REquest a new JWT to server\n\t\tString jwt = client.postForm(\"/sso/jwt\", jwtInfo);\n\t\tSimpleConsoleLogger.info(jwt);\n\t\tAssert.assertNotNull(jwt);\n\t\t\n\t\t//Validate the token signature\n\t\tMap<String,String> jwtValidationInfo = new HashMap<String,String>();\n\t\tjwtValidationInfo.put(\"jwt\", jwt);\n\t\tString authenticationResponseJson = client.postForm(\"/sso/jwt\", jwtValidationInfo);\n\t\tSimpleConsoleLogger.info(authenticationResponseJson);\n\t\t\n\t\t//JWT token validated on server to Java Object \n\t\tMap<String, Object> map = new HashMap<String, Object>();\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tmap = mapper.readValue(authenticationResponseJson, new TypeReference<Map<String, String>>(){});\n\t\t\n\t\tSimpleConsoleLogger.info(\"STATUS: \"+map.get(\"status\")+ \" eidentifier\"+ map.get(\"eidentifier\"));\n\t\t\n\t\tAssert.assertEquals(\"SUCCESS\", map.get(\"status\"));\n\t\t\t\t\n\t}\n\t\n\t@Test\n\tpublic void alteredJWT() throws Exception {\n\t\tMap<String,String> jwtInfo = new HashMap<String,String>();\n\t\tjwtInfo.put(\"sub\", \"theSub\");\n\t\tjwtInfo.put(\"eidentifier\", \"theEidentifier\");\n\t\tjwtInfo.put(\"name\", \"theName\");\n\t\tjwtInfo.put(\"phone\", \"thePhone\");\n\t\tjwtInfo.put(\"other\", \"theOther\");\n\t\t\n\t\t//REquest a new JWT to server\n\t\tString jwt = client.postForm(\"/sso/jwt\", jwtInfo);\n\t\tSimpleConsoleLogger.info(jwt);\n\t\tAssert.assertNotNull(jwt);\n\t\t\n\t\t//Signature modified\n\t\tjwt = jwt + \"XXX\";\n\t\t\n\t\t//Validate the token signature\n\t\tMap<String,String> jwtValidationInfo = new HashMap<String,String>();\n\t\tjwtValidationInfo.put(\"jwt\", jwt);\n\t\tString authenticationResponseJson = client.postForm(\"/sso/jwt\", jwtValidationInfo);\n\t\tSimpleConsoleLogger.info(authenticationResponseJson);\n\t\t\n\t\t//JWT token validated on server to Java Object \n\t\tMap<String, Object> map = new HashMap<String, Object>();\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tmap = mapper.readValue(authenticationResponseJson, new TypeReference<Map<String, String>>(){});\n\t\t\n\t\tSimpleConsoleLogger.info(\"STATUS: \"+map.get(\"status\")+ \" eidentifier\"+ map.get(\"eidentifier\"));\n\t\t\n\t\tAssert.assertEquals(\"FAIL\", map.get(\"status\"));\n\t\t\t\t\n\t}\n\t\n\t@Test\n\tpublic void fakeJWT() throws Exception {\n\t\t//Create a token with a key autogenerated (not server key)\n\t\tKey key = MacProvider.generateKey(JWTManager.DEFAULT_HMAC_KEY_ALGORITHM);\n\t\tString jwt =  Jwts.builder()\n\t\t\t\t.setSubject(\"fake\")\n\t\t\t\t.signWith(JWTManager.DEFAULT_HMAC_SIGNATURE_ALGORITHM, key).compact();\n\t\t\n\t\t//Validate token\t\t\n\t\tMap<String,String> jwtValidationInfo = new HashMap<String,String>();\n\t\tjwtValidationInfo.put(\"jwt\", jwt);\n\t\tString authenticationResponseJson = client.postForm(\"/sso/jwt\", jwtValidationInfo);\n\t\tSimpleConsoleLogger.info(authenticationResponseJson);\n\t\t\n\t\t\n\t\t//JWT token validated on server to Java Object \n\t\tMap<String, Object> map = new HashMap<String, Object>();\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tmap = mapper.readValue(authenticationResponseJson, new TypeReference<Map<String, String>>(){});\n\t\t\n\t\tSimpleConsoleLogger.info(\"STATUS: \"+map.get(\"status\")+ \" eidentifier\"+ map.get(\"eidentifier\"));\n\t\t\n\t\tAssert.assertEquals(\"FAIL\", map.get(\"status\"));\n\t}\n}\n"
  },
  {
    "path": "test/java/com/aralink/sslsignature/sso/jwt/test/RestClient.java",
    "content": "package com.aralink.sslsignature.sso.jwt.test;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.Map;\n\nimport javax.xml.bind.DatatypeConverter;\n\n\npublic class RestClient {\n\tprivate static final String CONTENT_TYPE_OCTET_STREAM =\t\"application/octet-stream\";\n\tprivate static final String CONTENT_TYPE_JSON =\t\"application/json\";\n\tprivate static final String CONTENT_TYPE_FORM =\t\"application/x-www-form-urlencoded\";\n\t\n\tprivate String baseurl;\n\tprivate String user;\n\tprivate String password;\n\n\tpublic RestClient (String url){\n\t\tsetUrl(url);\n\t}\n\n\tpublic RestClient (String url, String user, String password){\n\t\tsetUrl(url);\n\t\tsetUser(user);\n\t\tsetPassword(password);\t\t\n\t}\n\n\n\tpublic String getUrl() {\n\t\treturn baseurl;\n\t}\n\tpublic void setUrl(String url) {\n\t\tthis.baseurl = url;\n\t}\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\tpublic void setUser(String user) {\n\t\tthis.user = user;\n\t}\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\n\n\tpublic String postJson(String uri, String jsonRequest) throws IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"POST\",uri,CONTENT_TYPE_JSON);\n\t\tconn.connect();\n\t\tSimpleConsoleLogger.debug(\"request body: \"+jsonRequest);\n\t\tupload(conn,jsonRequest.getBytes());\n\n\t\treturn processJsonResponse(conn);\n\t} \n\t\n\tpublic String postForm(String uri, Map<String, String> formParams) throws IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"POST\",uri,CONTENT_TYPE_FORM);\n\t\tconn.connect();\n\t\tString request = serialize(formParams);\n\t\tSimpleConsoleLogger.debug(\"request body: \"+formParams);\n\t\tupload(conn,request.getBytes());\n\n\t\treturn processJsonResponse(conn);\n\t} \n\n\tpublic String post(String uri) throws IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"POST\",uri,CONTENT_TYPE_JSON);\n\t\tconn.connect();\n\t\treturn processJsonResponse(conn);\n\t} \n\n\tpublic String get(String uri) throws IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"GET\",uri,CONTENT_TYPE_JSON);\n\t\tconn.setRequestProperty(\"Accept\", CONTENT_TYPE_JSON);\n\t\tconn.connect();\n\t\treturn processJsonResponse(conn);\n\n\t} \n\n\tpublic InputStream getStream(String uri) throws IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"GET\",uri,CONTENT_TYPE_JSON);\n\t\tconn.connect();\n\t\treturn processStreamResponse(conn);\n\n\t} \n\n\tpublic String delete(String uri) throws IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"DELETE\",uri,CONTENT_TYPE_JSON);\n\t\tconn.connect();\n\t\treturn processJsonResponse(conn);\n\t} \n\n\tpublic String postStream(String uri, byte data[])throws  IOException{\n\n\t\tHttpURLConnection conn = getConnection(\"POST\",uri,CONTENT_TYPE_OCTET_STREAM);\n\t\tconn.connect();\n\t\tupload(conn,data);\n\t\treturn processJsonResponse(conn);\n\t}\n\n\tprivate String processJsonResponse(HttpURLConnection conn)throws IOException{\n\n\t\tint statusCode = conn.getResponseCode();\n\t\tSimpleConsoleLogger.info(\"response code: \"+statusCode);\n\t\tif (statusCode == 200 ||statusCode == 201 ||statusCode == 204) {\n\t\t\t//OK\n\t\t\tInputStream is = conn.getInputStream();\n\t\t\tString responseString = read(is);\n\t\t\tSimpleConsoleLogger.debug(\"response body: \"+responseString);\n\t\t\treturn responseString;\n\t\t} else {\n\t\t\tInputStream is =conn.getErrorStream();\n\t\t\tString error = read(is);\n\n\t\t\tthrow new IOException(error);\n\t\t}\n\t}\n\n\tprivate InputStream processStreamResponse(HttpURLConnection conn)throws IOException{\n\n\t\t//Recibe respuesta\n\t\tint statusCode = conn.getResponseCode();\n\t\tSimpleConsoleLogger.info(\"response code: \"+statusCode);\n\t\tif (statusCode == 200 ||statusCode == 201) {\n\t\t\tInputStream is = conn.getInputStream();\n\t\t\treturn is;\n\t\t} else {\n\t\t\tInputStream is =conn.getErrorStream();\n\t\t\tString error = read(is);\n\n\t\t\tthrow new IOException(error);\n\t\t}\n\t}\n\n\tprivate void upload(HttpURLConnection conn, byte data[]) throws IOException{\n\t\tOutputStream os = conn.getOutputStream();\n\t\tos.write(data);\n\t\tos.flush();\n\t\tos.close();\n\t}\n\n\tprivate HttpURLConnection getConnection(String method,String uri, String contentType) throws IOException{\n\t\tString URL = baseurl + uri; \n\t\tSimpleConsoleLogger.info(method+\" \"+URL);\n\t\tSimpleConsoleLogger.debug(\"username:\"+user+ \" PASSWORD:\"+password);\n\t\tURL url = new URL(URL);\n\t\tHttpURLConnection conn = (HttpURLConnection)url.openConnection();\n\t\tconn.setRequestMethod(method);\n\t\tif (\"POST\".equals(method))\n\t\t\tconn.setDoOutput(true);\n\n\t\tif (user != null){\n\t\t\tString basicAuth = \"Basic \" + DatatypeConverter.printBase64Binary((user+\":\"+password).getBytes());\n\t\t\tconn.setRequestProperty (\"Authorization\", basicAuth);\n\t\t\tconn.setRequestProperty(\"Content-Type\",contentType);\n\t\t}\n\t\treturn conn;\n\n\t}  \n\n\tprivate static String read(InputStream in) throws IOException{\n\n\t\tInputStreamReader is = new InputStreamReader(in);\n\t\tStringBuilder sb=new StringBuilder();\n\t\tBufferedReader br = new BufferedReader(is);\n\t\tString read = br.readLine();\n\n\t\twhile(read != null) {\n\t\t\tsb.append(read);\n\t\t\tread =br.readLine();\n\n\t\t}\n\t\tis.close();\n\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate static String serialize(Map<String,String> params){\n\t\tStringBuffer buf = new StringBuffer();\n\t\t\n\t\tString prefix = \"\";\n\t\tfor (String key:params.keySet()){\n\t\t\tbuf.append(prefix).append(key).append(\"=\").append(params.get(key));\n\t\t\tprefix=\"&\";\n\t\t}\t\t\n\t\t\n\t\treturn buf.toString();\n\t}\n\n\n}\n"
  },
  {
    "path": "test/java/com/aralink/sslsignature/sso/jwt/test/SimpleConsoleLogger.java",
    "content": "package com.aralink.sslsignature.sso.jwt.test;\n\npublic class SimpleConsoleLogger {\n\tpublic enum Level {\tERROR, WARN, INFO, DEBUG,TRACE}\n\t/*\n\tpublic enum Level {\n\t\tERROR(0), WARN(1), INFO(2), DEBUG(3),TRACE(4);\n\t\tprivate final int id;\n\t\tLevel(int id) { this.id = id; }\n    \tpublic int getValue() { return id; }\t\n\t};\n\t */\n\tprivate static Level level = Level.INFO;\n\tpublic static void setLevel (Level l){\n\t\tlevel = l;\n\t}\n\tpublic static Level getLevel(){\n\t\treturn level;\n\t}\n\n\tpublic static void info(String message){\n\t\tlog(Level.INFO,message);\n\t}\n\tpublic static void error(String message){\n\t\tlog(Level.ERROR,message);\n\t}\n\tpublic static void warn(String message){\n\t\tlog(Level.WARN,message);\n\t}\n\tpublic static void debug(String message){\n\t\tlog(Level.DEBUG,message);\n\t}\n\tpublic static void trace(String message){\n\t\tlog(Level.TRACE,message);\n\t}\n\n\tpublic static void log(Level level, String message){\n\t\tlog(level,message,null);\n\t}\n\tpublic static void log(Level level, String message, Throwable throwable){\n\t\tif (level.ordinal() <= getLevel().ordinal()){\n\t\t\tSystem.out.println(level.name()+ \" \"+message);\n\t\t\tif (throwable != null)\n\t\t\t\tthrowable.printStackTrace();\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "test/web/hosted/index.html",
    "content": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - CryptoKeys</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->\n\t\t<meta name=\"description\" content=\"\" />\n\t\t<meta name=\"keywords\" content=\"\" />\n\t\t<META NAME=\"ROBOTS\" CONTENT=\"NOINDEX, NOFOLLOW\">\n\t\t<link rel=\"icon\" href=\"img/favicon.ico\">\n\t\t<meta name=\"ssls.accountId\" content=\"5995a3c9-678b-4338-a674-362af68b9ef9\" />\n\t\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t\t\n\t\t\n\t</head>\n\t<body>\n\t\t<div id=\"notIdentified\" class=\"container\" hidden>\n\t\t\t<h2>Welcome</h2>\n\t\t\t<p>You do not have an authentication token</p>\n\t\t\t<a type=\"button\" class=\"btn btn-success\" aria-label=\"Left Align\" href=\"register.html\"> Register </a>\n\t\t\t<a type=\"button\" class=\"btn btn-default\" aria-label=\"Left Align\" href=\"login.html\"> Identify</a>\n\t\t</div>\t\n\t\t\n\t\t<div id=\"identified\" class=\"container\" hidden>\n\t\t\t<h2 id=\"identifiedTitle\">Identificación realizada</h2>\n\t\t\t<section id=\"identificationInfo\" ></section>\n\t\t\t<div id=\"idOk\" class=\"row\">\n\t\t\t\t<hr/>\n\t\t\t\t<p>User not registered in CryptoKeys</p>\n\t\t\t\t<a type=\"button\" class=\"btn btn-success\" aria-label=\"Left Align\" href=\"register.html\">  Register  </a>\n\t\t\t\t<button type=\"button\" class=\"btn btn-danger\" aria-label=\"Left Align\" onclick=\"handleLogoutClick();\"><span class=\"glyphicon glyphicon-off\" aria-hidden=\"true\"></span> Logout</button>\n\t\t\t</div>\n\t\t\t<div id=\"idFailed\" class=\"row\">\n\t\t\t\t<hr/>\n\t\t\t\t<p>You do not have an authentication token</p>\n\t\t\t\t<a type=\"button\" class=\"btn btn-success\" aria-label=\"Left Align\" href=\"register.html\">  Register  </a>\n\t\t\t\t<a type=\"button\" class=\"btn btn-default\" aria-label=\"Left Align\" href=\"login.html\"> Identify</a>\n\t\t\t</div>\n\t\t</div>\t\n\t\t\n\t\t\n\t\t<section id=\"logged\" hidden>\n\t\t\t<div class=\"container\" >\n\t\t\t\t<h2 id=\"pageTitle\">Identification performed</h2>\n\t\t\t\t<button type=\"button\" class=\"btn btn-danger\" aria-label=\"Left Align\" onclick=\"handleLogoutClick();\"><span class=\"glyphicon glyphicon-off\" aria-hidden=\"true\"></span> Logout</button>\n\t\t\t</div>\n\t\t\t\t\n\t\t\t<div  id = \"newDevice\" class=\"container\" hidden>\n\t\t\t\t<h3>CryptoKeys not enabled</h3>\n\t\t\t\t<p>It is the first time you connect with this device, to enable CryptoKeys an additional identification is required. Below you will create your security private key </p>\n\t\t\t\t<section id=\"newDeviceSend\" hidden>\n\t\t\t\t\t<p>Enter the 4-digit code that is sent to your mobile phone</p>\n\t\t\t\t\t<div class='row'>\n\t\t\t\t\t\t<div class='col-md-2'>\n\t\t\t\t\t\t\t<div class=\"form-group input-group\">\n                            \t<span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-phone-alt\"  ></i></span>\n                            \t<input type=\"text\" name=\"otp\" id=\"otp\" value=\"\"  class=\"form-control\" placeholder=\"OTP\" />\n\t                        </div>\n\t                    </div>    \n\t                    <div class='col-md-1'>\n\t                    \t<button type=\"button\" id=\"sendOtp\" class=\"btn btn-primary\" aria-label=\"Left Align\" onclick=\"handleEnrollClick()\"> Send </button>\n\t\t\t\t\t\t</div>\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t</div>\t\n\t\t\t\t</section>\n\t\t\t\t<section id=\"newDeviceError\" hidden>\n\t\t\t\t \t<div id=\"newDeviceErrorMessage\" class=\"alert alert-warning\" role=\"alert\">Invalid identification</div>\n\t\t\t\t\t<a href=\"javascript:handleResendClick()\" id=\"resendOtp\" class=\"btn btn-primary\" >Enable CryptoKeys</a>\n\t\t\t\t</section>\n\t\t\t</div>\n\t\t\t\n\t\t\t<div id =\"registeredDevice\" class=\"container\" hidden>\n\t\t\t\t<hr/>\n\t\t\t\t<h3>Device registered</h3>\n\t\t\t\t<p>Your current browser has a security key. </p>\n\t\t\t\t<table id=\"theDeviceList\" class=\"table table-striped\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th><a href=\"javascript:handleRefreshDevicesClick()\"><span class=\"glyphicon glyphicon-refresh\" aria-hidden=\"true\"></span> Dispositivos habilitados</a></th>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t<th>Private</th>\n\t\t\t\t\t\t\t<th>Type</th>\n\t\t\t\t\t\t\t<th>Enabled</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t<div class=\"checkbox\">\n\t\t\t\t    <label>\n\t\t\t\t      <input type=\"checkbox\" id=\"showOnlyActive\" name=\"showOnlyActive\" checked> Show only enabled keys\n\t\t\t\t    </label>\n\t\t\t\t </div>\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<section id=\"checkRegisterMessage\"></section>\n\t\t\t\t</div>\n\t\t\t\t<hr/>\n\t\t\t\t<h3>Link mobile</h3>\n\t\t\t\t<p>You can link mobile devices to perform operations with double safety factor. Download the app (android) first</p>\n\t\t\t\t<p>\n\t\t\t\t\t<a href=\"javascript:handleRegisterDeviceClick()\" id=\"registerDeviceKey\" class=\"btn btn-success\" >Link</a>\n\t\t\t\t\t<span class=\"image\"> <a href=\"javascript:handleDownloadAppClick()\"><img src=\"img/android2.png\" height=\"32\" alt=\"Download app\"/></a></span>\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t\t<div id=\"dialogQr\"></div>\n\t\t\t\n\t\t\t<div class=\"container\" id = \"signedTransaction\" hidden>\n\t\t\t\t<hr/>\n\t\t\t\t<h3>Use your key on a transaction</h3>\n\t\t\t\t<p>The transaction is signed with your private key and validated by the public. Only an authorized device can perform operations. In operations with double safety factor you will need a connected mobile device. An authorization request will be sent to the device</p>\n\t\t\t\t<section id=\"checkResultMessage\"></section>\n\t\t\t\t\t\t\t\t\n\t\t\t\t<p>\n\t\t\t\t\t<a href=\"javascript:handleExecuteSignedTransactionClick()\" id=\"sendTransaction\" class=\"btn btn-primary\" >Level 1 : WebCrypto</a>\n\t\t\t\t\t<a href=\"javascript:handleExecuteSignedTransactionDoubleFactorClick()\" id=\"sendTransactionDoubleFactor\" class=\"btn btn-primary\" >Level 2: Double Factor</a>\n\t\t\t\t\t<a href=\"javascript:handleAbortClick()\" id=\"abortButton\" class=\"btn btn-danger\" hidden>Abort</a>\n\t\t\t\t</p>\n\t\t\t\t\n\t\t\t</div>\t\t\t\t\t\n\t\t\t\n\t\t</section>\n\t\t\n\t\t<div class=\"modal fade\" id=\"downloadAndroidDialog\" tabindex=\"-1\" role=\"dialog\">\n\t\t  <div class=\"modal-dialog\">\n\t\t    <div class=\"modal-content\">\n\t\t      <div class=\"modal-header\">\n\t\t        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n\t\t        <h4 class=\"modal-title\">Download for Android</h4>\n\t\t      </div>\n\t\t      <div class=\"modal-body\">\n\t\t        <p>Scan QR with your device</p>\n\t\t        <img src=\"#\" width=\"500\" id=\"qrimage\"  alt=\"Descargar aplicación\">\n\t\t\t\t\n\t\t      </div>\n\t\t      <div class=\"modal-footer\">\n\t\t        \n\t\t        <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n\t\t      </div>\n\t\t    </div>\n\t\t  </div>\n\t\t</div>\n\t\t<div class=\"modal fade\" id=\"registerDeviceDialog\" tabindex=\"-1\" role=\"dialog\">\n\t\t  <div class=\"modal-dialog\">\n\t\t    <div class=\"modal-content\">\n\t\t      <div class=\"modal-header\">\n\t\t        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n\t\t        <h4 class=\"modal-title\">Register new device</h4>\n\t\t      </div>\n\t\t      <div class=\"modal-body\">\n\t\t        <p>Scan QR with your device</p>\n\t\t        <img src=\"#\" width=\"500\" id=\"qrdevice\"  alt=\"Vincular dispositivo\">\n\t\t\t\t\n\t\t      </div>\n\t\t      <div class=\"modal-footer\">\n\t\t        \n\t\t        <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n\t\t      </div>\n\t\t    </div>\n\t\t  </div>\n\t\t</div>\n\t\t\n\t\t\n\t\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n\t    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n   \t\t <!--SSO--><script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js\"></script><!--SSO-->\n\t    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js\"></script>\n\t    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js\"></script>\n\t    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js\"></script>\n\t    <script src=\"js/index.js\"></script>\n\t    <script src=\"js/config.js\"></script>\n\t    <script>\n\t    \tstart (config);\n    \t</script>\n\t</body>\n</html>"
  },
  {
    "path": "test/web/hosted/js/config.js",
    "content": "var config = {\n\t\tapiUrl: 'https://produccion.sslsignature.com/sslsignature',\n        accountId: '5995a3c9-678b-4338-a674-362af68b9ef9',\n        apiKey: \"Qt89SdnW\",\n        tokenType: \"Basic\",\n        cryptobankingAppImage: \"../images/qr_cb_des.jpg\",\n        cryptobankingAppKey:\"AIzaSyASSQmFExB9NNfNzhlsihdI0TQi5m8G6uY\",\n        registerSuccessUrl: 'https://produccion.sslsignature.com/sso/hosted/index.html',\n        signInSuccessUrl: 'https://produccion.sslsignature.com/sso/hosted/index.html',\n        signInOptions: [\"CERTIFICATE\", \"CLAVE\",\"CRYPTOKEYS\",\"WEBCRYPTO\", \"PASSWORD\"],\n        siteTitle: \"SSLSignature Sample Login Form\",\n        siteDescription: \"Select ID method\"\n\t};\n"
  },
  {
    "path": "test/web/hosted/js/index.js",
    "content": "﻿var uAg = navigator.userAgent.toLowerCase();\nvar isMobile = !!uAg.match(/android|iphone|ipad|ipod|blackberry|symbianos/i);\t\n\t\n\tvar keyStore = null;\n\tvar ssls = null;\n\tvar userId = null;\n\tvar userConnected = null;\n\tvar keyRequest =null;\n\tvar currentKey = null;\n\tvar jwt = null;\n\tvar otp = null;\n\t\n\tvar deviceId = null;\n\tvar deviceDescription = null;\n\tvar deviceCharacteristics = null;\n\tvar identified = false;\n\t\n\tfunction start(conf){\n\t\tconfig = conf;\n\t\tssls = new SSLSignature(config.apiUrl, config.accountId, config.apiKey,config.tokenType);\n\t\tconsole.log (\"Create sslsignature service agent url:\"+config.apiUrl+ \" accountId:\"+config.accountId+ \" \"+config.apiKey);\n\t}\n\t\n\t$(document).ready(function(){\n\t\t\n\t\t//Evita que IE11 cachee peticiones\n\t\t$.ajaxSetup({ cache: false })\n\t\n\t\t//$('.modificable').on('change input',initRequest);\n\t\t//$('#abortButton').hide();\t\n\t\t\t\t\n\t\t$('#showOnlyActive').change(function() {\n\t\t\tlistDevices(userId);\n\t\t});\n\t\totp = getGetParam('otp');\n\t\tvar browserInfo = getBrowserInfo();\n\t\tdeviceDescription = browserInfo.name+ \" \"+browserInfo.version+ \"(\"+navigator.platform+\")\";\n\t\tdeviceCharacteristics = navigator.userAgent;\n\t\t/*\n\t\tnew Fingerprint2().get(function(result){\n\t\t\tconsole.log(\"deviceId:\"+ result);\n\t\t\tdeviceId = result;\n\t\t});\n\t\t*/\n\t\tconsole.log (\"deviceDescription: \"+deviceDescription);\n\t\tconsole.log (\"deviceCharacteristics: \"+deviceCharacteristics);\n\t});\n\t\n\t/////////////////////\n\t////////\tSSO METHODS\n\t/////////////////////\n\tfunction onIdentification(operation){\n\t\tconsole.log(\"SSO PAGE onIdentification\");\n\t\tidentificationPerformed({AuthenticationOperation:operation});\n\t\tidentified = true;\n\t}\n\tfunction onLoad(){\n\t\tconsole.log(\"SSO PAGE onLoad\");\n\t\tif (!identified){\n\t\t\tif (otp){\n\t\t\t\trecoverFailedIdentification (otp);\n\t\t\t} else {\n\t\t\t\tconfigureForm('notidentified');\n\t\t\t}\n\t\t}\t\n\t}\n\tfunction onLogout(){\n\t\tconsole.log(\"SSO PAGE onLogout\");\n\t\tconfigureForm('notidentified');\n\t}\n\t\n\t\t/////////////////////\n\t////////\t\n\t/////////////////////\n\t\n\tfunction configureForm(mode){\n\t\tif (mode == 'notidentified'){\n\t\t\t$('#notIdentified').show();\n\t\t\t$('#identified').hide();\n\t\t\t$(\"#logged\").hide();\n\n\t\t}else if (mode == 'identificationFailed'){\n\t\t\t$('#notIdentified').hide();\n\t\t\t$('#identified').show();\n\t\t\t$('#idOk').hide();\n\t\t\t$('#idFailed').show();\n\t\t\t$(\"#logged\").hide();\n\t\t\t\n\t\t}else if (mode == 'notregistered'){\n\t\t\t$('#notIdentified').hide();\n\t\t\t$('#identified').show();\n\t\t\t$('#idOk').show();\n\t\t\t$('#idFailed').hide();\n\t\t\t$(\"#logged\").hide();\n\t\t\t\n\t\t}  else if (mode =='logged'){\n\t\t\t$('#notIdentified').hide();\n\t\t\t$('#identified').hide();\n\t\t\t$(\"#logged\").show();\n\t\t\t$(\"#newDevice\").show();\t\n\t\t\t$(\"#registeredDevice\").hide();\t\n\t\t\t$(\"#signedTransaction\").hide();\n\t\t} else if (mode =='registeredDevice'){\n\t\t\t$('#notIdentified').hide();\n\t\t\t$('#identified').hide();\n\t\t\t$(\"#logged\").show();\n\t\t\t$(\"#newDevice\").hide();\t\n\t\t\t$(\"#registeredDevice\").show();\t\n\t\t\t$(\"#signedTransaction\").show();\n\t\t}\t\n\t}\n\t\n\tfunction recoverFailedIdentification(otp){\n\t\tconsole.log(\"Identification failed. OTP with description = \"+otp)\n\t\tssls.login(otp).then(function (obj){\n\t\t\tidentificationPerformed(obj);\n\t\t}).catch (function (result){\n\t\t\tconsole.log(result);\n\t\t\tconfigureForm('notidentified');\n\t\t});\n\t}\n\t\n\t\n\tfunction identificationPerformed(obj){\n\t\tconsole.log (\"Identification performed with status: \"+obj.AuthenticationOperation.status);\n\t\t//Muestra la información de la autenticación, sea correcta o no\n\t\tif (obj.AuthenticationOperation.status == 'SUCCESS') {\n\t\t\tvar userId = obj.AuthenticationOperation.userId;\n\t\t\tvar jwt = obj.AuthenticationOperation.jwt;\n\t\t\tif (jwt){\n\t\t\t\tconsole.log (\"JWT: \"+jwt);\n\t\t\t}\n\t\t\t\n\t\t\tinfoSignature(obj);\n\t\t\t\n\t\t\tif (userId){\n\t\t\t\tconsole.log (\"User registered with userId \"+userId);\n\t\t\t\tconfigureForm('logged');\n\t\t\t\t\n\t\t\t\tlogin(userId, jwt,\"JWT\");\n\t\t\t} else {\n\t\t\t\tconsole.log (\"User identified but not registered\")\n\t\t\t\tconfigureForm('notregistered')\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tconsole.log (\"Identification failed: \"+obj.AuthenticationOperation.error)\n\t\t\tinfoSignature(obj);\n\t\t\tconfigureForm('identificationFailed');\t\t\t\n\t\t}\n\t\t\n\t\t\n\t}\n\t\n\tfunction infoSignature(obj) {\n\t\tvar status = obj.AuthenticationOperation.status;\n\t\tvar error = \"\";\t\t\n\t\tvar infoSection =\"\";\n\t\tvar alertClass = \"\";\n\t\n\t\tif  (status == \"SUCCESS\" || status==\"UNKNOWN\"){\n\t\t\timage = \"<img src='img/checkmark.png'/>\";\n\t\t\tstatus = \"ID successful\";\n\t\t\talertClass = \"alert alert-success well-sm\";\n\t\t}else if  (status == \"FAIL\"){\n\t\t\timage = \"<img src='img/no_entry.png'/>\";\n\t\t\tstatus = \"ID fail \"+obj.AuthenticationOperation.error;\n\t\t\talertClass = \"alert alert-danger well-sm\";\n\t\t}\n\t\tstatus = status +\" (\"+obj.AuthenticationOperation.mode+\") perfomed at \"+obj.AuthenticationOperation.date;\n\t\t\n\t\tvar nameInfo = \"Name: \"+obj.AuthenticationOperation.name;\n\t\tif (obj.AuthenticationOperation.phone){\n\t\t\tnameInfo = nameInfo + \" Phone: \"+obj.AuthenticationOperation.phone;\n\t\t}\n\t\tif (obj.AuthenticationOperation.email){\n\t\t\tnameInfo = nameInfo +\" Email: \"+obj.AuthenticationOperation.email ;\n\t\t}\n\t\tif (obj.AuthenticationOperation.nif){\n\t\t\tidInfo = obj.AuthenticationOperation.nif;\n\t\t} else if (obj.AuthenticationOperation.eIdentifier){\n\t\t\tidInfo = obj.AuthenticationOperation.eIdentifier;\n\t\t} else if (obj.AuthenticationOperation.eidentifier){\n\t\t\tidInfo = obj.AuthenticationOperation.eidentifier;\n\t\t} else {\n\t\t\tidInfo = \"\";\n\t\t}\n\t\t\n\t\tjwtInfo = \"JWT: \"+obj.AuthenticationOperation.jwt;\n\t\tinfoSection = \n\t\t\t \"        <ul>\"\n\t\t\t +\"          <li>ID: \"+idInfo+\"</li>\"\n\t\t \t +\"          <li>\"+nameInfo+\"</li>\"\n\t\t \t +\"          <li>\"+jwtInfo+\"</li>\"\n\t\t \t +\"       </ul>\";\n\n\t\tvar section = \"<div class='row'>\"\n\t\t\t\t\t\t +\"   <div class='col-md-2'>\"\n\t\t\t\t\t\t +\"      <span class='image'>\"+image+\"</span>\"\n\t\t\t\t\t\t +\"    </div>\"\n\t\t\t\t\t\t +\"    <div class='col-md-10'>\"\n\t\t\t\t\t\t +\"      <h4>\"+status+\"</h4>\"\n\t\t\t\t\t\t +       infoSection\n\t\t\t\t\t\t + \"   </div>\"\n\t\t\t\t\t\t + \"</div>\";\n\t\t\n\t\tvar text = $(\"<section id='identificationInfo'>\"+section+\"</section>\");\n\t\t$('#identificationInfo').replaceWith(text);\n\t}\n\t\n\t\n\t\n\t\n\tfunction login (username,password,scheme){\n\t\t\n\t\tsslsUser = new SSLSignature(config.apiUrl,username,password,scheme);\n\n\t\tsslsUser.getUser().then (function(us){\n\t\t\t\n\t\t\tuserConnected = us.User;\n\t\t\tuserId = us.User.id;\n\t\t\t$(\"#pageTitle\").html(\"Welcome to CryptoKeys, \"+us.User.name+\"!\");\n\t\t\t\n\t\t\tconsole.log (\"log user: \"+userId);\n\t\t\tif (scheme != 'JWT'){\n\t\t\t\t\n\t\t\t\t//Autenticación basic, procedente de registro. Guardar token en SSO\n\t\t\t\tconsole.log(\" Obtain JWT and store in  SSO localStorage\");\n\t\t\t\tsslsUser.issueJWT(userId).then(function(jwtResponse){\n\t\t\t\t\tjwt = jwtResponse.JWT.data;\n\t\t\t\t\tconsole.log(\"Issued JWT token by server: \"+jwt);\n\t\t\t\t\t//Guardar token en SSO\n\t\t\t\t\tsslssso.login(jwt);\n\t\t\t\t\t//Chequear claves\t\t\t\t\n\t\t\t\t\topenCryptoKeyStore();\n\t\t\t\t}).catch (function (err){\n\t\t\t\t\tconsole.log(err);\n\t\t\t\t\tcallFailed(err);\n\t\t\t\t});\n\t\t\t\n\t\t\t} else {\n\t\t\t\t//Chequear claves\t\t\t\t\n\t\t\t\topenCryptoKeyStore();\n\t\t\t}\n\t\t\t\n\t\t\treturn sslsUser.issueJWT(userId);\n\t\t}).then (function (jwtResponse){\n\t\t\tjwt = jwtResponse.JWT.data;\n\t\t\tconsole.log(\"Issued JWT token by server: \"+jwt);\n\t\t}).catch (function (err){\n\t\t\tconsole.log(err);\n\t\t\tcallFailed(err);\n\t\t});\n\t\t\n\t}\n\t\n\tfunction openCryptoKeyStore(){\n\t\tkeyStore = new KeyStore();\t\n\t    keyStore.open(\"CBKeyStore\").then(function() {\n\t    \tconsole.log (\"KeyStore opened\");\n\t    \t//Buscamos si en el navegador hay una key asociada a la cuenta de usuario\n\t    \treturn keyStore.getKey(\"name\",userId);\n\t    }).then (function (pkcs12Entry){\n\t    \tconsole.log(\"Key exists. Validate with server signing and example text\");\n\t    \tvalidateCurrentKeyAndRequestIfNotValid(pkcs12Entry);\n\t    \t\n\t    }).catch (function (err){\n\t    \tconsole.log(err);\n\t    \tconsole.log(\"Key does not exists. Enable button so user can request one\");\n\t    \tconfigureNewKeyForm();\n\t    \t//requestAKey();\n\t    });\n\t}\t\n\t\n\t\n\t\n\tfunction keyExists(pkcs12Entry){\n\t\tcurrentKey = pkcs12Entry;\n\t\tlistDevices(userId);\n\t\tconfigureForm('registeredDevice');\n    \twindow.location=\"#userAuthentication\";\n\t}\n\t\n\tfunction requestAKey(){\n\t\tconfigureForm('logged');\n\t\tssls.keyRequest(userConnected.id).then (function (kr){\n\t\t\tconsole.log (\"key requested\");\n\t\t\tkeyRequest = kr;\n\t\t\t\n\t\t}).catch (function (err){\n\t\t\tconsole.log(err);\n\t\t\tvar error = \"No se ha podido solicitar una nueva clave privada\";\n\t\t\tif (err && err.responseJSON ){\n\t\t\t\terror = error + \": \"+err.responseJSON.error;\n\t\t\t} else if (err) {\n\t\t\t\terror = error + \": \"+err.status+ \"-\"+err.statusText;\n\t\t\t}\n\t\t\terror = error + \"\\nCon este usuario no va a poder realizar operaciones. ¿Desea borrarlo y volver a registrarse?\";\n\t\t\t\n\t\t\tif (confirm(error)) {\n\t\t\t\tssls.deleteUser(userConnected.id).then (function (){\n\t\t\t\t\tconsole.log(\"User \"+userConnected.id+\" deleted\");\n\t\t\t\t\tlocation.reload();\n\t\t\t\t}).catch (function (err){\n\t\t\t\t\tconsole.log(\"Error deleting user\"+userConnected.id);\n\t\t\t\t\tlocation.reload();\n\t\t\t\t});\n\t\t\t\t\n\t\t\t} \n\t\t});\n\t}\t\n\t    \n\tfunction keyCreated(pkcs12Entry){\n\t\tcurrentKey = pkcs12Entry;\n\t\tconfigureForm('registeredDevice');\n\t\tlistDevices(userId);\n\t}\t\n\n\tfunction handleLogoutClick(){\n\t\tsslssso.logout();\n\t}\n\tfunction handleEnrollClick () {\n\t\tconsole.log(\"proceed to enroll \");\n\t\t//Genera un par de claves privada y pública\n\t\tvar keys = forge.pki.rsa.generateKeyPair(1024);\n\t\t\t\t\t\n\t\t// convierte de Forge public key a formatos PEM y  DER para enviar a servidor. Esta parte sobraría con el envío de pkcs10, pero desde aquí es más fácil extraer cosas que en servidor. \n\t\tvar publicKeyPem = forge.pki.publicKeyToPem(keys.publicKey);\n\t\tvar subjectPublicKeyInfo = forge.pki.publicKeyToAsn1(keys.publicKey);\n\t\tvar publicKeyInfoDer = forge.asn1.toDer(subjectPublicKeyInfo).getBytes();\n\t\tvar publicKeyb64 = forge.util.encode64(publicKeyInfoDer);\n\t\t\n\t\t//Crea una solicitud de certificado PKCS10\n\t\tvar csr = createCSR(keys,\"ES\",userConnected.name,userConnected.id);\n\t\t//Pasa a PEM format\n\t\tvar csrPem = forge.pki.certificationRequestToPem(csr);\n\t\t\n\t\t//Resto de datos del registro de clave. Incluye la clave pública y datos del dispositivo \n\t\tkeyRequest.KeyRequest.csrPem = csrPem;\n\t\tkeyRequest.KeyRequest.deviceId = deviceId;\t\n\t\tkeyRequest.KeyRequest.deviceDescription = deviceDescription;\t\n\t\tkeyRequest.KeyRequest.deviceCharacteristics = deviceCharacteristics;\n\t\tkeyRequest.KeyRequest.engine = \"WEBCRYPTO\";\t\n\t\tkeyRequest.KeyRequest.otp = $('#otp').val();\n\t\tkeyRequest.KeyRequest.publicKey = publicKeyb64;\n\t\t\t\t\n\t\t\n\t\t//Envía petición a servidor, ID de operación, OTP respondido y CSR con la clave pública\n\t\tssls.keyRegister(keyRequest.KeyRequest.userId,keyRequest.KeyRequest.id,keyRequest).then (function (csrResponse){\n\t\t\tconsole.log(\"CSR response from server\");\n\t\t\tconsole.log(csrResponse);\n    \t\tvar pkcsEntry = new PKCS12Entry();\n    \t\tpkcsEntry.fromCsrP7b(keys.privateKey,csrResponse.DeviceKey.certificatep7b);\n    \t\tpkcsEntry.name = userConnected.id;\n    \t\tpkcsEntry.keyId = csrResponse.DeviceKey.id;\n    \t\tpkcsEntry.keyName = userConnected.name;\n    \t\treturn keyStore.importCertificate(pkcsEntry,false);\n\t\t}).then(function(pkcs12Entry) {\n\t\t\tconsole.log (\"Imported CSR key, generated local, signed on server: \"+pkcs12Entry.name);\n    \t\tkeyCreated(pkcs12Entry);\n\t\t}).catch (function (err){\n\t\t\tconsole.log(err);\n\t\t\tenrollFailed(err);\n\t\t});\n\t}\n\t\n\tfunction enrollFailed(result){\n\t\t$('#newDeviceSend').hide();\n\t\t$('#newDeviceErrorMessage').text(\"La identificación no ha sido correcta: \"+result.status+\"-\"+result.responseText);\n\t\t$('#newDeviceErrorMessage').show();\n\t\t$('#newDeviceError').show();\n\t\t\n\t}\n\t\n\tfunction configureNewKeyForm(){\n\t\t$('#otp').val(null);\n\t\t$('#newDeviceSend').hide();\n\t\t$('#newDeviceErrorMessage').text(\"\");\n\t\t$('#newDeviceErrorMessage').hide();\n\t\t$('#resendOtp').text(\" Habilitar CryptoKeys \");\n\t\t$('#newDeviceError').show();\n\t\t\n\t\t//requestAKey();\n\t}\n\tfunction configureBadKeyForm(){\n\t\t$('#otp').val(null);\n\t\t$('#newDeviceSend').hide();\n\t\t$('#newDeviceErrorMessage').text(\"La clave existe pero no es válida\");\n\t\t$('#newDeviceErrorMessage').show();\n\t\t$('#resendOtp').text(\" Solicitar nueva clave \");\n\t\t$('#newDeviceError').show();\n\t\t\n\t\t//requestAKey();\n\t}\n\t\n\tfunction handleResendClick(){\n\t\t$('#otp').val(null);\n\t\t$('#newDeviceError').hide();\n\t\t$('#newDeviceErrorMessage').text(\"\");\n\t\t$('#resendOtp').text(\" Reintentar \");\n\t\t$('#newDeviceSend').show();\n\t\trequestAKey();\n\t}\n\t\n\tfunction handleExecuteSignedTransactionClick(){\n\t\t\n\t\tif (!currentKey){\n\t\t\tshowCheckResultMessage(\"No dispone de clave de firma. Por favor, validese primero.\", \"alert-warning\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t//La clave privada solo se puede usar con pin?\n\t\tif (currentKey.pin){\n\t\t\tpassword_prompt(\"La clave de identificación requiere PIN para habilitar el uso. Introdúzcalo a continuación\",\"Aceptar\",320,300,executeSignedTransactionImpl);\n\t\t} else {\n\t\t\texecuteSignedTransactionImpl();\n\t\t}\n\t}\t\n\tfunction executeSignedTransactionImpl(pin){\t\n\t\tvar textToSign = \"Authorization request text to sign\";\n\t\tvar message = \"1. Signing challenge with a private key <br/>\";\n\n\t\tvar st = new SignatureToken();\n    \tst.webcryptosign(textToSign,currentKey,pin).then (function (signature){\n    \t\tmessage = message + \"2. Sending signature to server<br/>\";\n    \t\tvar signatureB64 = forge.util.encode64(arrayBufferToString(signature));\n    \t\tconsole.log (\"signedData: \"+signatureB64);\n    \t\tvar dataB64 = forge.util.encode64(textToSign);\n    \t\tvar check ={KeyCheck:{data:dataB64,signature:signatureB64}};\n    \t\t\n    \t\treturn ssls.userKeyCheck(userId,check);\n    \t}).then (function(){\n    \t\tmessage =  message +\"3. Transaction validated\";\n    \t\tshowCheckResultMessage(message, \"alert-success\");\n\t\t}).catch (function (err){\n\t\t\tconsole.log(err);\n\t\t\tmessage =  message + \"Signature not validated. Transaction can not be performed\"\n\t\t\tvar motivo = null;\n\t\t\tif (err && err.responseJSON)\n\t\t\t\tmessage = message +\": \" + err.responseJSON.error;\n\t\t\telse if (err)\n\t\t\t\tmessage = message +\": \" + err;\n\t\t\tshowCheckResultMessage( message, \"alert-danger\");\n\t\t});\n\t} \n\t\n\tfunction validateCurrentKeyAndRequestIfNotValid(pkcs12Entry){\n\t\t//La clave privada solo se puede usar con pin?. En ese caso se da por buena y ya la validaremos con la primera transacción\n\t\tif (pkcs12Entry.pin)\n\t\t\treturn true;\n\n\t\tvar textToSign = \"Validating key\";\n\t\tvar pin = null;\n\t\t\n\t\tvar st = new SignatureToken();\n    \tst.webcryptosign(textToSign,pkcs12Entry,pin).then (function (signature){\n    \t\tvar signatureB64 = forge.util.encode64(arrayBufferToString(signature));\n    \t\tvar dataB64 = forge.util.encode64(textToSign);\n    \t\tvar check ={KeyCheck:{data:dataB64,signature:signatureB64}};\n    \t\treturn ssls.userKeyCheck(userId,check);\n    \t}).then (function(){\n    \t\tconsole.log(\"The key is valid\");    \t\t\n    \t\tkeyExists(pkcs12Entry);\n\t\t}).catch (function (err){\n\t\t\tconsole.log(err);\n\t\t\tconsole.log(\"The key is not valid. Deleting key for user: \"+userId);\n\t\t\tkeyStore.deleteKey(null,userId).then (function(){\n\t\t\t\tconsole.log(\"Invalid key deleted\");\n\t\t\t\tcurrentKey = null;\n\t\t\t\t//requestAKey();\n\t\t\t\tconfigureBadKeyForm();\n\t\t\t});\t\n\t\t});\n\t} \n\t\n\t\n\t\n\t\n\t\n\t\n\tfunction doDeleteKey(){\n\t\t\n\t\t\n\t\tkeyStore.deleteKey(null,userId).then(function (){\n\t\t\tconsole.log (\"key deleted from keystore for user: \"+userId);\n\t\t\t\n\t\t\tvar currentKeyToRevoke = currentKey;\n\t\t\tif (currentKeyToRevoke && currentKeyToRevoke.keyId && !currentKeyToRevoke.revoked){\n\t\t\t\tssls.keyRevoke(userId,currentKeyToRevoke.keyId).then(function(){\n\t\t\t\t\tconsole.log(\"Key revoked in server \"+currentKeyToRevoke.keyId);\n\t\t\t\t\tlistDevices(userId);\n\t\t\t\t}).catch (function (err){\n\t\t\t\t\tconsole.log (err);\n\t\t\t\t\tconsole.log(\"Error revoking key in server \"+currentKeyToRevoke.keyId);\n\t\t\t\t\tlistDevices(userId);\n\t\t\t\t});\n\t\t\t} else{\n\t\t\t\tlistDevices(userId);\n\t\t\t}\t\n\t\t\t$(\"#userId\").val(null);\n\t\t\tcurrentKey = null;\n\t\t\t\n\t\t}).catch (function (err){\n\t\t\tconsole.log(err);\n\t\t});\n\t\t\n\t\treturn \n\t}\n\t\n\n\tfunction showCheckResultMessage(mensaje, alertType){\n\t\tif (!alertType){\n\t\t\talertType = \"alert-info\"\n\t\t}\t\n\t\t\n\t\tvar text = \"<div id='checkResultMessage' class='alert \"+alertType+\"' role='alert'>\"+mensaje+\"</div>\";\n\t\t$('#checkResultMessage').replaceWith(text);\t\n\t}\n\t\n\tfunction callFailed(result) {\n\t\tconsole.log(result);\n\t\talert('Service call failed: ' + result.status + ' - ' + result.statusText + ' - ' +result.responseText);\n\t\t//showResponse ('Service call failed: ' + result.status + ' - ' + result.statusText + ' - ' +result.responseText);\n\t}\n\t\n\t\n\tfunction generateCSR(userConnected,keys){\n\t\tvar CN = null;\n\t\tif (userConnected.nif)\n\t\t\tCN = userConnected.nif;\n\t\telse if (userConnected.email)\n\t\t\tCN = userConnected.email;\n\t\tvar C = \"ES\";\n\t\tvar SERIALNUMBER = userConnected.id;\n\t\tvar extractable = false;\n\t\t\n\t\t//generate PKCS10 request\n\t\tvar csr = createCSR(keys,C,CN,SERIALNUMBER);\n\t\t//Pasa a PEM format\n\t\tvar csrPem = forge.pki.certificationRequestToPem(csr);\n    \t\n\t\treturn csrPem;\n\t}\t\n\t\t\n\t\n\t function createCSR(keys, C,CN,SERIALNUMBER){\n\t    // create a certification request (CSR)\n\t    var csr = forge.pki.createCertificationRequest();\n\t    csr.publicKey = keys.publicKey;\n\t    csr.setSubject([{\n\t      \tname: 'commonName',\n\t    \tvalue: CN\n\t    }, {\n\t    \tname: 'countryName',\n\t    \tvalue: C\n\t    }, {\n\t    \tname: 'serialName',\n\t    \tvalue: SERIALNUMBER\n\t    }]);\n\t    // set (optional) attributes\n\t    /*\n\t    csr.setAttributes([{\n\t      name: 'challengePassword',\n\t      value: 'password'\n\t    }, {\n\t      name: 'unstructuredName',\n\t    \t  value: 'SSL certificate, Inc.'\n\t    \t}, {\n\t    \t  name: 'extensionRequest',\n\t    \t  extensions: [{\n\t    \t    name: 'subjectAltName',\n\t    \t    altNames: [{\n\t    \t      // 2 is DNS type\n\t    \t      type: 2,\n\t    \t      value: 'test.domain.com'\n\t    \t    }, {\n\t    \t      type: 2,\n\t    \t      value: 'other.domain.com',\n\t    \t    }, {\n\t    \t      type: 2,\n\t    \t      value: 'www.domain.net'\n\t    \t    }]\n\t    \t  }]\n\t    \t}]);\n\t\t*/\n\t    // sign certification request\n\t    csr.sign(keys.privateKey);\n\n\t    // verify certification request\n\t    var verified = csr.verify();\n    \treturn csr;\n    }\n\t \n\t \n\t \n\t function listDevices(userId){\n\t\t console.log(\"listing keys\");\n\t\t ssls.keyList(userId).then(function(list) {\n\t\t\tconsole.log(list.DeviceKey);\n\t\t\t $(\"#theDeviceList > tbody\").empty();\n\t\t\tfor (var i=0; i<list.DeviceKey.length; i++) {\n\t       \t\taddToDeviceList (list.DeviceKey[i]);\n\t        }\n\t   \t}).catch(function(err) {\n\t   \t\tif (err.status!= 404)\n\t   \t\t\tcallFailed(err);\n\t    });\n\t }\n\t\t\n\tfunction addToDeviceList(key){\n\t\tvar id = key.id;\n\t\tvar name = key.deviceDescription\n\t\tvar actual = \"\";\n\t\tvar deleteAction =\"\";\n\t\tvar showOnlyActive = $('#showOnlyActive').is(':checked');\n\n\t\tconsole.log(\"add key to list id:\"+id +  \" name: \"+name+ \" revoked:\"+key.revoked);\n\t\t//var keyStatus = \"SI\";\n\t\t//if (key.revoked)\n\t\t//\tkeyStatus = \"Revocada\";\n\t\tvar keyStatus = \"<img src='img/checkmark.png' alt='Clave activa' title='Clave activa' height='32'/>\";\n\t\tif (key.revoked)\n\t\t\tkeyStatus = \"<img src='img/no_entry.png' alt='Clave revocada' title='Clave revocada' height='32'/>\";\n\t\t\n\t\tvar keyEngine = \"<img src='img/w3c-icon.png' alt='WEBCRYPTO' title='WEBCRYPTO' height='32'/>\";\n\t\tif (key.engine == 'ANDROID')\n\t\t\tkeyEngine = \"<img src='img/android-icon.png' alt='ANDROID' title='ANDROID' height='32'/>\";\n\t\telse if (key.engine == 'IOS')\n\t\t\tkeyEngine = \"<img src='img/ios-icon.png' alt='ANDROID' title='ANDROID' height='32'/>\";\t\t\n\t\t\t\t\n\t\t\n\t\tif (currentKey && currentKey.keyId == key.id){\n\t\t\tname = name+ \" [ACTUAL]\";\n\t\t\tactual = \"<img src='img/key-icon.png' alt='Clave privada' title='Private key' height='32'/>\";\n\t\t\t//deleteAction = \"\t<li><a href='javascript:doDeleteKey()'>Eliminar del navegador</a></li>\";\n\t\t\tdeleteAction=\"doDeleteKey()\";\n\t\t} else {\n\t\t\tdeleteAction =\"doRevokeKey(\\\"\"+id+\"\\\")\";\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tvar keyActions = \"<button type='button' class='btn btn-default' onclick=\"+deleteAction+\" >\"\n\t\t\t+\"<span class='glyphicon glyphicon-trash' ></span> \" \n\t\t\t+  \"</button>\";\n\t\t\n\t\tif (key.revoked){\n\t\t\tkeyActions = \"\";\n\t\t}\n\t\t\n\t\t  \n\t\tvar tableElement = \"<tr>\"\n\t\t//\t+ \"<td><input type='radio' name='key' value='\"+id+\"' id='\"+id+\"'><label for='\"+id+\"'>\"+name+\"</label></td>\"\n\t\t\t+ \"<td>\"+name+\"</td>\"\n\t\t\t+ \"<td>\"+actual+\"</td>\"\n\t\t\t+ \"<td>\"+keyEngine+\"</td>\"\n\t\t\t+ \"<td>\"+keyStatus+\"</td>\"\n\t\t\t+ \"<td>\"+keyActions+\"</td>\"\n\t\t\t+\"</tr>\";\n\t\t\n\t\tif (!showOnlyActive || !key.revoked)\n\t\t\t$('#theDeviceList').append(tableElement);\n\t}\n\t\n\tfunction doRevokeKey(selectedKeyId){\n\t\t//var selectedKeyId =$('input:radio[name=key]:checked').val();\n\t\tconsole.log (\"Revoking key \"+selectedKeyId);\n\t\tif (selectedKeyId){\n\t\t\tssls.keyRevoke(userId,selectedKeyId).then(function(){\n\t\t\t\tlistDevices(userId);\n\t\t\t}).catch(function(err) {\n\t        \talert(\"Could not delete key : \" + err);\n\t    \t});\n\t\t\t\n\t\t}\n\t}\n\t\n\tfunction handleRegisterDeviceClick(){\n\t\tvar message = \"Click to start mobile linking process\";\n\t\tif (isMobile ){\n\t\t\tvar link = makeRegisterLink(userId);\n\t\t\tvar section = \"<div id='checkResultMessage' class='alert alert-info' role='alert'>\"\n\t\t\t\t + message\n\t\t\t\t + \"<a href='\"+link+\"'  class='btn btn-default' target='_blank'>CryptoKeys app</a>\"\n\t\t\t\t +\t\"</div>\";\n\t\t\t$('#checkRegisterMessage').replaceWith(section);\t\t\t\n\t\t\t\n\t\t} else  {\n\t\t\tvar  qrLink = config.apiUrl+\"/account/\"+userId+\"/qr?userId=\"+userId+ \"&jwt=\"+jwt;\n\t\t    $('#qrdevice').attr(\"src\",qrLink);\n\t\t    $('#registerDeviceDialog').modal('show')  \n\t\t}\n\t\t\n\t}\n\t\n\tfunction handleRefreshDevicesClick(){\n\t\tlistDevices(userId);\n\t}\n\t\n\t\n\tfunction handleExecuteSignedTransactionDoubleFactorClick(){\n\t\tvar textToSign = \"Double factor transaction\";\n\t\tvar request = { Authorization : { userId : userId, appKey: config.cryptobankingAppKey,channel:'PUSH',mode:'DIGITAL_SIGNATURE',message: textToSign }};\n\t\t\n\t\tssls.postAuthorization(request).then (function(obj){\n\t\t\tauthorizationResponse(obj);\n\t\t\tinitTimer();\n\t\t}).catch (function (err){\n\t\t\tcallFailed(err);\n\t\t});\n\n\t} \n\t\n\tfunction checkCallStatus(){\n\t\tssls.getAuthorization (authorizationId).then (function (obj){\n\t\t\tvar status = obj.Authorization.status;\n\t\t\t\n\t\t\tif (isAuthorizationFinished(status))\n\t\t\t\tfinishAuthorization(obj.Authorization);\n\t\t}).catch (function (result){\n\t\t\tcallFailed(result);\n\t\t});\n\t}\n\t\n\t\n\t\n\tfunction authorizationResponse(obj) {\n\t\tauthorizationId = obj.Authorization.id;\n\t\tconsole.log(\"authorization Id : \"+authorizationId);\n\t\t\t\t\n\t\t$('#abortButton').show();\t\n\t\t$('#sendTransactionDoubleFactor').hide();\t\n\t\t$('#textToSignDoubleFactor').hide();\t\n\t\t\n\t\tvar message = \"Requesting authorization to your linked device...\";\n\t\tif (isMobile ){\n\t\t\tvar link = makeAuthorizationLink(obj.Authorization);\n\t\t\tvar section = \"<div id='checkResultMessage' class='alert alert-info' role='alert'>\"\n\t\t\t\t + message\n\t\t\t\t + \"<a href='\"+link+\"'  class='btn btn-default' target='_blank'>Cryptokeys app</a>\"\n\t\t\t\t +\t\"</div>\";\n\t\t\t$('#checkResultMessage').replaceWith(section);\t\t\t\n\t\t} else  {\n\t\t\tshowCheckResultMessage(message);\t\n\t\t}\n\t}\n\t\n\t\n\tfunction handleDownloadAppClick(){\n\t\t   if (!isMobile){\n\t\t\t   $('#qrimage').attr(\"src\",config.cryptobankingAppImage);\n\t\t\t   $('#downloadAndroidDialog').modal('show')  \n\t\t   } else  {\n\t\t\t   window.open(cryptobankingApp)\n\t\t   }\n\t   }\n\t\n\tfunction makeAuthorizationLink(authorization){\n\t\tvar protocol = \"cb\";\n\t\tvar appUrl = \"com.aralink.cryptobanking.authorization\";\n\t\tvar p1 = \"id=\"+authorization.id;\n\t\t//var p2 = \"web=\"+webHost;\n\t\tvar p2 = \"web=\"+config.apiUrl;\n\t\tvar p3 = \"data=\"+authorization.dataToSign;\n\t\t\t\n\t\tvar link = protocol + \"://\" + appUrl+ \"?\"+p1+\"&\"+p2+\"&\"+p3;\n\t\tconsole.log(link)\n\t\treturn link;\n\t}\n\t\n\tfunction makeRegisterLink(userId){\n\t\tvar protocol = \"cb\";\n\t\tvar appUrl = \"com.aralink.cryptobanking.register\";\n\t\tvar p1 = \"userId=\"+userId;\n\t\tvar p2 = \"web=\"+config.apiUrl;\n\t\tvar p3 = \"jwt=\"+jwt;\n\t\t//p2 = \"web=https://10.5.3.9:444/sslsignature\";\n\t\t\t\n\t\tvar link = protocol + \"://\" + appUrl+ \"?\"+p1+\"&\"+p2+\"&\"+p3;\n\t\tconsole.log(link)\n\t\treturn link;\n\t}\n\t\n\t\n\tfunction isAuthorizationFinished(status) {\n\t\treturn (status == \"CANCEL\" || status==\"SUCCESS\" || status ==\"FAIL\")\n\t}\n\tfunction finishAuthorization(authorization) {\n\t\tcancelTimer();\n\t\tvar mode = authorization.mode;\n\t\tvar status = authorization.status;\n\t\tconsole.log (\"Authorization status =\"+status);\n\t\t\n\t\tvar image;\n\t\tvar alertType;\n\t\tif (status == \"CANCEL\"){\n\t\t\timage = \"<img src='img/yield.png'/>\";\n\t\t\talertType = \"alert-warning\";\n\t\t}else if  (status == \"SUCCESS\"){\n\t\t\timage = \"<img src='img/checkmark.png'/>\";\n\t\t\talertType = \"alert-success\";\n\t\t}else if  (status == \"FAIL\"){\n\t\t\timage = \"<img src='img/no_entry.png'/>\";\n\t\t\talertType = \"alert-danger\";\n\t\t}else{ \n\t\t\timage = \"<img src='img/no_entry.png'/>\";\n\t\t\talertType = \"alert-info\";\n\t\t}\t\n\t\t\n\t\tvar section = \"<div id='checkResultMessage'  class='alert \"+alertType+\"' role='alert'><h5>Respuesta obtenida </h5>\"+image+\"<h5>\"+status+\"</h5></section>\";\n\t\t$('#checkResultMessage').replaceWith(section);\t\n\t\t\n\t\t$('#abortButton').hide();\n\t\t$('#sendTransactionDoubleFactor').show();\t\n\t\t//$('#textToSignDoubleFactor').show();\t\n\t}\t\n\n\t\n\t\n\t\n\tfunction doAbort(){\n\t\tfinishAuthorization('CANCEL');\n\t}\n\t\n\tfunction handleAbortClick(){\n\t\tcancelTimer();\t\t\n\t\t\n\t\timage = \"<img src='img/yield.png'/>\";\n\t\tvar section = \"<div id='checkResultMessage' class='alert alert-warning' role='alert'><h5>Resultado de la autorización</h5>\"+image+\"<h5>CANCEL</h5></div>\";\n\t\t$('#checkResultMessage').replaceWith(section);\n\t\t\n\t\t$('#abortButton').hide();\n\t\t$('#sendTransactionDoubleFactor').show();\t\n\t\t//$('#textToSignDoubleFactor').show();\t\n\t}\n\t\n\t\n\tfunction initTimer(){\n\t\ttimeout = 90;\n\t\tintervalId = window.setInterval(runTimer, 1000);\n\t}\n\t\n\tfunction runTimer(){\n\t\tvar oElem = document.getElementById(\"otp\");\n\t\t\n\t\ttimeout = timeout - 1;\n\t\t$('#abortButton').html(\"Abortar (\"+timeout+\")\");\n\t\tif (timeout < 0){\n\t\t\t$('#abortButton').html(\"Timeout\");\n\t\t\tdoAbort();\n\t\t} else {\t\n\t\t\t//Cada 5 segundos check call status\n\t\t\tif (timeout % 5 == 0)\n\t\t\t\tcheckCallStatus();\n\t\t}\t\n\t}\n\t\n\tfunction cancelTimer(){\n\t\tclearInterval(intervalId);\n\t}\n\t\n\t/***************\n\t * \n\t * Utilities\n\t */\n\t\n\tfunction getGetParam (vr){\n\t\tvar src = window.location.href;\n\t\tif (src != null) {\n\t\t\tvar vrs = src.split('?');\n\n\t\t\tfor (var x = 0, c = vrs.length; x < c; x++){\t\n\t\t\t\tif (vrs[x].indexOf(vr) != -1){\n\t\t\t\t\treturn decodeURI( vrs[x].split('=')[1] );\n\t\t\t\t\tbreak;\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\t\telse {\n\t\t\t return \"\";\n\t\t}\n\t};\n\t\n\tfunction getBrowserInfo(){\n\t    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)/i) || []; \n\t    if(/trident/i.test(M[1])){\n\t        tem=/\\brv[ :]+(\\d+)/g.exec(ua) || []; \n\t        return {name:'IE',version:(tem[1]||'')};\n\t        }   \n\t    if(M[1]==='Chrome'){\n\t        tem=ua.match(/\\bOPR\\/(\\d+)/)\n\t        if(tem!=null)   {return {name:'Opera', version:tem[1]};}\n\t        }   \n\t    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];\n\t    if((tem=ua.match(/version\\/(\\d+)/i))!=null) {M.splice(1,1,tem[1]);}\n\t    return {\n\t      name: M[0],\n\t      version: M[1]\n\t    };\n\t }\n\t\n\t"
  },
  {
    "path": "test/web/hosted/js/jwtcreator.js",
    "content": "﻿\nvar config;\n\t\n\tfunction start(conf){\n\t\tconfig = conf;\n\t}\n\t\n\t\n\t\n\tfunction onIdentification(operation){\n\t\tconsole.log(\"SSO PAGE onIdentification\");\n\t\tauthenticationPerformed(operation);\t\t\n\t}\n\tfunction onLoad(){\n\t\tconsole.log(\"SSO PAGE onLoad\");\n\t}\n\tfunction onLogout(){\n\t\tconsole.log(\"SSO PAGE onLogout\");\n\t}\n\t\n\t\n\tfunction handleCreateJWTClick(){\n\t\t\n\t\tvar params = $('#jwtForm').serialize();\n\t\tconsole.log(\"POST \"+config.url);\n\t\tconsole.log(params);\n\t\t$.post(\n\t\t\t\tconfig.url, \n\t\t\t\tparams,\n\t\t\t\tfunction(jwt) {\n\t\t\t\t\tconsole.log(\"JWT: \"+jwt);\n\t\t\t\t\t//Store JWT in browser SSO\n\t\t\t\t\tsslssso.login(jwt);\n                });\n\t\t\n\t}\t\n\t\t\n\t\n\t\n\t"
  },
  {
    "path": "test/web/hosted/js/keystore.js",
    "content": "\n\tvar ssls;\n\tvar crypto = window.crypto || window.msCrypto;\n\tvar keyStore;\n\tvar cbKeyStore;\n\tvar webcrypto = true;\n\t\n\t$(document).ready(function(){\n\t\tconfigureForm();\n\t\t\n\t\tcheckWebCrypto();\n\t\topenWebCryptoKeyStore();\n\t\topenCryptoKeysKeyStore();\n\t    \n\t});\n\t\n\tfunction configureForm(){\n\t}\n\t\t\n\t\n\tfunction checkWebCrypto(){\n\t\tif (window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle) {\n\t        window.crypto.subtle = window.crypto.webkitSubtle;\n\t    }\n\t\tif (!window.crypto &&  window.msCrypto){\n\t\t\twindow.crypto = window.msCrypto;\n\t\t}\n\t\t\n\t\tif (!window.crypto || !window.crypto.subtle) {\n\t\t\tdisableWebCrypto(\"Web Cryptographi API no soportada!\");\n\t    }\n\t    \n\t    if (!window.indexedDB) {\n\t\t\tdisableWebCrypto(\"IndexedDB no soportada!\");\n\t    } \n\t}\n\t\n\tfunction disableWebCrypto(message){\n\t\twebcrypto = false;\n\t\t$(\"#webcryptoAlert\").text(message);\n\t\t$(\"#webcryptoAlert\").show();\n\t}\n\t\n\tfunction openWebCryptoKeyStore(){\n\t\tif (webcrypto){\n\t\t\t keyStore = new KeyStore();\t\n\t\t\t keyStore.open().then(function() {\n\t\t\t   \tconsole.log (\"KeyStore opened\");\n\t\t\t    listKeyStore();\n\t\t\t }).catch(function(err) {\n\t\t\t    alert(\"Could not open key store: \" + err);\n\t\t\t });\t\t   \n\t\t}\n\t}\n\tfunction openCryptoKeysKeyStore(){\n\t\tif (webcrypto){\n\t\t\t cbKeyStore = new KeyStore();\t\n\t\t\t cbKeyStore.open(\"CBKeyStore\").then(function() {\n\t\t\t   \tconsole.log (\"CryptoKeyStore opened\");\n\t\t\t    listCryptoKeyStore();\n\t\t\t }).catch(function(err) {\n\t\t\t    alert(\"Could not open key store: \" + err);\n\t\t\t });\t\t   \n\t\t}\n\t}\n\t\n\t\t\n\tfunction importPkcs12(file,password, extractable){\n\t\tconsole.log(\"importPkcs12 \"+password + \" extractable:\"+extractable);\n\t\tvar reader = new FileReader();\n\t\treader.onload = function(e) { \t\t\t\t\n\t\t\t//var mime = convertMimetype(file.type);\n\t\t\tvar contents = e.target.result;\n\t\t\tvar pkcs12Bin = arrayBufferToString(contents)\n\t\t\tvar pkcs12B64 = forge.util.encode64(pkcs12Bin);\t\t\n\t\t\t\n\t\t\t\n\t\t\tkeyStore.importKey(pkcs12B64,password,extractable).then(function(savedObject) {\n\t    \t\tconsole.log (\"Imported key: \"+savedObject.name);\n\t    \t\t$('#importCertificateModal').modal('hide')\n\t    \t\tlistKeyStore();\n\t\t\t}).catch(function(err) {\n\t            alert(\"Could not import pcks12: \" + err);\n\t        });\n\t\t}\t\n\t\treader.readAsArrayBuffer(file);\n\t}\n\t\n\tfunction listKeyStore(){\n\t\tkeyStore.listKeys().then(function(list) {\n\t\t\t$( \"#keyList\" ).empty();\n\t\t\tfor (var i=0; i<list.length; i++) {\n\t\t\t\t$( \"#keyList\" ).append( \n\t\t\t\t\t\taddToKeyList (list[i]));\n        \t}\n   \t\t }).catch(function(err) {\n        \talert(\"Could not list key store: \" + err);\n    \t});\n\t}\n\t\n\tfunction addToKeyList(keystoreObject){\n\t\tvar id = keystoreObject.id;\n\t\tvar savedObject = keystoreObject.value;\n\t\tvar name = escapeHTML(savedObject.name);\n\t\tconsole.log(\"add key to list id:\"+id +  \" name: \"+name);\n\t\t\n\t\tvar keyElement = \n\t\t\t\"<div class='radio'>\" +\n\t\t\t\"<label>\"+\n\t\t\t\"<input type='radio' name='key' value='\"+id+\"' id='\"+id+\"'>\"+\n\t\t    name+\n\t\t    \"</label>\"+\n\t\t    \"</div>\";\n\t\treturn keyElement;\n\t\t\n\t}\n\t\t\n\t\n\tfunction listCryptoKeyStore(){\n\t\tcbKeyStore.listKeys().then(function(list) {\n\t\t\t$( \"#cryptoKeyList\" ).empty();\n\t\t\tfor (var i=0; i<list.length; i++) {\n       \t\t\t$( \"#cryptoKeyList\" ).append( \n       \t\t\t\t\taddToCryptoKeyList (list[i]));\n        \t}\n   \t\t }).catch(function(err) {\n        \talert(\"Could not list key store: \" + err);\n    \t});\n\t}\n\t\n\tfunction addToCryptoKeyList(keystoreObject){\n\t\tvar id = keystoreObject.id;\n\t\tvar savedObject = keystoreObject.value;\n\t\tvar name = escapeHTML(savedObject.keyName);\n\t\tconsole.log(\"add key to list id:\"+id +  \" name: \"+name);\n\t\t\n\t\tvar keyElement = \n\t\t\t\"<div class='radio'>\" +\n\t\t\t\"<label>\"+\n\t\t\t\"<input type='radio' name='cryptokey' value='\"+id+\"' id='\"+id+\"'>\"+\n\t\t    name+\n\t\t    \"</label>\"+\n\t\t    \"</div>\";\n\t\treturn keyElement;\n\t\t\n\t}\n\t\n\tfunction escapeHTML(s) {\n        return s.toString().replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/'/g, \"&apos;\");\n    }\n\t\n\t\t\n\t\n\tfunction handleDeleteClick(){\n\t\tvar selectedKeyId = parseInt($('input:radio[name=key]:checked').val());\n\t\tconsole.log (\"Deleting key \"+selectedKeyId);\n\t\tif (selectedKeyId){\n\t\t\tkeyStore.deleteKey(selectedKeyId).then(function(){\n\t\t\t\tlistKeyStore();\n\t\t\t}).catch(function(err) {\n\t        \talert(\"Could not delete key : \" + err);\n\t    \t});\n\t\t\t\n\t\t}\n\t}\n\tfunction handleDeleteCryptoKeyClick(){\n\t\tvar selectedKeyId = parseInt($('input:radio[name=cryptokey]:checked').val());\n\t\tconsole.log (\"Deleting key \"+selectedKeyId);\n\t\tif (selectedKeyId){\n\t\t\tcbKeyStore.deleteKey(selectedKeyId).then(function(){\n\t\t\t\tlistCryptoKeyStore();\n\t\t\t}).catch(function(err) {\n\t        \talert(\"Could not delete key : \" + err);\n\t    \t});\n\t\t\t\n\t\t}\n\t}\n\t\n\tfunction handleImportPkcs12Click(){\n\t\t\n\t\tvar file = document.getElementById('pkcs12File').files[0];\n\t    var password = $(\"#password\").val();\n\t    var extractable = $('#extractable').is(':checked');\n\t    \n\t\timportPkcs12(file, password,extractable);\n\t}\n\t\n\tfunction handleExportClick(){\n\t\tvar selectedKeyId = parseInt($('input:radio[name=key]:checked').val());\n\t\tvar selectedKeyName;\n\t\tconsole.log (\"Exporting key \"+selectedKeyId);\n\t\t\n\t\t\n\t\tkeyStore.getKey(\"id\",selectedKeyId).\n        then (function (pkcs12Entry){\n        \tselectedKeyName = pkcs12Entry.name;\n    \t\tconsole.log(\"exportKey:\"+ selectedKeyName);\n    \t\tvar password = window.prompt(\"Insert password for .p12\",\"\");\n\t    \treturn keyStore.exportKey (selectedKeyId,password);\n        }).then(function(p12b64){\n        \tif (isIE())\n        \t\tdownloadAsBlob(p12b64,selectedKeyName);\n        \telse {\n        \t\tvar downloadLink = 'data:application/x-pkcs12;base64,' + p12b64;\n        \t\twindow.location = downloadLink;\n        \t}\n        }).catch (function( err){\n        \talert(\"Error exporting key: \"+err);\n        });\n\t\t\n\t}\n\t\n\tfunction downloadAsBlob(p12b64,selectedKeyName){\n\t\tvar blob = b64toBlob(p12b64,'application/x-pkcs12');\n    \tvar name = selectedKeyName+ \".p12\";\n    \tif (window.saveAs) {\n    \t\twindow.saveAs(blob, name); \n    \t} else { \n    \t\tnavigator.saveBlob = navigator.saveBlob || navigator.msSaveBlob || navigator.mozSaveBlob || navigator.webkitSaveBlob;\n    \t\tnavigator.saveBlob(blob, name); \n    \t}\n\t}\n\t\n\t \n\t"
  },
  {
    "path": "test/web/hosted/js/login.js",
    "content": "\nvar uAg = navigator.userAgent.toLowerCase();\nvar isMobile = !!uAg.match(/android|iphone|ipad|ipod|blackberry|symbianos/i);\n\nvar config;\n\nvar webcrypto = true;\nvar webcryptoError;\n\nvar keyStore;\nvar keyStoreList;\n\nvar cbKeyStore;\nvar cbKeyStoreList;\n\n\n\n\n\n$(function () {\n\t$(\"[data-toggle='tooltip']\").tooltip();\n});\n\n\tfunction start(conf){\n\t\tconfig = conf;\n\t\tssls = new SSLSignature(config.apiUrl, config.accountId, config.apiKey,config.tokenType);\n\t}\n\n\t$(document).ready(function(){\n\t\tconfigureForm();\n\t\t\n\t\tif (isWebCryptoEnabled()){\n\t\t\tcheckWebCrypto();\n\t\t\topenWebCryptoKeyStore();\n\t\t}\n\t\tif (isCryptoKeysEnabled()){\n\t\t\tcheckCryptoKeys();\n\t\t\topenCryptoKeysKeyStore();\n\t\t}\t\n\t});\t\n\t\n\tfunction configureForm(){\n\t\t$(\"#webcryptoOff\").hide();\n\t\t$(\"#cryptokeysOff\").hide();\n\t\t\n\t\tif (!isCertificateEnabled()){\n\t\t\t$(\"#idByCert\").hide();\n\t\t}\t\n\t\tif (!isClaveEnabled()){\n\t\t\t$(\"#idByClave\").hide();\n\t\t}\n\t\tif (!isWebCryptoEnabled()){\n\t\t\t$(\"#webcryptoListOn\").hide();\n\t\t\t$(\"#webcryptoOff\").hide();\n\t\t}\t\n\t\tif (!isCryptoKeysEnabled()){\n\t\t\t$(\"#cryptokeysListOn\").hide();\n\t\t\t$(\"#cryptokeysOff\").hide();\n\t\t}\n\t\tif (!isPasswordEnabled()){\n\t\t\t$(\"#idByPassword\").hide();\n\t\t}\t\t\n\n\t\tif (config.siteTitle){\n\t\t\t$(\"#siteTitle\").text(config.siteTitle);\n\t\t}\n\t\tif (config.siteDescription){\n\t\t\t$(\"#siteDescription\").text(config.siteDescription);\n\t\t}\n\t}\n\t\n\tfunction isWebCryptoEnabled(){\n\t\treturn  !(config.signInOptions && config.signInOptions.indexOf(\"WEBCRYPTO\") == -1);\n\t}\n\tfunction isCryptoKeysEnabled(){\n\t\treturn  !(config.signInOptions && config.signInOptions.indexOf(\"CRYPTOKEYS\") == -1);\n\t}\n\tfunction isCertificateEnabled(){\n\t\treturn  !(config.signInOptions && config.signInOptions.indexOf(\"CERTIFICATE\") == -1);\n\t}\n\tfunction isClaveEnabled(){\n\t\treturn  !(config.signInOptions && config.signInOptions.indexOf(\"CLAVE\") == -1);\n\t}\n\tfunction isPasswordEnabled(){\n\t\treturn  !(config.signInOptions && config.signInOptions.indexOf(\"PASSWORD\") == -1);\n\t}\n\t\n\tfunction checkWebCrypto(){\n\t\tif (!window.crypto || !window.crypto.subtle) {\n\t\t\tdisableWebCrypto(\"Web Cryptographi API no soportada!\");\n\t    }\n\t    \n\t    if (!window.indexedDB) {\n\t\t\tdisableWebCrypto(\"IndexedDB no soportada!\");\n\t    } \n\t}\n\tfunction checkCryptoKeys(){\n\t\tif (!window.crypto || !window.crypto.subtle) {\n\t\t\tdisableCryptoKeys(\"Web Cryptographi API no soportada!\");\n\t    }\n\t    \n\t    if (!window.indexedDB) {\n\t\t\tdisableCryptoKeys(\"IndexedDB no soportada!\");\n\t    } \n\t}\n\t\n\tfunction disableWebCrypto(message){\n\t\twebcrypto = false;\n\t\twebcryptoError = message;\n\t\t\n\t\t$(\"#webcryptoOff\").attr('title', message).tooltip('fixTitle').tooltip('show');\n\t\t$(\"#webcryptoOff\").show();\n\t\t\n\t\t$(\"#webcryptoListOn\").hide();\n\t}\n\t\n\tfunction disableCryptoKeys(message){\n\t\twebcrypto = false;\n\t\twebcryptoError = message;\n\t\t\n\t\t$(\"#cryptokeysOff\").attr('title', message).tooltip('fixTitle').tooltip('show');\n\t\t$(\"#cryptokeysOff\").show();\t\t\n\t\t\n\t\t$(\"#cryptokeysOn\").hide();\n\t\t$(\"#cryptokeysListOn\").hide();\n\t}\n\t\n\tfunction enableWebCrypto(list){\n\t\tkeyStoreList = list;\n\t\t$('#webcryptoList').empty();\n\t\tfor (var i=0; i<list.length; i++) {\n\t\t\tconsole.log(\"key \"+i+ \" id:\"+list[i].id +  \" name: \"+list[i].value.name+ \" keyId: \"+list[i].value.keyId+ \" keyName: \"+list[i].value.keyName);\n\t\t\tid = list[i].id;\n\t\t\tname = list[i].value.name;\n\t\t\t$(\"#webcryptoList\").append(\"<li><a href='javascript:loginByWebCryptoId(\"+id+\")'>\"+name+\"</a></li>\");\n\t\t}\n\t\t$('#webcryptoListOn').show();\n\t}\n\t\n\tfunction enableCryptoKeys(list){\n\t\tcbKeyStoreList = list;\n\t\tif (list.length == 1 ){\n\t\t\tconsole.log(\"key \"+0+ \" id:\"+list[0].id +  \" userId: \"+list[0].value.name+ \" keyId: \"+list[0].value.keyId+ \" keyName: \"+list[0].value.keyName);\n\t\t\tuserId = list[0].value.name;\n\t\t\tkeyName = list[0].value.keyName;\n\t\t\t$(\"#cryptokeysOn\").attr(\"onclick\",\"javascript:loginByCryptoId(\\\"\"+userId+\"\\\")\");\n\t\t\t$('#cryptokeysOn').show();\n\t\t\t$('#cryptokeysListOn').hide();\n\t\t} else {\n\t\t\t$('#cryptokeysList').empty();\n\t\t\tfor (var i=0; i<list.length; i++) {\n\t\t\t\tconsole.log(\"key \"+i+ \" id:\"+list[i].id +  \" userId: \"+list[i].value.name+ \" keyId: \"+list[i].value.keyId+ \" keyName: \"+list[i].value.keyName);\n\t\t\t\tuserId = list[i].value.name;\n\t\t\t\tkeyName = list[i].value.keyName;\n\t\t\t\t$(\"#cryptokeysList\").append(\"<li><a href='javascript:loginByCryptoId(\\\"\"+userId+\"\\\")'>\"+keyName+\"</a></li>\");\n\t\t\t}\n\t\t\t$('#cryptokeysListOn').show();\n\t\t\t$('#cryptokeysOn').hide();\n\t\t}\t\n\t}\n\t\n\tfunction openWebCryptoKeyStore(){\n\t    if (webcrypto){\n\t    \tconsole.log(\"1. Init WebCrypto KeyStore\");\n\t    \tkeyStore = new KeyStore();\t\n\t    \tkeyStore.open().then(function() {\n\t    \t\tconsole.log (\"  WebCrypto KeyStore opened\");\n\t    \t\treturn  keyStore.listKeys();\n\t\t    }).then(function(list) {\n\t\t        console.log(\"Existen WebCrypto claves: \"+list.length);\n\t\t        if (list.length == 0){\n\t\t        \tdisableWebCrypto(\"No hay certificados disponibles\");\n\t\t        } else  {\n\t\t        \tenableWebCrypto(list);\t\t \n\t\t        \t\n\t\t        }    \n\t\t        \n\t    \t}).catch(function(err) {\n\t    \t\tdisableWebCrypto(\"Could not open key store: \"+err);\n\t    \t});\n\t    }\n\t}    \n\t\n\t\n\tfunction openCryptoKeysKeyStore(){\n\t \tif (webcrypto){\n\t    \tconsole.log(\"2. Init CryptoKeys KeyStore\");\n\t    \tcbKeyStore = new KeyStore();\n\t    \tcbKeyStore.open(\"CBKeyStore\").then(function() {\n\t    \t\tconsole.log (\"  CryptoKeys KeyStore opened\");\n\t    \t\treturn  cbKeyStore.listKeys();\n\t\t    }).then(function(list) {\n\t\t        console.log(\"Existen CryptoKeys claves: \"+list.length);\n\t\t        if (list.length == 0){\n\t\t        \tdisableCryptoKeys(\"No hay claves disponibles\");\n\t\t        } else  {\n\t\t        \tenableCryptoKeys(list);\t\t        \t\n\t\t        }\n\t    \t}).catch(function(err) {\n\t    \t\tdisableCryptoKeys(\"Could not open key store: \"+err);\n\t    \t});\n\t    }\t\n\t}\n\n\t\n\tfunction loginByCert () {\n\t\tvar loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByCert?p=1' + buildRedirect();\n\t\tdoRedirect(loginUrl);\t\t\n\t}\n\n\tfunction loginByClave () {\n\t\tvar loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByClave?p=1' + buildRedirect();\n\t\t//doRedirect(loginUrl);\n\t\twindow.location.href = loginUrl;\n\t}\t\n\t\n\tfunction loginByWebCrypto () {\n\t\tconsole.log(\"loginByWebCrypto\");\n\t\tconsole.log(Date.now());\n\t\tvar textToSign = \"Solicitud de autorizacion\";\n\t\tvar pin;\n\t\t\n\t\t//Box y Document a firmar. Por defecto XML\n\t\t\n\t\tvar content = \"<login></login>\";\n\t\tvar filename = \"login.xml\";\n\t\tvar name = \"login\";\n\t\tvar mimetype = \"application/xml\";\n\t\tvar contentB64 = forge.util.encode64( content);\n\t\t\n\t\t//TODO: Usar firma b�sica enviando el X509-->Solo una llamada a servidor\n\t\t// O bien optimizar teniendo el fichero b�sico ya en servidor con un ID--> solo se utiliza \n\t\t\n\t\t\n\t\tvar boxRequest = { EvidenceBox: \t{ name: \"Login\"\t} };\n\t\tssls.postBox(boxRequest).then (function (box){\n\t\t\tboxId = box.EvidenceBox.id;\n\t\t\tconsole.log(\"Box creada: \"+boxId);\n\t\t\tvar documentRequest = { Evidence:{name: name,filename: filename, mimetype: mimetype, type: \"DOCUMENT\", content:contentB64}};\n\t\t\treturn ssls.postDocument(boxId, null,documentRequest);\n\t\t}).then(function (document){\n\t\t\tdocumentId = document.Evidence.id;\n\t\t\tconsole.log(\"Documento creado: \"+documentId);\n\t\t\tvar params ={};\n\t\t    params.showKeystore = function(){window.location = \"keystore.html\" };\n\t\t\treturn keyStore.selectClientCertificate();\n\t\t}).then (function (currentKey){   \n\t\t\tconsole.log (\"Selected certificate to sign: \"+currentKey.name)\n\t\t\tvar signatureParams = { signatureLevel: 'XAdES_BASELINE_B',\tsignaturePackaging: 'ENVELOPED',digestAlgorithm : 'SHA256'};\n\t\t\tvar token = new SignatureToken (ssls);\n\t\t    return token.sign(documentId,currentKey, signatureParams);\n\t\t}).then(function(signature) {\n\t\t\tvar signatureId = signature.Evidence.id;\n        \tconsole.log (\"signature performed: \"+signature.Evidence.id);\n        \tvar loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idBySignature?signatureId='+signatureId+buildRedirect();\n        \t\n        \tdoRedirect(loginUrl);\n    \t\t//window.location.href = loginUrl;\n\t\t}).catch (function (result){\n\t\t\tconsole.log(result);\n\t\t\tshowMessage(\"Error en la identificación: \"+result.message);\n\t\t});\n\t\t\n\t}\t\n\t\n\tfunction loginByWebCryptoId (keyId) {\n\t\tconsole.log(\"loginByWebCryptoID \"+keyId);\n\t\tvar textToSign = \"Solicitud de autorizaci�n\";\n\t\tvar pin;\n\t\t\n\t\t//Box y Document a firmar. Por defecto XML\n\t\t\n\t\tvar content = \"<login></login>\";\n\t\tvar filename = \"login.xml\";\n\t\tvar name = \"login\";\n\t\tvar mimetype = \"application/xml\";\n\t\tvar contentB64 = forge.util.encode64( content);\n\t\t\n\t\t//TODO: Usar firma b�sica enviando el X509-->Solo una llamada a servidor\n\t\t// O bien optimizar teniendo el fichero b�sico ya en servidor con un ID--> solo se utiliza \n\t\t\n\t\t\n\t\tvar boxRequest = { EvidenceBox: \t{ name: \"Login\"\t} };\n\t\tssls.postBox(boxRequest).then (function (box){\n\t\t\tboxId = box.EvidenceBox.id;\n\t\t\tconsole.log(\"Box creada: \"+boxId);\n\t\t\tvar documentRequest = { Evidence:{name: name,filename: filename, mimetype: mimetype, type: \"DOCUMENT\", content:contentB64}};\n\t\t\treturn ssls.postDocument(boxId, null,documentRequest);\n\t\t}).then(function (document){\n\t\t\tdocumentId = document.Evidence.id;\n\t\t\tconsole.log(\"Documento creado: \"+documentId);\n\t\t    return keyStore.getKey(\"id\",keyId);\n\t\t}).then (function (currentKey){   \n\t\t\tconsole.log (\"Selected certificate to sign: \"+currentKey.name)\n\t\t\tvar signatureParams = { signatureLevel: 'XAdES_BASELINE_B',\tsignaturePackaging: 'ENVELOPED',digestAlgorithm : 'SHA256'};\n\t\t\tvar token = new SignatureToken (ssls);\n\t\t    return token.sign(documentId,currentKey, signatureParams);\n\t\t}).then(function(signature) {\n\t\t\tvar signatureId = signature.Evidence.id;\n        \tconsole.log (\"signature performed: \"+signature.Evidence.id);\n        \t\n        \tvar loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idBySignature?signatureId='+signatureId+buildRedirect();\n        \tdoRedirect(loginUrl);\n        \t\n    \t\t//window.location.href = loginUrl;\n\t\t}).catch (function (result){\n\t\t\tconsole.log(result);\n\t\t\tshowMessage(\"Error en la identificación: \"+result.message);\n\t\t});\n\t\t\n\t}\t\n\t\n\tfunction loginByCryptoId(userId){\n\t\tconsole.log(userId);\n\t\t\n\t\tconsole.log (\"Iniciando cryptoId con userId: \"+userId);\n\t\tcbKeyStore.getKey(\"name\",userId).then (function (currentKey){\n\t\t\tvar jwtHeader = {\"alg\":\"RS256\"};\n\t\t    var jwtPayload = {\"sub\":userId, \"exp\":(Date.now()/1000 + 60)}; \n\t\t    var pin;\t\t   \n\t\t    \n\t\t    return JWT.sign(jwtHeader,jwtPayload,currentKey,pin);\n\t\t}).then (function (token){\n\t\t   \tconsole.log(\"JWT: \"+token);\n\t\t   \t\n\t\t   \tvar loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByCryptoKey?userId='+userId+'&jwt='+token+buildRedirect();\n        \tdoRedirect(loginUrl);\n/*\n\t\t   \tvar sslsUser = new SSLSignature(apiUrl,userId,token,\"CJWT\");\n\n\t\t\treturn sslsUser.getUser();\n\t\t}).then(function (us){\n\t\t\tvar\tuserConnected = us.User;\n\t\t\tconsole.log (userConnected);*/\n\t \t}).catch (function (result){\n\t\t    console.log(result);\n\t\t    showMessage(\"Error en la identificación: \"+result.message);\n\t\t });\n\t}\n\t\n\tfunction loginByUserPwd(){\n\t\tvar username = $('#username').val();\n\t\tvar password = $('#password').val();\n\n\t\tif ( !username){\n\t\t\talert('Please, insert your user name');\n\t\t\treturn;\n\t\t}\t\t\n\t\t\n\t\tif ( !password){\n\t\t\talert('Please, insert your password');\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tvar sslsUser = new SSLSignature(config.apiUrl,username,password);\n\n\t\tsslsUser.getUser().then (function(us){\n\t\t\tuserId = us.User.id;\n\t\t\tconsole.log (\"login user: \"+userId);\n\t\t\treturn sslsUser.issueJWT(userId);\n\t\t}).then (function (jwtResponse){\n\t\t\tjwt = jwtResponse.JWT.data;\n\t\t\tconsole.log(\"Issued JWT token by server: \"+jwt);\n\t\t\t\n\t\t   \tvar loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByJWT?userId='+userId+'&jwt='+jwt+buildRedirect();\n        \tdoRedirect(loginUrl);\n    \t\t//window.location.href = loginUrl;\n\n    \t\t\n\t\t}).catch (function (result){\n\t\t\tconsole.log(result);\n\t\t\tshowMessage(\"Error en la identificación \"+result.status + ' - ' + result.statusText + ' - ' +result.responseText)\n\t\t});\n\t}\n\t\n\tfunction doRedirect(url){\n\n\t\tconsole.log(\"redirecting to: \"+url);\n\t\t//window.location.href = url;\n\t\t\n\t\tvar iframe = document.createElement('iframe');\n\t\tiframe.style.display = \"none\";\n\t\tiframe.src = url;\n\t\tiframe.id = 'ssls.login.iframe';\n\t\tdocument.body.appendChild(iframe);\n\t}\n\t \n\t function buildRedirect(){\n\t\t if (config && config.signInSuccessUrl){\n\t\t\t return '&redirect.url=' + config.signInSuccessUrl;\n\t\t } else {\n\t\t\t return '';\n\t\t }\n\t\t\n\t\t \n\t }\n\t \n\t function onIdentification(operation){\n\t\t\tvar userId = operation.userId;\n\t\t\tif (userId){\n\t\t\t\tconsole.log (\"[PAGE SSO] User logged with userId \"+userId);\n\t\t\t} else {\n\t\t\t\tconsole.log (\"[PAGE SSO] User logged but not registered\");\n\t\t\t}\n\t\t\tconsole.log(\"[PAGE] eidentifier: \"+ operation.eIdentifier);\n\t\t\tconsole.log(\"[PAGE] name: \"+ operation.name);\n\t\t\tconsole.log(\"[PAGE] jwt: \"+ operation.jwt);\n\t\t}\n\t\tfunction onLoad(){\n\t\t\tconsole.log (\"[PAGE SSO] Loaded\");\n\t\t}\n\t\tfunction onLogout(){\n\t\t\tconsole.log(\"[PAGE SSO] logout\");\t\t\t\n\t\t}\n\n\tfunction showMessage(message){\n\t\talert(message);\n\t}\n\t\n"
  },
  {
    "path": "test/web/hosted/js/register.js",
    "content": "﻿\nvar config = {\n        apiUrl: 'https://produccion.sslsignature.com/sslsignature',\n        accountId: '5995a3c9-678b-4338-a674-362af68b9ef9'\n};\nvar ssls = null;\n\t\n\tfunction start(conf){\n\t\tconfig = conf;\n\t\tssls = new SSLSignature(config.apiUrl, config.accountId, config.apiKey,config.tokenType);\n\t}\n\t\n\t\n\t\n\tfunction onIdentification(operation){\n\t\tconsole.log(\"SSO PAGE onIdentification\");\n\t\tauthenticationPerformed(operation);\t\t\n\t}\n\tfunction onLoad(){\n\t\tconsole.log(\"SSO PAGE onLoad\");\n\t}\n\tfunction onLogout(){\n\t\tconsole.log(\"SSO PAGE onLogout\");\n\t}\n\t\n\t\n\tfunction showRegisterMessage(message,alertClass){\n\t\tif (!alertClass){\n\t\t\talertClass = \"alert alert-info well-sm\";\n\t\t} \n\t\n\t\t$('#identifiedUser').show();\n\t\t$('#identifiedUser').text(message);\n\t\t$('#identifiedUser').attr(\"class\",alertClass);\n\t}\n\t\n\t\n\tfunction handleRegisterUserClick(){\n\t\tvar username = $('#usernameSignup').val();\n\t\tvar nif = $('#nifSignup').val(); // Solo cryptokeys\n\t\tvar email = $('#emailSignup').val();\n\t\tvar phone = $('#phoneSignup').val();\n\t\tvar password = $('#passwordSignup').val();\n\t\tvar password2 = $('#passwordSignup2').val();\n\n\t\tif ( !username){\n\t\t\tshowRegisterMessage(\"Insert username\",\"alert alert-warning well-sm\");\n\t\t\treturn;\n\t\t}\t\t\n\t\tif ( !phone){\n\t\t\tshowRegisterMessage(\"Insert a phone number\",\"alert alert-warning well-sm\");\n\t\t\treturn;\n\t\t}\t\n\t\tif ( !email ){\n\t\t\tshowRegisterMessage(\"Insert an email\",\"alert alert-warning well-sm\");\n\t\t\treturn;\n\t\t}\n\t\tif ( !password){\n\t\t\tshowRegisterMessage(\"Insert password\",\"alert alert-warning well-sm\");\n\t\t\treturn;\n\t\t}\t\n\t\tif ( password != password2){\n\t\t\tshowRegisterMessage(\"Passwords do not match\",\"alert alert-warning well-sm\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tvar userToRegister = {User:{\n\t\t\tphone:phone,\n\t\t\tname:username,\n\t\t\temail:email,\n\t\t\tnif:nif,\n\t\t\tpassword:password\n\t\t}};\n\t\t\n\t\tproceedToRegister(userToRegister);\n\t}\t\n\t\t\n\tfunction proceedToRegister(userToRegister){\n\t\t//Register user on SSLSignature server\n\t\tssls.registerUser(userToRegister).then (function(createdUser){\n\t\t\tuserId = createdUser.User.id;\n\t\t\tconsole.log (\"User created: \"+userId);\n\t\t\t//Issue JWT Id token for created user\n\t\t\treturn ssls.issueJWT(userId);\n\t\t}).then (function (jwtResponse){\n\t\t\tjwt = jwtResponse.JWT.data;\n\t\t\tconsole.log(\"Issued JWT token by server: \"+jwt);\n\t\t\t\n\t\t\t//Store JWT in browser sSO\n\t\t\tsslssso.login(jwt);\n\t\t\talert (\"User registered with ID \"+userId);\n\t\t\tif (config.registerSuccessUrl){\n\t\t\t\twindow.location.href = config.registerSuccessUrl;\n\t\t\t}\n\t\t}).catch (function (err){\n\t\t\tshowRegisterError(err);\n\t\t});\n\t}\n\t\n\tfunction showRegisterError(err){\n\t\tconsole.log(err);\n\t\tvar error = \"No se ha podido registrar el usuario\";\n\t\tif (err && err.responseJSON ){\n\t\t\terror = error + \": \"+err.responseJSON.error;\n\t\t} else if (err) {\n\t\t\terror = error + \": \"+err.status+ \"-\"+err.statusText;\n\t\t}\t\n\t\talert (error);\n\t}\n\t\n\t\n\tfunction authenticationPerformed(operation){\n\t\tvar userId = operation.userId;\n\t\tvar jwt = operation.jwt;\n\t\tif (userId){\n\t\t\tconsole.log (\"User registered with userId \"+userId);\n\t\t\tshowRegisterMessage (\"User registere\");\n\t\t} else {\n\t\t\tconsole.log (\"User  is not registered\");\n\t\t\tvar name = operation.name;\n\t\t\tvar email = operation.email;\n\t\t\tvar nif = operation.eIdentifier;\n\t\t\tif (operation.nif){\n\t\t\t\tnif = operation.nif;\n\t\t\t} \n\t\t\tconsole.log (\"name: \"+name + \" nif:\"+nif)\n\t\t\t$('#usernameSignup').val(name);\n\t\t\t$('#nifSignup').val(nif);\n\t\t\t$('#emailSignup').val(email);\n\t\t}\n\t\t\n\t\t\n\t}\n\t\n\t\n\t\n\t"
  },
  {
    "path": "test/web/hosted/jwtcreator.html",
    "content": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - JWT Creator</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->\n\t\t\n\t\t<META NAME=\"ROBOTS\" CONTENT=\"NOINDEX, NOFOLLOW\">\n\t\t\n\t\t<meta name=\"ssls.accountId\" content=\"5995a3c9-678b-4338-a674-362af68b9ef9\" />\n\t\t<meta name=\"ssls.validate\" content=\"false\" />\n\t\t \n\t\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t</head>\n\t<body>\n\n\t\t<!-- CTA -->\n\t\t<div id=\"cta\" class=\"container\">\n\t\t\t\n\t\t\t<div class=\"text-center pad-top \">\n\t\t\t\t<h2>JWT creator </h2>\n\t\t\t\t<p>Set the fields, issue a new token, store in browser</hp>\n\t\t\t</div>\t\n \t\t\t<div class=\"row  pad-top\">\n               \n                <div class=\"col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1\">\n                \n                        <div class=\"panel panel-default\">\n                            \n                            <div class=\"panel-body\">\n                                <form id=\"jwtForm\" role=\"form\" >\n                                \t\n\t\t\t\t\t\t\t\t\t\t<div id=\"identifiedUser\" class=\"well well-sm\"  hidden>JWT issued <a href=\"index.html\">(view)</a></div>\n\t\t\t\t\t\t\t\t\t<!-- \t\t\t\t\t\t\t\t\t<br/> -->\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-user\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"User unique ID (sub)\" id=\"sub\"  value=\"123456\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-credit-card\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Your unique identifier(eidentifier)\" id=\"eidentifier\"  value=\"john.smith\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\">@</span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Full name (name)\" id=\"name\" value=\"John Smith\"/>\n                                        </div>\n                                     \t<div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-phone-alt\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Your phone number (phone)\" id=\"phone\" value=\"34 661661661\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\">@</span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Your email (email)\" id=\"email\" value=\"john.smith@mycompany.com\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-credit-card\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Other interesting field (other)\" id=\"other\" value=\"...\"/>\n                                        </div>\n                                     \n                                     \n                                     <a href=\"javascript:handleCreateJWTClick()\" class=\"btn btn-success \">Create JWT token</a>\n                                    </form>\n                            </div>\n                           \n                        </div>\n                    </div>\n                \n                \n        </div>\n\t</div>\n\t\t\n\t\t\n\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n    <!--SSO--><script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js\"></script><!--SSO-->\n    <script src=\"js/config.js\"></script>\n    \n    <script>\n    \t    \t\n    \tfunction onIdentification(operation){\n    \t\tconsole.log(\"SSO PAGE onIdentification event\" );\n    \t\t$('#identifiedUser').show();\n    \t\t\n    \t}\n    \tfunction onLoad(){\n    \t\tconsole.log(\"SSO PAGE onLoad event\");\n    \t}\n    \tfunction onLogout(){\n    \t\tconsole.log(\"SSO PAGE onLogout event\");\n    \t\t$('#identifiedUser').hide();\n    \t}\n    \t\n    \t\n    \tfunction handleCreateJWTClick(){\n    \t\tvar url = config.apiUrl + \"/account/jwt\";\n    \t\tvar params = {\n    \t\t\tsub:\t$('#sub').val(),\n    \t\t\teidentifier:\t$('#eidentifier').val(),\n    \t\t\tname:\t$('#name').val(),\n    \t\t\tphone:\t$('#phone').val(),\n    \t\t\temail:\t$('#email').val(),\n    \t\t\tother:\t$('#other').val()\n    \t\t}\n    \t\tconsole.log(\"POST \"+url);\n    \t\tconsole.log(params);\n    \t\t\n    \t\t$.ajax({\n    \t\t\t  type: \"POST\",\n    \t\t\t  url: url,\n    \t\t\t  data: JSON.stringify(params),\n    \t\t\t  success: function(jwt) {\n  \t\t\t\t\tconsole.log(\"JWT: \"+jwt.JWT.data);\n\t\t\t\t\t//Store JWT in browser SSO\n\t\t\t\t\tsslssso.login(jwt.JWT.data);\n\t\t\t\t\t$('#identifiedUser').show();\n                  },\n                  contentType: \"application/json\",\n    \t\t\t  beforeSend: function (xhr) {\n    \t\t\t\tvar auth =  config.tokenType+\" \" + btoa(config.accountId + ':' + config.apiKey);\n  \t\t\t\t\txhr.setRequestHeader(\"Authorization\", auth);\n  \t\t\t\t  }\n\t\t\t});\n    \t\t\n    \t}\t\n    \t\n    \t\n    </script>\n\t</body>\n</html>"
  },
  {
    "path": "test/web/hosted/keystore.html",
    "content": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\n\t\t<title>SSLSignature KeyStore</title>\n\t    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->\n\t\t<link rel=\"icon\" href=\"img/favicon.ico\">\n\t\t <!-- Bootstrap core CSS -->\n    \t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t\n\t</head>\n<body>\n\t<div class=\"container\">\n\t\t<div>\n   \t\t\t<h2>SSLSignature Keystore</h2>\n   \t \t\t<p>Store digital certificates and private keys on browser using Web Cryptography Api</p>\n   \t \t</div>\n    \n    \t<div id=\"webcryptoAlert\" class=\"alert alert-warning well-sm\" role=\"alert\" hidden></div>\n   \t \t<div>\n   \t \t\t<hr/>\n   \t \t\t<h3>Available digital certificates</h3>\n\t\t\t\n\t\t\t<div id = \"keyList\" class=\"input-group\">\t\t\t\t\n\t        </div>\n\t        <div class=\"btn-group\">\n\t\t\t\t<button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#importCertificateModal\">Import</button>\n\t\t\t\t<a href=\"javascript:handleExportClick();\" id=\"export\" class=\"btn btn-default \" role=\"button\">Export</a>\n\t\t\t\t<a href=\"javascript:handleDeleteClick();\" id=\"delete\" class=\"btn btn-default\" role=\"button\">Delete</a>\n\t\t\t</div>\n\t\t</div>\n\t\n   \t \t<div>\n   \t \t\t<hr/>\n   \t \t\t<h3>Available CryptoKeys </h3>\n\t\t\t\n\t\t\t<div id = \"cryptoKeyList\" class=\"input-group\">\t\t\t\t\n\t        </div>\n\t        <div class=\"btn-group\">\n\t\t\t\t<a href=\"javascript:handleDeleteCryptoKeyClick();\" id=\"deleteCryptoKey\" class=\"btn btn-default\" role=\"button\">Delete</a>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n\t\n\t\n\t<div class=\"modal fade\" id=\"importCertificateModal\" tabindex=\"-1\" role=\"dialog\">\n\t  <div class=\"modal-dialog\">\n\t    <div class=\"modal-content\">\n\t      <div class=\"modal-header\">\n\t        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n\t        <h4 class=\"modal-title\">Import certificate (PFX o P12)</h4>\n\t      </div>\n\t      <div class=\"modal-body\">\n\t        <p>Select the file with your certificate and enter the password. The certificate will be stored in the native keystore of the browser and could not be exportable, therefore you should maintain an additional copy of your certificates</p>\n\t\t\t<div class=\"form-group\">\n\t\t\t    <input type=\"file\" name=\"content\" id=\"pkcs12File\" placeholder=\".pfx o .p12 file\" />\n\t\t\t</div>\n\t\t\t<div class=\"form-group\">\n    \t\t\t<label for=\"password\">Password</label>\n    \t\t\t<input type=\"password\" name=\"password\" id=\"password\" value=\"\" placeholder =\"Contrasea .p12 or .pfx \" class=\"form-control\">\n  \t\t\t</div>\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t<div class=\"checkbox\">\n\t\t\t  <label>\n\t\t\t    <input type=\"checkbox\" id=\"extractable\" name=\"extractable\">\n\t\t\t    Mark the key as exportable\n\t\t\t  </label>\n\t\t\t</div>\t\n\t      </div>\n\t      <div class=\"modal-footer\">\n\t        <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleImportPkcs12Click();\">Import</button>\n\t        <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n\t      </div>\n\t    </div>\n\t  </div>\n\t</div>\n\t\n\t\n\t\n\n\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n    <!-- <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js\"></script> -->\n        \n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js\"></script>\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js\"></script>\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js\"></script>\n\t\n\t<script src=\"js/keystore.js\"></script>\n\t</body>\t\n</html>"
  },
  {
    "path": "test/web/hosted/login.html",
    "content": "<!DOCTYPE HTML>\n<html>\n<head>\n\t<title>SSO SSLSignature</title>\n\t<meta charset=\"utf-8\">\n\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->\n\t<meta name=\"description\" content=\"\" />\n\t<meta name=\"keywords\" content=\"\" />\n\t<META NAME=\"ROBOTS\" CONTENT=\"NOINDEX, NOFOLLOW\">\n\t<link rel=\"icon\" href=\"img/favicon.ico\">\n\t\n\t<meta name=\"ssls.accountId\" content=\"5995a3c9-678b-4338-a674-362af68b9ef9\" />\n\t\n\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\n</head>\n\n\n <body>\n \t<div class=\"container\">\n   \t\t<div class=\"text-center pad-top \">\n   \t\t\t<h2 id=\"siteTitle\">SSO ID FORM</h2>\n   \t \t\t<p id=\"siteDescription\">Select ID method</p>\n   \t \t</div>\n   \t \t<div class=\"row pad-top\">\n           \t<div class=\"col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1\">\t\n                <hr/>\n                <button type=\"button\" class=\"btn btn-default btn-block\" aria-label=\"Left Align\" onclick=\"loginByCert();\" id=\"idByCert\"><span><img  src=\"img/cert.png\" alt=\"Identificación por certificado electrónico SSL\"  height=\"20\" class=\"pull-left\"></span> ID por certificado (SSL)</button>\n                <button type=\"button\" class=\"btn btn-default btn-block\" aria-label=\"Left Align\" onclick=\"loginByClave();\" id=\"idByClave\"><span><img  src=\"img/clave.gif\" alt=\"Identificación por cl@ve\"  height=\"20\" class=\"pull-left\"></span> ID por cl@ve</button>\n\t\t\t \t\n\t\t\t \t <!-- WebCryptographyApi -->\n\t\t\t \t<div class=\"btn-group btn-block\" id=\"webcryptoListOn\">\n          \t  \t\t<button type=\"button\" class=\"btn btn-default col-lg-11\" aria-label=\"Left Align\" onclick=\"loginByWebCrypto();\"><span><img  src=\"img/cert.png\" alt=\"Identificación por certificado electrónico con WebCrypto\"  height=\"20\" class=\"pull-left\"></span> ID por certificado (WebCrypto)</button>\n\t\t\t  \t\t<button type=\"button\" class=\"btn btn-default dropdown-toggle col-lg-1\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n\t\t\t  \t \t\t<span class=\"caret\"></span>\n\t\t\t     \t\t<span class=\"sr-only\">Toggle Dropdown</span>\n\t\t\t  \t\t</button>\n\t\t\t  \t\t<ul class=\"dropdown-menu\" id=\"webcryptoList\">\n\t\t\t  \t\t</ul>\n\t\t  \t\t</div> \n\t\t  \t\t<!-- \n\t\t  \t\t<div class=\"form-group has-error has-feedback\" id=\"webcryptoOff\">\n          \t\t\t<button type=\"button\" class=\"btn btn-default btn-block\" aria-label=\"Left Align\" disabled>\n          \t\t\t\t<span><img  src=\"img/cert.png\" alt=\"Identificación por certificado electrónico con WebCrypto\"  height=\"20\" class=\"pull-left\"></span> \n          \t\t\t\tID por certificado (WebCrypto)\n          \t\t\t</button> \n          \t\t\t<span class=\"glyphicon glyphicon-warning-sign form-control-feedback\" aria-hidden=\"true\"></span> \n          \t\t\t<span id=\"webcryptoAlert\" class=\"help-block\" hidden></span> \n          \t\t\n          \t\t</div>\n          \t\t-->\n          \t\t\n          \t\t<button type=\"button\" class=\"btn btn-default btn-block\" aria-label=\"Left Align\" id=\"webcryptoOff\" data-toggle=\"tooltip\" title=\"\">\n         \t\t\t\t<span><img  src=\"img/cert.png\" alt=\"Identificación por certificado electrónico con WebCrypto\"  height=\"20\" class=\"pull-left\"></span> \n         \t\t\t\tID with digital certificate (WebCrypto)\n         \t\t\t\t<span class=\"glyphicon glyphicon-warning-sign pull-right\" aria-hidden=\"true\"></span>\n       \t\t\t</button> \n        \t\t\t\n\t\t\t \t<!-- CryptoKeys -->\n\t\t\t \t\n\t\t\t \t<button id=\"cryptokeysOn\" type=\"button\" class=\"btn btn-default btn-block\" aria-label=\"Left Align\">\n\t\t\t \t\t<span><img  src=\"img/cryptokeys.png\" alt=\"Identificación por CryptoKey\"  height=\"20\" class=\"pull-left\" ></span> \n\t\t        \t ID with CryptoKey\n\t\t        </button>  \n\t\t\t \t<div id=\"cryptokeysListOn\" class=\"btn-group btn-block\" >\n\t\t\t\t\t  <button type=\"button\" class=\"btn btn-default btn-block dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n\t\t\t\t\t  \t<span><img  src=\"img/cryptokeys.png\" alt=\"Identificación por CryptoKey\"  height=\"20\" class=\"pull-left\"></span> ID with CryptoKey <span class=\"caret pull-right\"></span>\n\t\t\t\t\t  </button>\n\t\t\t\t\t  <ul class=\"dropdown-menu\" id=\"cryptokeysList\">\n\t\t\t\t\t  </ul>\n\t\t\t\t</div>\n\t\t        \n\t\t       \t      \n\t\t        <button  id=\"cryptokeysOff\" type=\"button\" class=\"btn btn-default btn-block\" aria-label=\"Left Align\"   data-toggle=\"tooltip\" title=\"opa\">\n\t\t        \t<span><img  src=\"img/cryptokeys.png\" alt=\"Identificación por CryptoKey\"  height=\"20\" class=\"pull-left\" ></span> \n\t\t        \t ID with CryptoKey\n\t\t        \t <span class=\"glyphicon glyphicon-warning-sign pull-right\" aria-hidden=\"true\"></span>  \n\t\t        </button>\n\t\t         \n\t\t        <!-- Usuario y contraseña -->\n\t\t        \n\t\t\t \t<button type=\"button\" class=\"btn btn-default btn-block\" data-toggle=\"modal\" data-target=\"#loginByUserPwd\" id=\"idByPassword\"> <span><img  src=\"img/pwd.png\" alt=\"Identificación por usuario y contraseña\"  height=\"20\" class=\"pull-left\"></span> ID por contraseña</button>\n\t\t\t \t<hr/>\n\t\t\t \t<a href=\"register.html\" class=\"btn btn-success \">Register</a>\n\t\t\t \t<a href=\"keystore.html\" class=\"pull-right\" >Manage Key Store</a>\n\t\t \t</div>\n\t\t \t \n\t\t</div>\n\t</div>\t\n\t\n\t<div class=\"modal fade\" id=\"loginByUserPwd\" tabindex=\"-1\" role=\"dialog\">\n\t  <div class=\"modal-dialog\">\n\t    <div class=\"modal-content\">\n\t      <div class=\"modal-header\">\n\t        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n\t        <h4 class=\"modal-title\">ID with username and password</h4>\n\t      </div>\n\t      <div class=\"modal-body\">\n\t        <p>Enter your CryptoKeys credentials. You have to be registered to use this service</p>\n\t\t\t<div class=\"form-group\">\n    \t\t\t<label for=\"password\">User</label>\n    \t\t\t<input type=\"text\" name=\"username\" id=\"username\" value=\"\" placeholder =\"username / email / private ID / phone\" class=\"form-control\">\n  \t\t\t</div>\n\t\t\t<div class=\"form-group\">\n    \t\t\t<label for=\"password\">Password</label>\n    \t\t\t<input type=\"password\" name=\"password\" id=\"password\" value=\"\" placeholder =\"Password \" class=\"form-control\">\n  \t\t\t</div>\n\t\t\t\t\t\n\t\t\t\t<!-- \n\t\t\t<div class=\"checkbox\">\n\t\t\t  <label>\n\t\t\t    <input type=\"checkbox\" id=\"extractable\" name=\"extractable\">\n\t\t\t    Marcar la clave como exportable\n\t\t\t  </label>\n\t\t\t</div>\t\n\t\t\t -->\n\t      </div>\n\t      <div class=\"modal-footer\">\n\t        <button type=\"button\" class=\"btn btn-primary\" onclick=\"loginByUserPwd();\">Identify</button>\n\t        <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n\t      </div>\n\t    </div>\n\t  </div>\n\t</div>\t\n\t\n\t\n\t\n\t\n\t <!-- Bootstrap core JavaScript\n    ================================================== -->\n    <!-- Placed at the end of the document so the pages load faster -->\n    \n    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n \t <!--SSO--><script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js\"></script><!--SSO-->\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js\"></script>\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js\"></script>\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js\"></script>\n    <script src=\"js/login.js\"></script>\n    <script src=\"js/config.js\"></script>\n\n    <script>\n    \t\n    \tstart (config);\n    \t\n    \tsslssso.listen(\"sso.onload\", function(observable, eventType, data){\n\t        console.log(\"----------------\");\n\t        console.log(\"sso.onload\");\n\t        console.log(\"----------------\");\n\t    });\n    \tsslssso.listen(\"sso.onidentification\", function(observable, eventType, data){\n\t        console.log(\"----------------\");\n\t        console.log(\"sso.onidentification\");\n\t        console.log(\"----------------\");\n\t    });\n    </script>\n   \n</body>\n</html>"
  },
  {
    "path": "test/web/hosted/register.html",
    "content": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - Cryptokeys</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->\n\t\t\n\t\t<META NAME=\"ROBOTS\" CONTENT=\"NOINDEX, NOFOLLOW\">\n\t\t<link rel=\"icon\" href=\"img/favicon.ico\">\n\t\t<meta name=\"ssls.accountId\" content=\"5995a3c9-678b-4338-a674-362af68b9ef9\" />\n\t\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t</head>\n\t<body>\n\n\t\t<!-- CTA -->\n\t\t<div id=\"cta\" class=\"container\">\n\t\t\t\n\t\t\t<div class=\"text-center pad-top \">\n\t\t\t\t<h2>CryptoKeys Register</h2>\n\t\t\t</div>\t\n \t\t\t<div class=\"row  pad-top\">\n               \n                <div class=\"col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1\">\n                \n                        <div class=\"panel panel-default\">\n                            \n                            <div class=\"panel-body\">\n                                <form role=\"form\">\n                                \t<div id=\"identifiedUser\" class=\"alert alert-info well-sm\" role=\"alert\">User not identified</div>\n\t\t\t\t\t\t\t\t\t<!-- \t\t\t\t\t\t\t\t\t<br/> -->\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-user\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Su nombre\" id=\"usernameSignup\"/>\n                                        </div>\n                                     \t<div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-phone-alt\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Su teléfono (+34xxxxx)\" id=\"phoneSignup\"/>\n                                        </div>\n                                         <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\">@</span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Su correo (email@server.es)\" id=\"emailSignup\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-credit-card\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Su NIF (12345678A)\" id=\"nifSignup\"/>\n                                        </div>\n                                      <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-lock\"  ></i></span>\n                                            <input type=\"password\" class=\"form-control\" placeholder=\"Contraseña de recuperación\" id=\"passwordSignup\"/>\n                                        </div>\n                                     <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-lock\"  ></i></span>\n                                            <input type=\"password\" class=\"form-control\" placeholder=\"Vuelva a introducir la contraseña\" id=\"passwordSignup2\"/>\n                                        </div>\n                                     \n                                     <a href=\"javascript:handleRegisterUserClick()\" class=\"btn btn-success \">Register</a>\n                                    <hr />\n                                    ¿Ya registrado? <a href=\"login.html\" >Identify</a>\n                                    </form>\n                            </div>\n                           \n                        </div>\n                    </div>\n                \n                \n        </div>\n\t</div>\n\t\t\n\t\t\n\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\t<!--SSO--><script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js\"></script><!--SSO-->\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js\"></script>\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js\"></script>\n    <script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js\"></script>\n    <script src=\"js/register.js\"></script>\n    <script src=\"js/config.js\"></script>\n    <script>\n    \tstart (config);\n    \t</script>\n\t</body>\n</html>"
  },
  {
    "path": "test/web/hosted/sso.html",
    "content": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>SSLSignature Demo SSO</title>\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t<meta name=\"ssls.accountId\" content=\"5995a3c9-678b-4338-a674-362af68b9ef9\" />\n\t\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t\t\n\t</head>\n\t<script>\n\t\t// Fired after validating JWT on page onLoad process, or after a successful identification\n\t\tfunction onIdentification(operation){\n\t\t\t$( \"#title\" ).html(\"Welcome \"+operation.name + \"(\"+operation.eIdentifier+\")\");\n\t\t\t$( \"#token\" ).html(\"JWT\");\n\t\t\t\n\t\t\t$( \"#body\" ).val(JSON.stringify(operation, null, '\\t'));\n\t\t\t$( \"#body\" ).show();\n\t\t}\n\t\t//Fired when sso is fully loaded\n\t\tfunction onLoad(){\n\t\t}\n\t\t//Fired onLogout\n\t\tfunction onLogout(){\n\t\t\tconsole.log(\"[PAGE] logout\");\n\t\t\t$( \"#title\" ).html(\"Welcome!! \");\n\t\t\t$( \"#token\" ).html(\"No identification token (JWT) available\");\n\t\t\t$( \"#body\" ).hide();\n\t\t}\n\t</script>\n\t\t\n<body>\n\n\t<div class=\"jumbotron\">\n      <div class=\"container\">\n        <h1>SSLSignature SingleSignOn Demo</h1>\n        <p>Multidomain Single Sign On with Json Web Token (JWT)</p>\n      </div>\n    </div>\n    \n    <section id=\"main\">\n   \t \t<div class=\"container\">\n   \t \t\t<h2 id=\"title\">Welcome!!</h2>\n   \t \t\t<p id=\"token\">No identification token (JWT) available</p>\n \t \t\t\t<textarea  id=\"body\" rows=10 disabled class=\"form-control\" style=\"min-width: 100%\"></textarea>\n   \t \t\t\n\t\t\t<hr/>\n\t\t\t <a type=\"button\" class=\"btn btn-success\" aria-label=\"Left Align\" href=\"jwtcreator.html\">JWT creator</a>\n\t\t\t <a type=\"button\" class=\"btn btn-primary\" aria-label=\"Left Align\" href=\"login.html\">Identify</a>\n\t\t\t <button type=\"button\" class=\"btn btn-danger\" aria-label=\"Left Align\" onclick=\"sslssso.logout();\"><span class=\"glyphicon glyphicon-off\" aria-hidden=\"true\"></span> Logout</button>\n\t\t</div>\n\t</section>\n\t\n\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n     <!--SSO--><script src=\"https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js\"></script><!--SSO-->\n   \n\t\n</body>\n</html>"
  },
  {
    "path": "test/web/standalone/index.html",
    "content": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - JWT Creator</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t\t\t\n\t\t<meta name=\"ssls.accountId\" content=\"jwtdemo\" />\n\t\t<meta name=\"ssls.validate\" content=\"false\" />\n\t\t\t\t \n\t\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t</head>\n\t<body>\n\n\t\t<!-- CTA -->\n\t\t<div id=\"cta\" class=\"container\">\n\t\t\t\n\t\t\t<div class=\"text-center pad-top \">\n\t\t\t\t<h2>JWT creator </h2>\n\t\t\t\t<p>Set the fields, issue a new token, store in browser</hp>\n\t\t\t</div>\t\n \t\t\t<div class=\"row  pad-top\">\n               \n                <div class=\"col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1\">\n                \n                        <div class=\"panel panel-default\">\n                            \n                            <div class=\"panel-body\">\n                                <form id=\"jwtForm\" role=\"form\" >\n                                \t\n\t\t\t\t\t\t\t\t\t\t<div id=\"identifiedUser\" class=\"well well-sm\"  hidden>JWT issued <a href=\"sso.html\">(view)</a></div>\n\t\t\t\t\t\t\t\t\t<!-- \t\t\t\t\t\t\t\t\t<br/> -->\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-user\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"User unique ID (sub)\" name=\"sub\" value=\"123456\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-credit-card\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Your unique identifier(eidentifier)\" name=\"eidentifier\" value=\"john.smith\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\">@</span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Full name (name)\" name=\"name\" value=\"John Smith\"/>\n                                        </div>\n                                     \t<div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-phone-alt\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Your phone number (phone)\" name=\"phone\" value=\"34 661661661\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\">@</span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Your email (email)\" name=\"email\" value=\"john.smith@mycompany.com\"/>\n                                        </div>\n                                        <div class=\"form-group input-group\">\n                                            <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-credit-card\"  ></i></span>\n                                            <input type=\"text\" class=\"form-control\" placeholder=\"Other interesting field (other)\" name=\"other\" value=\"...\"/>\n                                        </div>\n                                     \n                                     \n                                     <a href=\"javascript:handleCreateJWTClick()\" class=\"btn btn-success \">Create JWT token</a>\n                                    </form>\n                            </div>\n                           \n                        </div>\n                    </div>\n                \n                \n        </div>\n\t</div>\n\t\t\n\t\t\n\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n    <script src=\"../resources/js/sslssso.js\"></script>\n   \n    \n    <script>\n    \t\n  \t\t//URL of server\n\t\tvar issueTokenUrl = document.location.origin+\"/sso/jwt\";\n  \t\t\n    \t//1) Sends an AJAX POST request to  the sample server in /sso/jwt with the required fields\n    \t//2) The server returns a new JWT with sent info which is signed with server  key (hmac)\n    \t//3) The JWT is stored in browser usign sslsso.login(jwt)\n    \t//4) An sslssso.onIdentification event is fired to all listeners\n    \t//\n    \t// Issue JWT after a successful user authentication in your own login form (on server side) \n    \tfunction handleCreateJWTClick(){\n    \t\t\n    \t\tvar params = $('#jwtForm').serialize();\n    \t\tconsole.log(\"POST \"+issueTokenUrl);\n    \t\tconsole.log(params);\n    \t\t$.post(\n    \t\t\t\tissueTokenUrl, \n    \t\t\t\tparams,\n    \t\t\t\tfunction(jwt) {\n    \t\t\t\t\tconsole.log(\"JWT: \"+jwt);\n    \t\t\t\t\t//Store JWT in browser SSO\n    \t\t\t\t\tsslssso.login(jwt);\n    \t\t\t\t\t$('#identifiedUser').show();\n                    });\n    \t\t\n    \t}\t\n    \t\n    \t\n    </script>\n\t</body>\n</html>"
  },
  {
    "path": "test/web/standalone/sso.html",
    "content": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>SSLSignature Demo SSO</title>\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t<meta name=\"ssls.accountId\" content=\"jwtdemo\" />\n\t\t<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t\t\n\t</head>\n\t<script>\n\t\t//sslssso will connect this URL to validate JWT\n\t\t//Use full URL because it will be invoked from user browser\n\t\tssls_validationUrl = document.location.origin+\"/sso/jwt\";\n\t\n\t\t// Fired after validating JWT on page onLoad process, or after a successful identification\n\t\tfunction onIdentification(operation){\n\t\t\t$( \"#title\" ).html(\"Welcome \"+operation.name + \"(\"+operation.eidentifier+\")\");\n\t\t\t$( \"#token\" ).html(\"JWT\");\n\t\t\t\n\t\t\t$( \"#body\" ).val(JSON.stringify(operation, null, '\\t'));\n\t\t\t$( \"#body\" ).show();\n\t\t}\n\t\t//Fired when sso is fully loaded\n\t\tfunction onLoad(){\n\t\t}\n\t\t//Fired onLogout\n\t\tfunction onLogout(){\n\t\t\tconsole.log(\"[PAGE] logout\");\n\t\t\t$( \"#title\" ).html(\"Welcome!! \");\n\t\t\t$( \"#token\" ).html(\"No identification token (JWT) available\");\n\t\t\t$( \"#body\" ).hide();\n\t\t}\n\t</script>\n\t\t\n<body>\n\n\t<div class=\"jumbotron\">\n      <div class=\"container\">\n        <h1>SSLSignature SingleSignOn Demo</h1>\n        <p>Multidomain Single Sign On with Json Web Token (JWT)</p>\n      </div>\n    </div>\n    \n    <section id=\"main\">\n   \t \t<div class=\"container\">\n   \t \t\t<h2 id=\"title\">Welcome!!</h2>\n   \t \t\t<p id=\"token\">No identification token (JWT) available</p>\n \t \t\t\t<textarea  id=\"body\" rows=10 disabled class=\"form-control\" style=\"min-width: 100%\"></textarea>\n   \t \t\t\n\t\t\t<hr/>\n\t\t\t <a type=\"button\" class=\"btn btn-primary\" aria-label=\"Left Align\" href=\"index.html\">Identify</a>\n\t\t\t <button type=\"button\" class=\"btn btn-danger\" aria-label=\"Left Align\" onclick=\"sslssso.logout();\"><span class=\"glyphicon glyphicon-off\" aria-hidden=\"true\"></span> Logout</button>\n\t\t</div>\n\t</section>\n\t\n\t<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n    <script src=\"../resources/js/sslssso.js\"></script>\n   \n\t\n</body>\n</html>"
  }
]