diff --git a/README.md b/README.md index cd2dc98..3aa2a8c 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,8 @@ Compact, developer-friendly monorepo for a central identity service, a branded l ## Current phase status - **P01 Foundation:** complete, initial commit `8f54ccb`. - **P02 ZITADEL local backend:** pinned official images, development Compose and secure local bootstrap helper source prepared. **Docker startup and Admin Console integration remain unverified**; all follow-up local testing is explicitly deferred to a future Gitea Actions scope. -- **P03 Login V2 source / P04 Account Portal:** not started. +- **P03 Login V2 source:** official v4.20.4 source and matching client/proto workspace imported under `auth/ui/v2/`; no redesign or runtime build/test was performed. **CI validation remains pending.** +- **P04 Account Portal:** not started. - **Production / Coolify:** not configured or deployed. ## Responsibility map @@ -14,7 +15,7 @@ Compact, developer-friendly monorepo for a central identity service, a branded l | --- | --- | | `core/backend/zitadel/` | Official ZITADEL backend integration and local helper | | `deployment/docker/compose.backend.dev.yaml` | Loopback-only developer stack | -| `auth/ui/v2/` | Future customized official Login V2 source (P03) | +| `auth/ui/v2/` | Official Login V2 monorepo subset (Next.js source in `apps/login/`, matched client/proto and pnpm/Nx workspace) | | `users/ui/` | Future account self-service portal (P04) | | `packages/` | Shared packages only when needed | | `tests/` | Focused contracts and future integration/UI tests | @@ -38,4 +39,4 @@ When the backend stack is actually running, the local Admin Console is expected - One Git repo, isolated containers; ZITADEL Go source remains upstream. ## Working agreements -Read [AGENTS.md](AGENTS.md), [architecture](docs/ARCHITECTURE.md) and [phase scopes](docs/PHASES.md). Use separate, expressly approved phases; no production secrets or user data in Git. +Read [AGENTS.md](AGENTS.md), [architecture](docs/ARCHITECTURE.md), [P03 source import](docs/P03-SOURCE-IMPORT.md), [Login V2 workspace guide](auth/ui/v2/README.md) and [phase scopes](docs/PHASES.md). Use separate, expressly approved phases; no production secrets or user data in Git. diff --git a/auth/ui/v2/.npmrc b/auth/ui/v2/.npmrc new file mode 100644 index 0000000..7bd5109 --- /dev/null +++ b/auth/ui/v2/.npmrc @@ -0,0 +1,2 @@ +auto-install-peers = true +ignore-scripts = "postman-code-generators" diff --git a/auth/ui/v2/.nvmrc b/auth/ui/v2/.nvmrc new file mode 100644 index 0000000..deed13c --- /dev/null +++ b/auth/ui/v2/.nvmrc @@ -0,0 +1 @@ +lts/jod diff --git a/auth/ui/v2/.nxignore b/auth/ui/v2/.nxignore new file mode 100644 index 0000000..fd3a2de --- /dev/null +++ b/auth/ui/v2/.nxignore @@ -0,0 +1,6 @@ +!console/dist +!console/src/app/proto/generated +!internal/api/ui/console/static +!.artifacts/bin/*/*/zitadel.local +!apps/docs/content/apis/assets/assets.mdx +!apps/docs/content/reference/api/ diff --git a/auth/ui/v2/LICENSE b/auth/ui/v2/LICENSE new file mode 100644 index 0000000..bae94e1 --- /dev/null +++ b/auth/ui/v2/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. \ No newline at end of file diff --git a/auth/ui/v2/LICENSING.md b/auth/ui/v2/LICENSING.md new file mode 100644 index 0000000..67aff71 --- /dev/null +++ b/auth/ui/v2/LICENSING.md @@ -0,0 +1,35 @@ +# Licensing Policy + +This repository is licensed under the [GNU Affero General Public License v3.0](LICENSE) (AGPL-3.0-only). We use the [SPDX License List](https://spdx.org/licenses/) for standard license naming. + +## AGPL-3.0-only Compliance + +ZITADEL is open-source software intended for community use. Determining your application's compliance with the AGPL-3.0-only license is your responsibility. + +**We strongly recommend consulting with legal counsel or licensing specialists to ensure your usage of ZITADEL, and any other integrated open-source projects, adheres to their respective licenses. AGPL-3.0-only compliance can be complex.** + +If your application triggers AGPL-3.0-only obligations and you wish to avoid them (e.g., you do not plan to open-source your modifications or application), please [contact us](https://zitadel.com/contact) to discuss commercial licensing options. Using ZITADEL without verifying your license compliance is at your own risk. + +## Exceptions to AGPL-3.0-only + +The following files and directories, including their subdirectories, are licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0): + +``` +proto/ +apps/docs/ +``` + + +The following files and directories, including their subdirectories, are licensed under the [MIT License](https://opensource.org/license/mit/): + +``` +apps/login/ +packages/zitadel-client/ +packages/zitadel-proto/ +``` + +## Community Contributions + +To maintain a clear licensing structure and facilitate community contributions, all contributions must be licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) to be accepted. By submitting a contribution, you agree to this licensing. + +This approach avoids the need for a Contributor License Agreement (CLA) while ensuring clarity regarding license terms. We will only accept contributions licensed under Apache 2.0. diff --git a/auth/ui/v2/README.md b/auth/ui/v2/README.md index 7236d0c..7e2347c 100644 --- a/auth/ui/v2/README.md +++ b/auth/ui/v2/README.md @@ -1,3 +1,52 @@ -# Login V2 frontend +# ZitPlane Login UI V2 — Upstream Source Workspace -Reserved for a customized official ZITADEL Next.js Login V2. Phase 03 will select and pin an upstream commit, bring all required workspace dependencies, and verify the original behavior before any redesign. No UI source is installed yet. +**Status:** P03 source imported; **not built, tested, launched, or connected to the P02 Compose service**. No UI redesign has been performed. + +This folder is a self-contained **source workspace**, not a single standalone app. Its files were copied from the official `zitadel/zitadel` release tag **v4.20.4**, Git revision **384bb9ec96b501ad39dc232ee2061a40fe180bbd**, matching the pinned P02 backend image. + +## Start here (beginner-friendly) + +| What you want to change | Where to look | +| --- | --- | +| Login / signup / recovery / verification pages | `apps/login/src/app/` | +| Buttons, forms, field styles and reusable UI | `apps/login/src/components/` | +| Global CSS / theme | `apps/login/src/styles/` | +| Images, icons, static assets | `apps/login/public/` | +| Language translations | `apps/login/locales/` | +| Browser/OIDC auth code (protected) | `apps/login/src/lib/` and `apps/login/src/proxy.ts` | +| API client and auth transport (protected) | `packages/zitadel-client/` | +| Generated API types (do not hand-edit) | `packages/zitadel-proto/` and `proto/` | +| Tooling and pinned dependency graph | `package.json`, `pnpm-workspace.yaml`, `pnpm-lock.yaml`, `nx.json` | + +App source is at **`auth/ui/v2/apps/login/`**, not directly under `auth/ui/v2/src`. This deliberately preserves the upstream workspace layout, so Next.js/Nx/proto imports are easier to maintain. + +## Local/CI workflow — commands are DOCUMENTED ONLY (not executed in P03) + +From the **`auth/ui/v2`** folder after the development environment is available: + +```sh +corepack enable +pnpm install --frozen-lockfile +pnpm nx run @zitadel/proto:generate +pnpm nx run @zitadel/client:build +pnpm nx run @zitadel/login:build +``` + +The partial upstream workspace has the **original full-monorepo lockfile**. A CI phase must confirm if frozen installation works with these retained importers. If it does not, reconcile the lockfile with a separately approved dependency-only change and pin the revised artifact before calling the source reproducible. **Do not silently run plain `pnpm install` or auto-upgrade packages.** + +Required environment values, such as `ZITADEL_API_URL` and a dedicated Login Client PAT, must be supplied **only at runtime in secure, ignored local files or CI secrets**. No credentials or real tokens are stored here. The upstream tracked `apps/login/.env` and `apps/login/.env.prod` were intentionally **not imported** to avoid confusing dev/prod config; follow the ZITADEL docs when wiring environment values. The upstream `apps/login/.env.theme.example` remains as a safe design reference. + +## Scope and update rules + +- Edit **visual-only** components, CSS, icons and copy only after P06 is explicitly approved. +- Do **not** change OIDC, MFA, SSO, server actions, routing, token handling, passkey, cookies or session logic as a side effect of visual work. +- P03 does **not** replace `zitadel-login` in the P02 Docker Compose; P05 will wire the customized image after CI checks. +- This source is an import snapshot. Updating it requires selecting a new official release, reading release notes, importing the whole dependency closure from the same revision, and running future CI verification. +- The upstream Login app and the client/proto TypeScript packages are MIT-licensed; upstream `proto/` is Apache-2.0; root build/config and other files may have different licensing. See upstream `LICENSING.md` and `LICENSE` included here. + +## Provenance and details + +Read [P03 Source Import Evidence](../../../docs/P03-SOURCE-IMPORT.md). + +Official docs: https://zitadel.com/docs/guides/integrate/login-ui/fork-and-deploy-login-app +Official revision: https://github.com/zitadel/zitadel/tree/v4.20.4 diff --git a/auth/ui/v2/apps/login/.env.theme.example b/auth/ui/v2/apps/login/.env.theme.example new file mode 100644 index 0000000..ab5dd7f --- /dev/null +++ b/auth/ui/v2/apps/login/.env.theme.example @@ -0,0 +1,75 @@ +# ============================================== +# ZITADEL LOGIN THEME CONFIGURATION +# ============================================== +# This file contains all available theme options for customizing the login experience. +# Copy the variables you want to customize to your .env.local file. + +# Theme Roundness Options +# ---------------------- +# Controls the border radius of UI elements +# Options: "edgy" | "mid" | "full" +# - edgy: Sharp corners (rounded-none) +# - mid: Medium rounded corners (rounded-lg) +# - full: Fully rounded corners (rounded-full) +NEXT_PUBLIC_THEME_ROUNDNESS=mid + +# Layout Options +# -------------- +# Controls the overall layout structure +# Options: "side-by-side" | "top-to-bottom" +# - side-by-side: Brand section on left, form on right (desktop) +# - top-to-bottom: Brand section on top, form below +NEXT_PUBLIC_THEME_LAYOUT=side-by-side + +# Spacing Options +# --------------- +# Controls spacing and padding throughout the interface +# Options: "regular" | "compact" +# - regular: Standard spacing with comfortable padding (p-6, space-y-6) +# - compact: Tighter spacing for information-dense layouts (p-4, space-y-4) +NEXT_PUBLIC_THEME_SPACING=regular + +# Appearance Options +# ------------------ +# Complete design philosophies +# Options: "flat" | "material" +# - flat: Minimal flat design with cards matching background color, subtle borders, and normal typography +# - material: Material Design inspired with elevated cards, proper contrast, and medium typography +NEXT_PUBLIC_THEME_APPEARANCE=flat + +# Background Image +# --------------- +# Path to a background image (optional) +# Can be a relative path from /public or an absolute URL +# Example: NEXT_PUBLIC_THEME_BACKGROUND_IMAGE=/images/login-bg.jpg +# NEXT_PUBLIC_THEME_BACKGROUND_IMAGE= + +# ============================================== +# EXAMPLE COMBINATIONS +# ============================================== + +# Modern Tech Startup +# NEXT_PUBLIC_THEME_ROUNDNESS=full +# NEXT_PUBLIC_THEME_LAYOUT=side-by-side +# NEXT_PUBLIC_THEME_SPACING=regular +# NEXT_PUBLIC_THEME_APPEARANCE=material +# NEXT_PUBLIC_THEME_BACKGROUND_IMAGE=/images/tech-bg.jpg + +# Corporate Banking +# NEXT_PUBLIC_THEME_ROUNDNESS=edgy +# NEXT_PUBLIC_THEME_LAYOUT=top-to-bottom +# NEXT_PUBLIC_THEME_SPACING=regular +# NEXT_PUBLIC_THEME_APPEARANCE=material + +# Minimal SaaS +# NEXT_PUBLIC_THEME_ROUNDNESS=mid +# NEXT_PUBLIC_THEME_LAYOUT=side-by-side +# NEXT_PUBLIC_THEME_SPACING=compact +# NEXT_PUBLIC_THEME_APPEARANCE=flat + +# Creative Agency +# NEXT_PUBLIC_THEME_ROUNDNESS=full +# NEXT_PUBLIC_THEME_LAYOUT=top-to-bottom +# NEXT_PUBLIC_THEME_SPACING=regular +# NEXT_PUBLIC_THEME_APPEARANCE=material +# NEXT_PUBLIC_THEME_BACKGROUND_IMAGE=/images/creative-bg.jpg diff --git a/auth/ui/v2/apps/login/.gitignore b/auth/ui/v2/apps/login/.gitignore new file mode 100644 index 0000000..41a1674 --- /dev/null +++ b/auth/ui/v2/apps/login/.gitignore @@ -0,0 +1,17 @@ +custom-config.js +.env*.local +standalone +tsconfig.tsbuildinfo +cypress + +.DS_Store +node_modules +*.log +.next +dist +dist-ssr +*.local +.vscode +/blob-report/ +# Dockerized test output (generated by integration tests) +dockerized/*/output/ diff --git a/auth/ui/v2/apps/login/.prettierignore b/auth/ui/v2/apps/login/.prettierignore new file mode 100644 index 0000000..be49df4 --- /dev/null +++ b/auth/ui/v2/apps/login/.prettierignore @@ -0,0 +1,9 @@ +* +!constants +!constants/** +!src +!src/** +!locales +!locales/** +!scripts +!scripts/** diff --git a/auth/ui/v2/apps/login/AGENTS.md b/auth/ui/v2/apps/login/AGENTS.md new file mode 100644 index 0000000..3fc4c2b --- /dev/null +++ b/auth/ui/v2/apps/login/AGENTS.md @@ -0,0 +1,38 @@ +# ZITADEL Login App Guide for AI Agents + +## Context +The **Login App** (`apps/login`) provides the user interface for authentication flows (Login, Register, MFA, etc.). It is built with Next.js and React. + +## Key Technology +- **Framework**: Next.js (React). +- **Styling**: TailwindCSS, configured via `apps/login/tailwind.config.mjs`. +- **Data Fetching**: Primarily server-side interaction with ZITADEL APIs via `@zitadel/client` or direct gRPC calls where applicable. +- **Language**: TypeScript. + +## Architecture & Conventions +- **Routing**: Uses the Next.js App Router (routes are defined under `src/app/`). +- **Composability**: Components should be small and reusable. +- **State**: Critical authentication state is often managed via URL parameters (Auth Requests) and cookies/sessions. +- **Scope Rule**: For shared API typings and client behavior, also read `packages/AGENTS.md` and `proto/AGENTS.md`. + +## Server Actions & Server-Only Code (critical — read before adding or changing a server function) +- **`src/lib/actions/`**: only Server Actions. Every file starts with `"use server"`, and **every export is a public, unauthenticated POST endpoint**, whether or not a component calls it. Treat every argument as attacker-controlled: derive the user, session and policy (lifetimes, link hosts, IdP identities) on the server from the caller's signed cookie and ZITADEL, never from the arguments. +- **`src/lib/server/`**: server-only code. Every file imports `"server-only"`. Helpers that take identity, links or lifetimes as parameters belong here. +- **`src/lib/` (top level)**: code shared with client components only. +- `"use server"` is not allowed anywhere else, inline directives included. The `login/module-boundaries` ESLint rule (`checks/eslint-module-boundaries.mjs`) enforces the layout. +- The build fails when the published actions differ from `checks/server-actions.allowlist.json` (`checks/server-actions.mjs`). Adding an action means reviewing it and adding it there. + +## Base Path & Redirects (critical — read before touching any redirect logic) +- **The login app is served under a non-root base path in production.** ZITADEL Cloud and the official container image are built with `NEXT_PUBLIC_BASE_PATH=/ui/v2/login` (see `apps/login/.env`; the value is inlined at build time by Next.js). Never assume the app lives at the domain root. +- **`constructUrl()` (`src/lib/server/service-url.ts`) prepends the base path and must ONLY ever receive root-relative paths** (`/loginname`, `/password?...`). Passing an absolute URL glues the base path onto it and produces a broken redirect like `https:///ui/v2/loginhttps://login.microsoftonline.com/...`. +- **Some redirect targets ARE absolute URLs**: IdP authorize URLs returned by `startIdentityProviderFlow`, OIDC callback URLs from `createCallback`, and SAML endpoints from `createResponse`. When handling a redirect value that could be absolute, branch on `isExternalUrl()` first, validate absolute URLs with `isSafeRedirectUri()`, and pass them to `NextResponse.redirect` (server) / `window.location.href` (client) untouched. Canonical pattern: `resolveLoginHint` in `src/lib/server/flow-initiation.ts` and `handleServerActionResponse` in `src/lib/client-utils.ts`. +- **An empty base path masks this whole bug class**: with `NEXT_PUBLIC_BASE_PATH` unset, `new URL("" + absoluteUrl, origin)` still parses the absolute URL correctly, so local setups without the base path won't reproduce base-path bugs. Always test redirect changes with `NEXT_PUBLIC_BASE_PATH=/ui/v2/login` set, and verify the raw `Location` header (e.g. `curl -I`), not just browser behavior. + +## Verified Nx Targets +- **Dev Server**: `pnpm nx run @zitadel/login:dev` +- **Build**: `pnpm nx run @zitadel/login:build` +- **Lint**: `pnpm nx run @zitadel/login:lint` +- **Test (all)**: `pnpm nx run @zitadel/login:test` +- **Test (unit)**: `pnpm nx run @zitadel/login:test-unit` +- **Test (integration)**: `pnpm nx run @zitadel/login:test-integration` +- **Pack (Docker)**: `pnpm nx run @zitadel/login:pack` — builds a local Docker image `zitadel/zitadel-login:local`. Requires Docker daemon. diff --git a/auth/ui/v2/apps/login/Dockerfile b/auth/ui/v2/apps/login/Dockerfile new file mode 100644 index 0000000..c737bef --- /dev/null +++ b/auth/ui/v2/apps/login/Dockerfile @@ -0,0 +1,22 @@ +FROM node:24-alpine +WORKDIR /app +RUN addgroup --system --gid 1001 nodejs && \ + adduser --system --uid 1001 nextjs +# If /.env-file/.env is mounted into the container, its variables are made available to the server before it starts up. +RUN mkdir -p /.env-file && touch /.env-file/.env && chown -R nextjs:nodejs /.env-file + +COPY --chown=nextjs:nodejs .next/standalone ./ + +USER nextjs +ENV HOSTNAME="::" \ + PORT="3000" \ + NODE_ENV="production" \ + NODE_OPTIONS="--use-openssl-ca --require /app/load-ssl-cert-dir.cjs" \ + SSL_CERT_FILE="/etc/ssl/certs/ca-certificates.crt" \ + ZITADEL_TLS_ENABLED="false" \ + OTEL_SERVICE_NAME="zitadel-login" \ + OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf" + +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD ["/usr/local/bin/node", "/app/healthcheck.mjs", "/ui/v2/login/ready"] +ENTRYPOINT ["/app/entrypoint.sh", "node", "apps/login/server.js"] diff --git a/auth/ui/v2/apps/login/Dockerfile.fips b/auth/ui/v2/apps/login/Dockerfile.fips new file mode 100644 index 0000000..4784861 --- /dev/null +++ b/auth/ui/v2/apps/login/Dockerfile.fips @@ -0,0 +1,23 @@ +FROM registry.access.redhat.com/ubi9/nodejs-24 +USER root +RUN update-crypto-policies --set FIPS +WORKDIR /app +# If /.env-file/.env is mounted into the container, its variables are made available to the server before it starts up. +RUN mkdir -p /.env-file && touch /.env-file/.env && chown -R 1001:0 /.env-file + +COPY --chown=1001:0 .next/standalone ./ + +USER 1001 +ENV HOSTNAME="::" \ + PORT="3000" \ + NODE_ENV="production" \ + NODE_OPTIONS="--use-openssl-ca --openssl-shared-config --enable-fips --require /app/load-ssl-cert-dir.cjs" \ + SSL_CERT_FILE="/etc/pki/tls/certs/ca-bundle.crt" \ + ZITADEL_TLS_ENABLED="false" \ + ZITADEL_FIPS_REQUIRED="true" \ + OTEL_SERVICE_NAME="zitadel-login" \ + OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf" + +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD ["node", "/app/healthcheck.mjs", "/ui/v2/login/ready"] +ENTRYPOINT ["/app/entrypoint.sh", "node", "apps/login/server.js"] diff --git a/auth/ui/v2/apps/login/LICENSE b/auth/ui/v2/apps/login/LICENSE new file mode 100644 index 0000000..89f750f --- /dev/null +++ b/auth/ui/v2/apps/login/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 ZITADEL + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/auth/ui/v2/apps/login/THEME_ARCHITECTURE.md b/auth/ui/v2/apps/login/THEME_ARCHITECTURE.md new file mode 100644 index 0000000..758c7a4 --- /dev/null +++ b/auth/ui/v2/apps/login/THEME_ARCHITECTURE.md @@ -0,0 +1,212 @@ +# Current Theme System Architecture + +Our theme system provides a simple, environment variable-driven approach for consistent component styling and responsive layout switching. + +## 🏗️ **Current Implementation** + +### **Environment Variable Configuration** + +```bash +# .env.local +NEXT_PUBLIC_THEME_ROUNDNESS=mid # edgy | mid | full +NEXT_PUBLIC_THEME_LAYOUT=side-by-side # side-by-side | top-to-bottom +NEXT_PUBLIC_THEME_APPEARANCE=material # flat | material +NEXT_PUBLIC_THEME_SPACING=regular # regular | compact +``` + +### **Core Theme Functions** + +```tsx +// Server-safe theme configuration +import { getThemeConfig, getComponentRoundness } from "@/lib/theme"; + +// Get full theme settings +const themeConfig = getThemeConfig(); +// Returns: { roundness: 'mid', layout: 'side-by-side', appearance: 'material', ... } + +// Get component-specific styling +const buttonRoundness = getComponentRoundness("button"); +// Returns: "rounded-md" (CSS class) +``` + +### **Responsive Layout Hook** + +```tsx +// Client-side responsive layout detection +import { useResponsiveLayout } from "@/lib/theme-hooks"; + +function MyComponent() { + const { isSideBySide, isResponsiveOverride } = useResponsiveLayout(); + + return
{/* Layout adapts automatically */}
; +} +``` + +## 🎨 **Component Integration Patterns** + +### **Pattern 1: Direct Function Calls** (Current Standard) + +```tsx +import { getComponentRoundness } from "@/lib/theme"; + +export function Button({ children, variant = "primary" }) { + const roundness = getComponentRoundness("button"); + + return ( + + ); +} +``` + +### **Pattern 2: Component-Specific Helper Functions** + +```tsx +import { getComponentRoundness } from "@/lib/theme"; + +// Helper function for UserAvatar +function getUserAvatarRoundness(): string { + return getComponentRoundness("avatarContainer"); +} + +export function UserAvatar({ loginName, displayName }) { + const roundness = getUserAvatarRoundness(); + + return
{/* Avatar content */}
; +} +``` + +### **Pattern 3: Theme-Aware Layout Components** + +```tsx +import { useResponsiveLayout } from "@/lib/theme-hooks"; + +export function DynamicTheme({ children, branding }) { + const { isSideBySide } = useResponsiveLayout(); + + return ( + + {isSideBySide ? ( + // Side-by-side layout for desktop +
+
{/* Left content */}
+
{/* Right content */}
+
+ ) : ( + // Top-to-bottom layout for mobile +
{children}
+ )} +
+ ); +} +``` + +## 🎯 **Theme Configuration Structure** + +### **Component Roundness Mapping** + +```tsx +export interface ComponentRoundnessConfig { + card: ThemeRoundness; // "rounded-lg" | "rounded-none" | "rounded-3xl" + button: ThemeRoundness; // "rounded-md" | "rounded-none" | "rounded-full" + input: ThemeRoundness; // "rounded-md" | "rounded-none" | "rounded-full pl-4" + image: ThemeRoundness; // "rounded-lg" | "rounded-none" | "rounded-full" + avatar: ThemeRoundness; // "rounded-lg" | "rounded-none" | "rounded-full" + avatarContainer: ThemeRoundness; // "rounded-md" | "rounded-none" | "rounded-full" + themeSwitch: ThemeRoundness; // "rounded-md" | "rounded-none" | "rounded-full" +} +``` + +### **Responsive Layout Logic** + +```tsx +// Automatic layout switching based on screen size +const isSideBySide = themeConfig.layout === "side-by-side" && !isMdOrSmaller; + +// md breakpoint: 768px (Tailwind default) +// Below 768px: Always use top-to-bottom layout +// Above 768px: Use configured layout (side-by-side or top-to-bottom) +``` + +## � **File Structure** + +``` +src/lib/ +├── theme.ts # Server-safe theme functions +├── theme-hooks.ts # Client-side responsive hooks +└── themeUtils.tsx # Legacy utility functions + +src/components/ +├── dynamic-theme.tsx # Main responsive layout component +├── theme-wrapper.tsx # Theme application wrapper +├── button.tsx # Example themed component +├── card.tsx # Example themed component +└── user-avatar.tsx # Example themed component +``` + +## � **Usage Examples** + +### **Adding Theme Support to New Components** + +```tsx +import { getComponentRoundness } from "@/lib/theme"; + +export function NewComponent() { + // Get theme-appropriate styling + const roundness = getComponentRoundness("card"); + + return
{/* Component content */}
; +} +``` + +### **Using Responsive Layout** + +```tsx +import { useResponsiveLayout } from "@/lib/theme-hooks"; + +export function ResponsiveComponent() { + const { isSideBySide } = useResponsiveLayout(); + + return
Content adapts to layout
; +} +``` + +### **Page Layout Integration** + +```tsx +import { DynamicTheme } from "@/components/dynamic-theme"; + +export default function LoginPage() { + return ( + +
+

Login Title

+

Description text

+
+ +
+ +
+
+ ); +} +``` + +## ⚡ **Key Features** + +1. **Environment Variable Configuration**: Simple `.env.local` setup +2. **Server-Safe Functions**: Work in both SSR and client components +3. **Responsive Layout Switching**: Automatic mobile/desktop adaptation +4. **Component-Specific Styling**: Different roundness per component type +5. **Type Safety**: Full TypeScript support +6. **Zero Runtime Dependencies**: No context providers or complex state +7. **SSR Compatible**: No hydration mismatches + +## 🔄 **Architecture Benefits** + +- **Simple**: Environment variables → CSS classes +- **Fast**: No runtime theme calculations or context switching +- **Reliable**: Server-side rendering compatible +- **Scalable**: Easy to add new theme properties +- **Maintainable**: Clear separation between layout and styling concerns + +This architecture provides a solid foundation for environment-driven theming while keeping the implementation simple and performant! diff --git a/auth/ui/v2/apps/login/THEME_CUSTOMIZATION.md b/auth/ui/v2/apps/login/THEME_CUSTOMIZATION.md new file mode 100644 index 0000000..153e8bb --- /dev/null +++ b/auth/ui/v2/apps/login/THEME_CUSTOMIZATION.md @@ -0,0 +1,138 @@ +# Login App Theme Customization Guide + +This guide helps you customize the appearance of your ZITADEL login application for a personalized user experience. + +## Quick Start + +1. Copy the theme variables you want to customize from `.env.theme.example` to your `.env.local` file +2. Restart your application +3. Your theme changes will be applied automatically + +## Theme Options + +### 🔄 Roundness (`NEXT_PUBLIC_THEME_ROUNDNESS`) + +Controls how rounded the UI elements appear: + +- **`edgy`** - Sharp, rectangular corners (modern tech, corporate) +- **`mid`** - Medium rounded corners (balanced, professional) +- **`full`** - Fully rounded corners (friendly, approachable) + +### 📱 Layout (`NEXT_PUBLIC_THEME_LAYOUT`) + +Controls the overall page structure: + +- **`side-by-side`** - Brand section on left, form on right (desktop view) +- **`top-to-bottom`** - Brand section on top, form below (mobile-first) + +### 📏 Spacing (`NEXT_PUBLIC_THEME_SPACING`) + +Controls spacing and padding throughout the interface: + +- **`regular`** - Standard spacing with comfortable padding (p-6, space-y-6) +- **`compact`** - Tighter spacing for information-dense layouts (p-4, space-y-4) + +### 🎨 Appearance (`NEXT_PUBLIC_THEME_APPEARANCE`) + +Complete design philosophies: + +- **`flat`** - Minimal flat design with cards matching background color, subtle borders, and normal typography +- **`material`** - Material Design inspired with elevated cards, proper contrast, and medium typography + +### 🖼️ Background Image (`NEXT_PUBLIC_THEME_BACKGROUND_IMAGE`) + +Add a custom background image: + +- Use local images: `/images/my-background.jpg` (place in `public/images/`) +- Use external URLs: `https://example.com/background.jpg` +- Leave empty for solid color backgrounds + +## Example Settings + +### Tech Startup + +```env +NEXT_PUBLIC_THEME_ROUNDNESS=full +NEXT_PUBLIC_THEME_LAYOUT=side-by-side +NEXT_PUBLIC_THEME_SPACING=regular +NEXT_PUBLIC_THEME_APPEARANCE=material +NEXT_PUBLIC_THEME_BACKGROUND_IMAGE=/images/tech-gradient.jpg +``` + +### Corporate Bank + +```env +NEXT_PUBLIC_THEME_ROUNDNESS=edgy +NEXT_PUBLIC_THEME_LAYOUT=top-to-bottom +NEXT_PUBLIC_THEME_SPACING=regular +NEXT_PUBLIC_THEME_APPEARANCE=material +``` + +### Minimal SaaS + +```env +NEXT_PUBLIC_THEME_ROUNDNESS=mid +NEXT_PUBLIC_THEME_LAYOUT=side-by-side +NEXT_PUBLIC_THEME_SPACING=compact +NEXT_PUBLIC_THEME_APPEARANCE=flat +``` + +### Creative Agency + +```env +NEXT_PUBLIC_THEME_ROUNDNESS=full +NEXT_PUBLIC_THEME_LAYOUT=top-to-bottom +NEXT_PUBLIC_THEME_SPACING=regular +NEXT_PUBLIC_THEME_APPEARANCE=material +NEXT_PUBLIC_THEME_BACKGROUND_IMAGE=/images/creative-workspace.jpg +``` + +### Flat Design App + +```env +NEXT_PUBLIC_THEME_ROUNDNESS=mid +NEXT_PUBLIC_THEME_LAYOUT=side-by-side +NEXT_PUBLIC_THEME_SPACING=compact +NEXT_PUBLIC_THEME_APPEARANCE=flat +``` + +### Material Design System + +```env +NEXT_PUBLIC_THEME_ROUNDNESS=mid +NEXT_PUBLIC_THEME_LAYOUT=side-by-side +NEXT_PUBLIC_THEME_SPACING=regular +NEXT_PUBLIC_THEME_APPEARANCE=material +``` + +## Advanced Customization + +For more detailed customization beyond these presets, you can: + +1. **Custom CSS**: Add your own CSS files in the `src/styles/` directory +2. **Component Override**: Modify the theme settings in `src/lib/theme.ts` +3. **Custom Appearances**: Add new appearance options to the `APPEARANCE_STYLES` or `SPACING_STYLES` objects + +## Troubleshooting + +### Theme not applying + +- Ensure you're using `NEXT_PUBLIC_` prefix for all theme variables (`NEXT_PUBLIC_THEME_ROUNDNESS`, `NEXT_PUBLIC_THEME_SPACING`, `NEXT_PUBLIC_THEME_APPEARANCE`, etc.) +- Restart your development server after changing environment variables +- Check that your `.env.local` file is in the root of the login app directory + +### Background image not loading + +- Verify the image path is correct +- For external URLs, ensure the domain is accessible +- Check browser console for any loading errors + +### Layout issues on mobile + +- Test your theme on different screen sizes +- The `top-to-bottom` layout is generally more mobile-friendly +- Some combinations work better on certain screen sizes + +## Support + +For additional customization needs or questions, please refer to the ZITADEL documentation or community forums. diff --git a/auth/ui/v2/apps/login/acceptance/.gitignore b/auth/ui/v2/apps/login/acceptance/.gitignore new file mode 100644 index 0000000..6a7425e --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/.gitignore @@ -0,0 +1 @@ +go-command diff --git a/auth/ui/v2/apps/login/acceptance/eslint.config.mjs b/auth/ui/v2/apps/login/acceptance/eslint.config.mjs new file mode 100644 index 0000000..8773b26 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/eslint.config.mjs @@ -0,0 +1,30 @@ +import js from "@eslint/js"; +import tsPlugin from "@typescript-eslint/eslint-plugin"; +import tsParser from "@typescript-eslint/parser"; +import prettierConfig from "eslint-config-prettier/flat"; + +export default [ + { ignores: ["node_modules/**"] }, + js.configs.recommended, + { + files: ["**/*.ts"], + plugins: { + "@typescript-eslint": tsPlugin, + }, + languageOptions: { + parser: tsParser, + ecmaVersion: "latest", + sourceType: "module", + }, + rules: { + ...tsPlugin.configs.recommended.rules, + "no-unused-vars": "off", + "no-undef": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { argsIgnorePattern: "^_" }, + ], + }, + }, + prettierConfig, +]; diff --git a/auth/ui/v2/apps/login/acceptance/go-command.Dockerfile b/auth/ui/v2/apps/login/acceptance/go-command.Dockerfile new file mode 100644 index 0000000..fafebd6 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/go-command.Dockerfile @@ -0,0 +1,11 @@ +ARG LOGIN_TEST_ACCEPTANCE_GOLANG_TAG="golang:1.24-alpine" + +FROM ${LOGIN_TEST_ACCEPTANCE_GOLANG_TAG} +RUN apk add curl jq +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN go build -o /go-command . +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s \ + CMD curl -f http://localhost:${PORT}/healthy || exit 1 +ENTRYPOINT [ "/go-command" ] diff --git a/auth/ui/v2/apps/login/acceptance/idp/oidc/go.mod b/auth/ui/v2/apps/login/acceptance/idp/oidc/go.mod new file mode 100644 index 0000000..860cc54 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/idp/oidc/go.mod @@ -0,0 +1,27 @@ +module github.com/zitadel/typescript/acceptance/idp/oidc + +go 1.24.1 + +require github.com/zitadel/oidc/v3 v3.37.0 + +require ( + github.com/bmatcuk/doublestar/v4 v4.8.1 // indirect + github.com/go-chi/chi/v5 v5.4.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.7 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/muhlemmer/gu v0.3.1 // indirect + github.com/muhlemmer/httpforwarded v0.1.0 // indirect + github.com/rs/cors v1.11.1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/zitadel/logging v0.6.2 // indirect + github.com/zitadel/schema v1.3.1 // indirect + go.opentelemetry.io/otel v1.29.0 // indirect + go.opentelemetry.io/otel/metric v1.29.0 // indirect + go.opentelemetry.io/otel/trace v1.29.0 // indirect + golang.org/x/oauth2 v0.28.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/auth/ui/v2/apps/login/acceptance/idp/oidc/go.sum b/auth/ui/v2/apps/login/acceptance/idp/oidc/go.sum new file mode 100644 index 0000000..b19d7fa --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/idp/oidc/go.sum @@ -0,0 +1,69 @@ +github.com/bmatcuk/doublestar/v4 v4.8.1 h1:54Bopc5c2cAvhLRAzqOGCYHYyhcDHsFF4wWIR5wKP38= +github.com/bmatcuk/doublestar/v4 v4.8.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi/v5 v5.4.0 h1:+ufzvFTGKyin26Or5DLrlIDq4ygIDBVcj7oVNeeaYFE= +github.com/go-chi/chi/v5 v5.4.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= +github.com/go-jose/go-jose/v4 v4.1.7 h1:Nac/98uT5LPkfbiFuYa8ktf62a2VxwQ4xbq1GK8pV5E= +github.com/go-jose/go-jose/v4 v4.1.7/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= +github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/muhlemmer/gu v0.3.1 h1:7EAqmFrW7n3hETvuAdmFmn4hS8W+z3LgKtrnow+YzNM= +github.com/muhlemmer/gu v0.3.1/go.mod h1:YHtHR+gxM+bKEIIs7Hmi9sPT3ZDUvTN/i88wQpZkrdM= +github.com/muhlemmer/httpforwarded v0.1.0 h1:x4DLrzXdliq8mprgUMR0olDvHGkou5BJsK/vWUetyzY= +github.com/muhlemmer/httpforwarded v0.1.0/go.mod h1:yo9czKedo2pdZhoXe+yDkGVbU0TJ0q9oQ90BVoDEtw0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= +github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/zitadel/logging v0.6.2 h1:MW2kDDR0ieQynPZ0KIZPrh9ote2WkxfBif5QoARDQcU= +github.com/zitadel/logging v0.6.2/go.mod h1:z6VWLWUkJpnNVDSLzrPSQSQyttysKZ6bCRongw0ROK4= +github.com/zitadel/oidc/v3 v3.37.0 h1:nYATWlnP7f18XiAbw6upUruBaqfB1kUrXrSTf1EYGO8= +github.com/zitadel/oidc/v3 v3.37.0/go.mod h1:/xDan4OUQhguJ4Ur73OOJrtugvR164OMnidXP9xfVNw= +github.com/zitadel/schema v1.3.1 h1:QT3kwiRIRXXLVAs6gCK/u044WmUVh6IlbLXUsn6yRQU= +github.com/zitadel/schema v1.3.1/go.mod h1:071u7D2LQacy1HAN+YnMd/mx1qVE2isb0Mjeqg46xnU= +go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= +go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= +go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc= +go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8= +go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= +go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= +golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= +golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/auth/ui/v2/apps/login/acceptance/idp/oidc/main.go b/auth/ui/v2/apps/login/acceptance/idp/oidc/main.go new file mode 100644 index 0000000..b04ac94 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/idp/oidc/main.go @@ -0,0 +1,186 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "log/slog" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/zitadel/oidc/v3/example/server/exampleop" + "github.com/zitadel/oidc/v3/example/server/storage" +) + +func main() { + apiURL := os.Getenv("API_URL") + pat := readPAT(os.Getenv("PAT_FILE")) + domain := os.Getenv("API_DOMAIN") + schema := os.Getenv("SCHEMA") + host := os.Getenv("HOST") + port := os.Getenv("PORT") + + logger := slog.New( + slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + AddSource: true, + Level: slog.LevelDebug, + }), + ) + + issuer := fmt.Sprintf("%s://%s:%s/", schema, host, port) + redirectURI := fmt.Sprintf("%s/idps/callback", apiURL) + + clientID := "web" + clientSecret := "secret" + storage.RegisterClients( + storage.WebClient(clientID, clientSecret, redirectURI), + ) + + storage := storage.NewStorage(storage.NewUserStore(issuer)) + router := exampleop.SetupServer(issuer, storage, logger, false) + + server := &http.Server{ + Addr: ":" + port, + Handler: router, + } + go func() { + if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("HTTP server error: %v", err) + } + log.Println("Stopped serving new connections.") + }() + + createZitadelResources(apiURL, pat, domain, issuer, clientID, clientSecret) + + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + <-sigChan + + shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownRelease() + + if err := server.Shutdown(shutdownCtx); err != nil { + log.Fatalf("HTTP shutdown error: %v", err) + } +} + +func readPAT(path string) string { + f, err := os.Open(path) + if err != nil { + panic(err) + } + pat, err := io.ReadAll(f) + if err != nil { + panic(err) + } + return strings.Trim(string(pat), "\n") +} + +func createZitadelResources(apiURL, pat, domain, issuer, clientID, clientSecret string) error { + idpID, err := CreateIDP(apiURL, pat, domain, issuer, clientID, clientSecret) + if err != nil { + return err + } + return ActivateIDP(apiURL, pat, domain, idpID) +} + +type createIDP struct { + Name string `json:"name"` + Issuer string `json:"issuer"` + ClientId string `json:"clientId"` + ClientSecret string `json:"clientSecret"` + Scopes []string `json:"scopes"` + ProviderOptions providerOptions `json:"providerOptions"` + IsIdTokenMapping bool `json:"isIdTokenMapping"` + UsePkce bool `json:"usePkce"` +} + +type providerOptions struct { + IsLinkingAllowed bool `json:"isLinkingAllowed"` + IsCreationAllowed bool `json:"isCreationAllowed"` + IsAutoCreation bool `json:"isAutoCreation"` + IsAutoUpdate bool `json:"isAutoUpdate"` + AutoLinking string `json:"autoLinking"` +} + +type idp struct { + ID string `json:"id"` +} + +func CreateIDP(apiURL, pat, domain string, issuer, clientID, clientSecret string) (string, error) { + createIDP := &createIDP{ + Name: "OIDC", + Issuer: issuer, + ClientId: clientID, + ClientSecret: clientSecret, + Scopes: []string{"openid", "profile", "email"}, + ProviderOptions: providerOptions{ + IsLinkingAllowed: true, + IsCreationAllowed: true, + IsAutoCreation: true, + IsAutoUpdate: true, + AutoLinking: "AUTO_LINKING_OPTION_USERNAME", + }, + IsIdTokenMapping: false, + UsePkce: false, + } + + resp, err := doRequestWithHeaders(apiURL+"/admin/v1/idps/generic_oidc", pat, domain, createIDP) + if err != nil { + return "", err + } + data, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + defer resp.Body.Close() + + idp := new(idp) + if err := json.Unmarshal(data, idp); err != nil { + return "", err + } + return idp.ID, nil +} + +type activateIDP struct { + IdpId string `json:"idpId"` +} + +func ActivateIDP(apiURL, pat, domain string, idpID string) error { + activateIDP := &activateIDP{ + IdpId: idpID, + } + _, err := doRequestWithHeaders(apiURL+"/admin/v1/policies/login/idps", pat, domain, activateIDP) + return err +} + +func doRequestWithHeaders(apiURL, pat, domain string, body any) (*http.Response, error) { + data, err := json.Marshal(body) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, apiURL, io.NopCloser(bytes.NewReader(data))) + if err != nil { + return nil, err + } + values := http.Header{} + values.Add("Authorization", "Bearer "+pat) + values.Add("x-forwarded-host", domain) + values.Add("Content-Type", "application/json") + req.Header = values + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/auth/ui/v2/apps/login/acceptance/idp/saml/go.mod b/auth/ui/v2/apps/login/acceptance/idp/saml/go.mod new file mode 100644 index 0000000..2d79829 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/idp/saml/go.mod @@ -0,0 +1,16 @@ +module github.com/zitadel/typescript/acceptance/idp/saml + +go 1.25.0 + +require ( + github.com/crewjam/saml v0.4.14 + github.com/mattermost/xml-roundtrip-validator v0.1.0 + github.com/zenazn/goji v1.0.1 + golang.org/x/crypto v0.52.0 +) + +require ( + github.com/beevik/etree v1.1.0 // indirect + github.com/jonboulle/clockwork v0.2.2 // indirect + github.com/russellhaering/goxmldsig v1.3.0 // indirect +) diff --git a/auth/ui/v2/apps/login/acceptance/idp/saml/go.sum b/auth/ui/v2/apps/login/acceptance/idp/saml/go.sum new file mode 100644 index 0000000..73f3073 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/idp/saml/go.sum @@ -0,0 +1,49 @@ +github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= +github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/crewjam/saml v0.4.14 h1:g9FBNx62osKusnFzs3QTN5L9CVA/Egfgm+stJShzw/c= +github.com/crewjam/saml v0.4.14/go.mod h1:UVSZCf18jJkk6GpWNVqcyQJMD5HsRugBPf4I1nl2mME= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang-jwt/jwt/v4 v4.4.3 h1:Hxl6lhQFj4AnOX6MLrsCb/+7tCj7DxP7VA+2rDIq5AU= +github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= +github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattermost/xml-roundtrip-validator v0.1.0 h1:RXbVD2UAl7A7nOTR4u7E3ILa4IbtvKBHw64LDsmu9hU= +github.com/mattermost/xml-roundtrip-validator v0.1.0/go.mod h1:qccnGMcpgwcNaBnxqpJpWWUiPNr5H3O8eDgGV9gT5To= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/russellhaering/goxmldsig v1.3.0 h1:DllIWUgMy0cRUMfGiASiYEa35nsieyD3cigIwLonTPM= +github.com/russellhaering/goxmldsig v1.3.0/go.mod h1:gM4MDENBQf7M+V824SGfyIUVFWydB7n0KkEubVJl+Tw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/zenazn/goji v1.0.1 h1:4lbD8Mx2h7IvloP7r2C0D6ltZP6Ufip8Hn0wmSK5LR8= +github.com/zenazn/goji v1.0.1/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= diff --git a/auth/ui/v2/apps/login/acceptance/idp/saml/main.go b/auth/ui/v2/apps/login/acceptance/idp/saml/main.go new file mode 100644 index 0000000..059eab7 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/idp/saml/main.go @@ -0,0 +1,328 @@ +package main + +import ( + "bytes" + "crypto" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "encoding/xml" + "errors" + "io" + "log" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/signal" + "strings" + "syscall" + + "github.com/crewjam/saml" + "github.com/crewjam/saml/logger" + "github.com/crewjam/saml/samlidp" + xrv "github.com/mattermost/xml-roundtrip-validator" + "github.com/zenazn/goji" + "github.com/zenazn/goji/bind" + "github.com/zenazn/goji/web" + "golang.org/x/crypto/bcrypt" +) + +var key = func() crypto.PrivateKey { + b, _ := pem.Decode([]byte(`-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEA0OhbMuizgtbFOfwbK7aURuXhZx6VRuAs3nNibiuifwCGz6u9 +yy7bOR0P+zqN0YkjxaokqFgra7rXKCdeABmoLqCC0U+cGmLNwPOOA0PaD5q5xKhQ +4Me3rt/R9C4Ca6k3/OnkxnKwnogcsmdgs2l8liT3qVHP04Oc7Uymq2v09bGb6nPu +fOrkXS9F6mSClxHG/q59AGOWsXK1xzIRV1eu8W2SNdyeFVU1JHiQe444xLoPul5t +InWasKayFsPlJfWNc8EoU8COjNhfo/GovFTHVjh9oUR/gwEFVwifIHihRE0Hazn2 +EQSLaOr2LM0TsRsQroFjmwSGgI+X2bfbMTqWOQIDAQABAoIBAFWZwDTeESBdrLcT +zHZe++cJLxE4AObn2LrWANEv5AeySYsyzjRBYObIN9IzrgTb8uJ900N/zVr5VkxH +xUa5PKbOcowd2NMfBTw5EEnaNbILLm+coHdanrNzVu59I9TFpAFoPavrNt/e2hNo +NMGPSdOkFi81LLl4xoadz/WR6O/7N2famM+0u7C2uBe+TrVwHyuqboYoidJDhO8M +w4WlY9QgAUhkPyzZqrl+VfF1aDTGVf4LJgaVevfFCas8Ws6DQX5q4QdIoV6/0vXi +B1M+aTnWjHuiIzjBMWhcYW2+I5zfwNWRXaxdlrYXRukGSdnyO+DH/FhHePJgmlkj +NInADDkCgYEA6MEQFOFSCc/ELXYWgStsrtIlJUcsLdLBsy1ocyQa2lkVUw58TouW +RciE6TjW9rp31pfQUnO2l6zOUC6LT9Jvlb9PSsyW+rvjtKB5PjJI6W0hjX41wEO6 +fshFELMJd9W+Ezao2AsP2hZJ8McCF8no9e00+G4xTAyxHsNI2AFTCQcCgYEA5cWZ +JwNb4t7YeEajPt9xuYNUOQpjvQn1aGOV7KcwTx5ELP/Hzi723BxHs7GSdrLkkDmi +Gpb+mfL4wxCt0fK0i8GFQsRn5eusyq9hLqP/bmjpHoXe/1uajFbE1fZQR+2LX05N +3ATlKaH2hdfCJedFa4wf43+cl6Yhp6ZA0Yet1r8CgYEAwiu1j8W9G+RRA5/8/DtO +yrUTOfsbFws4fpLGDTA0mq0whf6Soy/96C90+d9qLaC3srUpnG9eB0CpSOjbXXbv +kdxseLkexwOR3bD2FHX8r4dUM2bzznZyEaxfOaQypN8SV5ME3l60Fbr8ajqLO288 +wlTmGM5Mn+YCqOg/T7wjGmcCgYBpzNfdl/VafOROVbBbhgXWtzsz3K3aYNiIjbp+ +MunStIwN8GUvcn6nEbqOaoiXcX4/TtpuxfJMLw4OvAJdtxUdeSmEee2heCijV6g3 +ErrOOy6EqH3rNWHvlxChuP50cFQJuYOueO6QggyCyruSOnDDuc0BM0SGq6+5g5s7 +H++S/wKBgQDIkqBtFr9UEf8d6JpkxS0RXDlhSMjkXmkQeKGFzdoJcYVFIwq8jTNB +nJrVIGs3GcBkqGic+i7rTO1YPkquv4dUuiIn+vKZVoO6b54f+oPBXd4S0BnuEqFE +rdKNuCZhiaE2XD9L/O9KP1fh5bfEcKwazQ23EvpJHBMm8BGC+/YZNw== +-----END RSA PRIVATE KEY-----`)) + k, _ := x509.ParsePKCS1PrivateKey(b.Bytes) + return k +}() + +var cert = func() *x509.Certificate { + b, _ := pem.Decode([]byte(`-----BEGIN CERTIFICATE----- +MIIDBzCCAe+gAwIBAgIJAPr/Mrlc8EGhMA0GCSqGSIb3DQEBBQUAMBoxGDAWBgNV +BAMMD3d3dy5leGFtcGxlLmNvbTAeFw0xNTEyMjgxOTE5NDVaFw0yNTEyMjUxOTE5 +NDVaMBoxGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBANDoWzLos4LWxTn8Gyu2lEbl4WcelUbgLN5zYm4ron8A +hs+rvcsu2zkdD/s6jdGJI8WqJKhYK2u61ygnXgAZqC6ggtFPnBpizcDzjgND2g+a +ucSoUODHt67f0fQuAmupN/zp5MZysJ6IHLJnYLNpfJYk96lRz9ODnO1Mpqtr9PWx +m+pz7nzq5F0vRepkgpcRxv6ufQBjlrFytccyEVdXrvFtkjXcnhVVNSR4kHuOOMS6 +D7pebSJ1mrCmshbD5SX1jXPBKFPAjozYX6PxqLxUx1Y4faFEf4MBBVcInyB4oURN +B2s59hEEi2jq9izNE7EbEK6BY5sEhoCPl9m32zE6ljkCAwEAAaNQME4wHQYDVR0O +BBYEFB9ZklC1Ork2zl56zg08ei7ss/+iMB8GA1UdIwQYMBaAFB9ZklC1Ork2zl56 +zg08ei7ss/+iMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAVoTSQ5 +pAirw8OR9FZ1bRSuTDhY9uxzl/OL7lUmsv2cMNeCB3BRZqm3mFt+cwN8GsH6f3uv +NONIhgFpTGN5LEcXQz89zJEzB+qaHqmbFpHQl/sx2B8ezNgT/882H2IH00dXESEf +y/+1gHg2pxjGnhRBN6el/gSaDiySIMKbilDrffuvxiCfbpPN0NRRiPJhd2ay9KuL +/RxQRl1gl9cHaWiouWWba1bSBb2ZPhv2rPMUsFo98ntkGCObDX6Y1SpkqmoTbrsb +GFsTG2DLxnvr4GdN1BSr0Uu/KV3adj47WkXVPeMYQti/bQmxQB8tRFhrw80qakTL +UzreO96WzlBBMtY= +-----END CERTIFICATE-----`)) + c, _ := x509.ParseCertificate(b.Bytes) + return c +}() + +// Example from https://github.com/crewjam/saml/blob/main/example/idp/idp.go +func main() { + apiURL := os.Getenv("API_URL") + pat := readPAT(os.Getenv("PAT_FILE")) + domain := os.Getenv("API_DOMAIN") + schema := os.Getenv("SCHEMA") + host := os.Getenv("HOST") + port := os.Getenv("PORT") + + baseURL, err := url.Parse(schema + "://" + host + ":" + port) + if err != nil { + + panic(err) + } + + idpServer, err := samlidp.New(samlidp.Options{ + URL: *baseURL, + Logger: logger.DefaultLogger, + Key: key, + Certificate: cert, + Store: &samlidp.MemoryStore{}, + }) + if err != nil { + + panic(err) + } + + metadata, err := xml.MarshalIndent(idpServer.IDP.Metadata(), "", " ") + if err != nil { + panic(err) + } + idpID, err := createZitadelResources(apiURL, pat, domain, metadata) + if err != nil { + panic(err) + } + + lis := bind.Socket(":" + baseURL.Port()) + goji.Handle("/*", idpServer) + + go func() { + goji.ServeListener(lis) + }() + + addService(idpServer, apiURL+"/idps/"+idpID+"/saml/metadata") + addUsers(idpServer) + + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + <-sigChan + + if err := lis.Close(); err != nil { + log.Fatalf("HTTP shutdown error: %v", err) + } +} + +func readPAT(path string) string { + f, err := os.Open(path) + if err != nil { + panic(err) + } + pat, err := io.ReadAll(f) + if err != nil { + panic(err) + } + return strings.Trim(string(pat), "\n") +} + +func addService(idpServer *samlidp.Server, spURLStr string) { + metadataResp, err := http.Get(spURLStr) + if err != nil { + panic(err) + } + defer metadataResp.Body.Close() + + idpServer.HandlePutService( + web.C{URLParams: map[string]string{"id": spURLStr}}, + httptest.NewRecorder(), + httptest.NewRequest(http.MethodPost, spURLStr, metadataResp.Body), + ) +} + +func getSPMetadata(r io.Reader) (spMetadata *saml.EntityDescriptor, err error) { + var data []byte + if data, err = io.ReadAll(r); err != nil { + return nil, err + } + + spMetadata = &saml.EntityDescriptor{} + if err := xrv.Validate(bytes.NewBuffer(data)); err != nil { + return nil, err + } + + if err := xml.Unmarshal(data, &spMetadata); err != nil { + if err.Error() == "expected element type but have " { + entities := &saml.EntitiesDescriptor{} + if err := xml.Unmarshal(data, &entities); err != nil { + return nil, err + } + + for _, e := range entities.EntityDescriptors { + if len(e.SPSSODescriptors) > 0 { + return &e, nil + } + } + + // there were no SPSSODescriptors in the response + return nil, errors.New("metadata contained no service provider metadata") + } + + return nil, err + } + + return spMetadata, nil +} + +func addUsers(idpServer *samlidp.Server) { + hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("hunter2"), bcrypt.DefaultCost) + err := idpServer.Store.Put("/users/alice", samlidp.User{Name: "alice", + HashedPassword: hashedPassword, + Groups: []string{"Administrators", "Users"}, + Email: "alice@example.com", + CommonName: "Alice Smith", + Surname: "Smith", + GivenName: "Alice", + }) + if err != nil { + panic(err) + } + + err = idpServer.Store.Put("/users/bob", samlidp.User{ + Name: "bob", + HashedPassword: hashedPassword, + Groups: []string{"Users"}, + Email: "bob@example.com", + CommonName: "Bob Smith", + Surname: "Smith", + GivenName: "Bob", + }) + if err != nil { + panic(err) + } +} + +func createZitadelResources(apiURL, pat, domain string, metadata []byte) (string, error) { + idpID, err := CreateIDP(apiURL, pat, domain, metadata) + if err != nil { + return "", err + } + return idpID, ActivateIDP(apiURL, pat, domain, idpID) +} + +type createIDP struct { + Name string `json:"name"` + MetadataXml string `json:"metadataXml"` + Binding string `json:"binding"` + WithSignedRequest bool `json:"withSignedRequest"` + ProviderOptions providerOptions `json:"providerOptions"` + NameIdFormat string `json:"nameIdFormat"` +} +type providerOptions struct { + IsLinkingAllowed bool `json:"isLinkingAllowed"` + IsCreationAllowed bool `json:"isCreationAllowed"` + IsAutoCreation bool `json:"isAutoCreation"` + IsAutoUpdate bool `json:"isAutoUpdate"` + AutoLinking string `json:"autoLinking"` +} + +type idp struct { + ID string `json:"id"` +} + +func CreateIDP(apiURL, pat, domain string, idpMetadata []byte) (string, error) { + encoded := make([]byte, base64.URLEncoding.EncodedLen(len(idpMetadata))) + base64.URLEncoding.Encode(encoded, idpMetadata) + + createIDP := &createIDP{ + Name: "CREWJAM", + MetadataXml: string(encoded), + Binding: "SAML_BINDING_REDIRECT", + WithSignedRequest: false, + ProviderOptions: providerOptions{ + IsLinkingAllowed: true, + IsCreationAllowed: true, + IsAutoCreation: true, + IsAutoUpdate: true, + AutoLinking: "AUTO_LINKING_OPTION_USERNAME", + }, + NameIdFormat: "SAML_NAME_ID_FORMAT_PERSISTENT", + } + + resp, err := doRequestWithHeaders(apiURL+"/admin/v1/idps/saml", pat, domain, createIDP) + if err != nil { + return "", err + } + data, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + defer resp.Body.Close() + + idp := new(idp) + if err := json.Unmarshal(data, idp); err != nil { + return "", err + } + return idp.ID, nil +} + +type activateIDP struct { + IdpId string `json:"idpId"` +} + +func ActivateIDP(apiURL, pat, domain string, idpID string) error { + activateIDP := &activateIDP{ + IdpId: idpID, + } + _, err := doRequestWithHeaders(apiURL+"/admin/v1/policies/login/idps", pat, domain, activateIDP) + return err +} + +func doRequestWithHeaders(apiURL, pat, domain string, body any) (*http.Response, error) { + data, err := json.Marshal(body) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, apiURL, io.NopCloser(bytes.NewReader(data))) + if err != nil { + return nil, err + } + values := http.Header{} + values.Add("Authorization", "Bearer "+pat) + values.Add("x-forwarded-host", domain) + values.Add("Content-Type", "application/json") + req.Header = values + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/auth/ui/v2/apps/login/acceptance/oidcrp/go.mod b/auth/ui/v2/apps/login/acceptance/oidcrp/go.mod new file mode 100644 index 0000000..a586d94 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/oidcrp/go.mod @@ -0,0 +1,25 @@ +module github.com/zitadel/typescript/acceptance/oidc + +go 1.24.1 + +require ( + github.com/google/uuid v1.6.0 + github.com/sirupsen/logrus v1.9.3 + github.com/zitadel/logging v0.6.1 + github.com/zitadel/oidc/v3 v3.36.1 +) + +require ( + github.com/go-jose/go-jose/v4 v4.1.7 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/muhlemmer/gu v0.3.1 // indirect + github.com/zitadel/schema v1.3.0 // indirect + go.opentelemetry.io/otel v1.29.0 // indirect + go.opentelemetry.io/otel/metric v1.29.0 // indirect + go.opentelemetry.io/otel/trace v1.29.0 // indirect + golang.org/x/oauth2 v0.28.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect +) diff --git a/auth/ui/v2/apps/login/acceptance/oidcrp/go.sum b/auth/ui/v2/apps/login/acceptance/oidcrp/go.sum new file mode 100644 index 0000000..a02f5bc --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/oidcrp/go.sum @@ -0,0 +1,65 @@ +github.com/bmatcuk/doublestar/v4 v4.8.1 h1:54Bopc5c2cAvhLRAzqOGCYHYyhcDHsFF4wWIR5wKP38= +github.com/bmatcuk/doublestar/v4 v4.8.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8= +github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= +github.com/go-jose/go-jose/v4 v4.1.7 h1:Nac/98uT5LPkfbiFuYa8ktf62a2VxwQ4xbq1GK8pV5E= +github.com/go-jose/go-jose/v4 v4.1.7/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= +github.com/jeremija/gosubmit v0.2.8 h1:mmSITBz9JxVtu8eqbN+zmmwX7Ij2RidQxhcwRVI4wqA= +github.com/jeremija/gosubmit v0.2.8/go.mod h1:Ui+HS073lCFREXBbdfrJzMB57OI/bdxTiLtrDHHhFPI= +github.com/muhlemmer/gu v0.3.1 h1:7EAqmFrW7n3hETvuAdmFmn4hS8W+z3LgKtrnow+YzNM= +github.com/muhlemmer/gu v0.3.1/go.mod h1:YHtHR+gxM+bKEIIs7Hmi9sPT3ZDUvTN/i88wQpZkrdM= +github.com/muhlemmer/httpforwarded v0.1.0 h1:x4DLrzXdliq8mprgUMR0olDvHGkou5BJsK/vWUetyzY= +github.com/muhlemmer/httpforwarded v0.1.0/go.mod h1:yo9czKedo2pdZhoXe+yDkGVbU0TJ0q9oQ90BVoDEtw0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= +github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/zitadel/logging v0.6.1 h1:Vyzk1rl9Kq9RCevcpX6ujUaTYFX43aa4LkvV1TvUk+Y= +github.com/zitadel/logging v0.6.1/go.mod h1:Y4CyAXHpl3Mig6JOszcV5Rqqsojj+3n7y2F591Mp/ow= +github.com/zitadel/oidc/v3 v3.36.1 h1:1AT1NqKKEqAwx4GmKJZ9fYkWH2WIn/VKMfQ46nBtRf0= +github.com/zitadel/oidc/v3 v3.36.1/go.mod h1:dApGZLvWZTHRuxmcbQlW5d2XVjVYR3vGOdq536igmTs= +github.com/zitadel/schema v1.3.0 h1:kQ9W9tvIwZICCKWcMvCEweXET1OcOyGEuFbHs4o5kg0= +github.com/zitadel/schema v1.3.0/go.mod h1:NptN6mkBDFvERUCvZHlvWmmME+gmZ44xzwRXwhzsbtc= +go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= +go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= +go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc= +go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8= +go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= +go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= +golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/auth/ui/v2/apps/login/acceptance/oidcrp/main.go b/auth/ui/v2/apps/login/acceptance/oidcrp/main.go new file mode 100644 index 0000000..72ae5f5 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/oidcrp/main.go @@ -0,0 +1,322 @@ +package main + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "log/slog" + "net/http" + "os" + "os/signal" + "strings" + "sync/atomic" + "syscall" + "time" + + "github.com/google/uuid" + "github.com/sirupsen/logrus" + + "github.com/zitadel/logging" + "github.com/zitadel/oidc/v3/pkg/client/rp" + httphelper "github.com/zitadel/oidc/v3/pkg/http" + "github.com/zitadel/oidc/v3/pkg/oidc" +) + +var ( + callbackPath = "/auth/callback" + key = []byte("test1234test1234") +) + +func main() { + apiURL := os.Getenv("API_URL") + pat := readPAT(os.Getenv("PAT_FILE")) + domain := os.Getenv("API_DOMAIN") + loginURL := os.Getenv("LOGIN_URL") + issuer := os.Getenv("ISSUER") + port := os.Getenv("PORT") + scopeList := strings.Split(os.Getenv("SCOPES"), " ") + + redirectURI := fmt.Sprintf("%s%s", issuer, callbackPath) + cookieHandler := httphelper.NewCookieHandler(key, key, httphelper.WithUnsecure()) + + clientID, clientSecret, err := createZitadelResources(apiURL, pat, domain, redirectURI, loginURL) + if err != nil { + panic(err) + } + + logger := slog.New( + slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + AddSource: true, + Level: slog.LevelDebug, + }), + ) + client := &http.Client{ + Timeout: time.Minute, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, + }, + }, + } + // enable outgoing request logging + logging.EnableHTTPClient(client, + logging.WithClientGroup("client"), + ) + + options := []rp.Option{ + rp.WithCookieHandler(cookieHandler), + rp.WithVerifierOpts(rp.WithIssuedAtOffset(5 * time.Second)), + rp.WithHTTPClient(client), + rp.WithLogger(logger), + rp.WithSigningAlgsFromDiscovery(), + rp.WithCustomDiscoveryUrl(issuer + "/.well-known/openid-configuration"), + } + if clientSecret == "" { + options = append(options, rp.WithPKCE(cookieHandler)) + } + + // One can add a logger to the context, + // pre-defining log attributes as required. + ctx := logging.ToContext(context.TODO(), logger) + provider, err := rp.NewRelyingPartyOIDC(ctx, issuer, clientID, clientSecret, redirectURI, scopeList, options...) + if err != nil { + logrus.Fatalf("error creating provider %s", err.Error()) + } + + // generate some state (representing the state of the user in your application, + // e.g. the page where he was before sending him to login + state := func() string { + return uuid.New().String() + } + + urlOptions := []rp.URLParamOpt{ + rp.WithPromptURLParam("Welcome back!"), + } + + // register the AuthURLHandler at your preferred path. + // the AuthURLHandler creates the auth request and redirects the user to the auth server. + // including state handling with secure cookie and the possibility to use PKCE. + // Prompts can optionally be set to inform the server of + // any messages that need to be prompted back to the user. + http.Handle("/login", rp.AuthURLHandler( + state, + provider, + urlOptions..., + )) + + // for demonstration purposes the returned userinfo response is written as JSON object onto response + marshalUserinfo := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[*oidc.IDTokenClaims], state string, rp rp.RelyingParty, info *oidc.UserInfo) { + fmt.Println("access token", tokens.AccessToken) + fmt.Println("refresh token", tokens.RefreshToken) + fmt.Println("id token", tokens.IDToken) + + data, err := json.Marshal(info) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("content-type", "application/json") + w.Write(data) + } + + // register the CodeExchangeHandler at the callbackPath + // the CodeExchangeHandler handles the auth response, creates the token request and calls the callback function + // with the returned tokens from the token endpoint + // in this example the callback function itself is wrapped by the UserinfoCallback which + // will call the Userinfo endpoint, check the sub and pass the info into the callback function + http.Handle(callbackPath, rp.CodeExchangeHandler(rp.UserinfoCallback(marshalUserinfo), provider)) + + // if you would use the callback without calling the userinfo endpoint, simply switch the callback handler for: + // + // http.Handle(callbackPath, rp.CodeExchangeHandler(marshalToken, provider)) + + // simple counter for request IDs + var counter atomic.Int64 + // enable incomming request logging + mw := logging.Middleware( + logging.WithLogger(logger), + logging.WithGroup("server"), + logging.WithIDFunc(func() slog.Attr { + return slog.Int64("id", counter.Add(1)) + }), + ) + + http.Handle("/healthy", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return })) + fmt.Println("/healthy returns 200 OK") + + server := &http.Server{ + Addr: ":" + port, + Handler: mw(http.DefaultServeMux), + } + go func() { + if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("HTTP server error: %v", err) + } + log.Println("Stopped serving new connections.") + }() + + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + <-sigChan + + shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownRelease() + + if err := server.Shutdown(shutdownCtx); err != nil { + log.Fatalf("HTTP shutdown error: %v", err) + } +} + +func readPAT(path string) string { + f, err := os.Open(path) + if err != nil { + panic(err) + } + pat, err := io.ReadAll(f) + if err != nil { + panic(err) + } + return strings.Trim(string(pat), "\n") +} + +func createZitadelResources(apiURL, pat, domain, redirectURI, loginURL string) (string, string, error) { + projectID, err := CreateProject(apiURL, pat, domain) + if err != nil { + return "", "", err + } + return CreateApp(apiURL, pat, domain, projectID, redirectURI, loginURL) +} + +type project struct { + ID string `json:"id"` +} +type createProject struct { + Name string `json:"name"` + ProjectRoleAssertion bool `json:"projectRoleAssertion"` + ProjectRoleCheck bool `json:"projectRoleCheck"` + HasProjectCheck bool `json:"hasProjectCheck"` + PrivateLabelingSetting string `json:"privateLabelingSetting"` +} + +func CreateProject(apiURL, pat, domain string) (string, error) { + createProject := &createProject{ + Name: "OIDC", + ProjectRoleAssertion: false, + ProjectRoleCheck: false, + HasProjectCheck: false, + PrivateLabelingSetting: "PRIVATE_LABELING_SETTING_UNSPECIFIED", + } + resp, err := doRequestWithHeaders(apiURL+"/management/v1/projects", pat, domain, createProject) + if err != nil { + return "", err + } + data, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + defer resp.Body.Close() + + p := new(project) + if err := json.Unmarshal(data, p); err != nil { + return "", err + } + fmt.Printf("projectID: %+v\n", p.ID) + return p.ID, nil +} + +type createApp struct { + Name string `json:"name"` + RedirectUris []string `json:"redirectUris"` + ResponseTypes []string `json:"responseTypes"` + GrantTypes []string `json:"grantTypes"` + AppType string `json:"appType"` + AuthMethodType string `json:"authMethodType"` + PostLogoutRedirectUris []string `json:"postLogoutRedirectUris"` + Version string `json:"version"` + DevMode bool `json:"devMode"` + AccessTokenType string `json:"accessTokenType"` + AccessTokenRoleAssertion bool `json:"accessTokenRoleAssertion"` + IdTokenRoleAssertion bool `json:"idTokenRoleAssertion"` + IdTokenUserinfoAssertion bool `json:"idTokenUserinfoAssertion"` + ClockSkew string `json:"clockSkew"` + AdditionalOrigins []string `json:"additionalOrigins"` + SkipNativeAppSuccessPage bool `json:"skipNativeAppSuccessPage"` + BackChannelLogoutUri []string `json:"backChannelLogoutUri"` + LoginVersion version `json:"loginVersion"` +} + +type version struct { + LoginV2 loginV2 `json:"loginV2"` +} +type loginV2 struct { + BaseUri string `json:"baseUri"` +} + +type app struct { + ClientID string `json:"clientId"` + ClientSecret string `json:"clientSecret"` +} + +func CreateApp(apiURL, pat, domain, projectID string, redirectURI, loginURL string) (string, string, error) { + createApp := &createApp{ + Name: "OIDC", + RedirectUris: []string{redirectURI}, + ResponseTypes: []string{"OIDC_RESPONSE_TYPE_CODE"}, + GrantTypes: []string{"OIDC_GRANT_TYPE_AUTHORIZATION_CODE"}, + AppType: "OIDC_APP_TYPE_WEB", + AuthMethodType: "OIDC_AUTH_METHOD_TYPE_BASIC", + Version: "OIDC_VERSION_1_0", + DevMode: true, + AccessTokenType: "OIDC_TOKEN_TYPE_BEARER", + AccessTokenRoleAssertion: true, + IdTokenRoleAssertion: true, + IdTokenUserinfoAssertion: true, + ClockSkew: "1s", + SkipNativeAppSuccessPage: true, + LoginVersion: version{ + LoginV2: loginV2{ + BaseUri: loginURL, + }, + }, + } + + resp, err := doRequestWithHeaders(apiURL+"/management/v1/projects/"+projectID+"/apps/oidc", pat, domain, createApp) + data, err := io.ReadAll(resp.Body) + if err != nil { + return "", "", err + } + defer resp.Body.Close() + + a := new(app) + if err := json.Unmarshal(data, a); err != nil { + return "", "", err + } + return a.ClientID, a.ClientSecret, err +} + +func doRequestWithHeaders(apiURL, pat, domain string, body any) (*http.Response, error) { + data, err := json.Marshal(body) + if err != nil { + return nil, err + } + req, err := http.NewRequest(http.MethodPost, apiURL, io.NopCloser(bytes.NewReader(data))) + if err != nil { + return nil, err + } + values := http.Header{} + values.Add("Authorization", "Bearer "+pat) + values.Add("x-forwarded-host", domain) + values.Add("Content-Type", "application/json") + req.Header = values + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/auth/ui/v2/apps/login/acceptance/pat/.gitignore b/auth/ui/v2/apps/login/acceptance/pat/.gitignore new file mode 100644 index 0000000..bf27f31 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/pat/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!.gitkeep diff --git a/auth/ui/v2/apps/login/acceptance/pat/.gitkeep b/auth/ui/v2/apps/login/acceptance/pat/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/auth/ui/v2/apps/login/acceptance/playwright-report/.gitignore b/auth/ui/v2/apps/login/acceptance/playwright-report/.gitignore new file mode 100644 index 0000000..bf27f31 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/playwright-report/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!.gitkeep diff --git a/auth/ui/v2/apps/login/acceptance/playwright-report/.gitkeep b/auth/ui/v2/apps/login/acceptance/playwright-report/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/auth/ui/v2/apps/login/acceptance/playwright.config.ts b/auth/ui/v2/apps/login/acceptance/playwright.config.ts new file mode 100644 index 0000000..8025db3 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/playwright.config.ts @@ -0,0 +1,78 @@ +import { defineConfig, devices } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; + +dotenv.config({ path: path.resolve(__dirname, "../login/.env.test.local") }); + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: "./tests", + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + expect: { + timeout: 10_000, // 10 seconds + }, + timeout: 300 * 1000, // 5 minutes + globalTimeout: 30 * 60_000, // 30 minutes + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: [ + ["line"], + ["html", { open: process.env.CI ? "never" : "on-failure", host: "0.0.0.0", outputFolder: "./playwright-report/html" }], + ], + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL: process.env.LOGIN_BASE_URL || "http://127.0.0.1:3000", + trace: "retain-on-failure", + headless: true, + screenshot: "only-on-failure", + video: "retain-on-failure", + ignoreHTTPSErrors: true, + }, + outputDir: "test-results/results", + + /* Configure projects for major browsers */ + projects: [ + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + }, + /* + { + name: "firefox", + use: { ...devices["Desktop Firefox"] }, + }, + TODO: webkit fails. Is this a bug? + { + name: 'webkit', + use: { ...devices['Desktop Safari'] }, + }, + */ + + /* Test against mobile viewports. */ + // { + // name: 'Mobile Chrome', + // use: { ...devices['Pixel 5'] }, + // }, + // { + // name: 'Mobile Safari', + // use: { ...devices['iPhone 12'] }, + // }, + + /* Test against branded browsers. */ + // { + // name: 'Microsoft Edge', + // use: { ...devices['Desktop Edge'], channel: 'msedge' }, + // }, + // { + // name: 'Google Chrome', + // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, + // }, + ], +}); diff --git a/auth/ui/v2/apps/login/acceptance/samlsp/go.mod b/auth/ui/v2/apps/login/acceptance/samlsp/go.mod new file mode 100644 index 0000000..de4bfea --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/samlsp/go.mod @@ -0,0 +1,18 @@ +module github.com/zitadel/typescript/acceptance/saml + +go 1.25.0 + +require github.com/crewjam/saml v0.4.14 + +require ( + github.com/beevik/etree v1.5.0 // indirect + github.com/crewjam/httperr v0.2.0 // indirect + github.com/golang-jwt/jwt/v4 v4.5.2 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/jonboulle/clockwork v0.5.0 // indirect + github.com/mattermost/xml-roundtrip-validator v0.1.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/russellhaering/goxmldsig v1.5.0 // indirect + github.com/stretchr/testify v1.10.0 // indirect + golang.org/x/crypto v0.52.0 // indirect +) diff --git a/auth/ui/v2/apps/login/acceptance/samlsp/go.sum b/auth/ui/v2/apps/login/acceptance/samlsp/go.sum new file mode 100644 index 0000000..0a13cdd --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/samlsp/go.sum @@ -0,0 +1,38 @@ +github.com/beevik/etree v1.5.0 h1:iaQZFSDS+3kYZiGoc9uKeOkUY3nYMXOKLl6KIJxiJWs= +github.com/beevik/etree v1.5.0/go.mod h1:gPNJNaBGVZ9AwsidazFZyygnd+0pAU38N4D+WemwKNs= +github.com/crewjam/httperr v0.2.0 h1:b2BfXR8U3AlIHwNeFFvZ+BV1LFvKLlzMjzaTnZMybNo= +github.com/crewjam/httperr v0.2.0/go.mod h1:Jlz+Sg/XqBQhyMjdDiC+GNNRzZTD7x39Gu3pglZ5oH4= +github.com/crewjam/saml v0.4.14 h1:g9FBNx62osKusnFzs3QTN5L9CVA/Egfgm+stJShzw/c= +github.com/crewjam/saml v0.4.14/go.mod h1:UVSZCf18jJkk6GpWNVqcyQJMD5HsRugBPf4I1nl2mME= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= +github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= +github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= +github.com/mattermost/xml-roundtrip-validator v0.1.0 h1:RXbVD2UAl7A7nOTR4u7E3ILa4IbtvKBHw64LDsmu9hU= +github.com/mattermost/xml-roundtrip-validator v0.1.0/go.mod h1:qccnGMcpgwcNaBnxqpJpWWUiPNr5H3O8eDgGV9gT5To= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russellhaering/goxmldsig v1.5.0 h1:AU2UkkYIUOTyZRbe08XMThaOCelArgvNfYapcmSjBNw= +github.com/russellhaering/goxmldsig v1.5.0/go.mod h1:x98CjQNFJcWfMxeOrMnMKg70lvDP6tE0nTaeUnjXDmk= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= diff --git a/auth/ui/v2/apps/login/acceptance/samlsp/main.go b/auth/ui/v2/apps/login/acceptance/samlsp/main.go new file mode 100644 index 0000000..9dcfd13 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/samlsp/main.go @@ -0,0 +1,271 @@ +package main + +import ( + "bytes" + "context" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/crewjam/saml/samlsp" +) + +var keyPair = func() tls.Certificate { + cert := []byte(`-----BEGIN CERTIFICATE----- +MIIDITCCAgmgAwIBAgIUKjAUmxsHO44X+/TKBNciPgNl1GEwDQYJKoZIhvcNAQEL +BQAwIDEeMBwGA1UEAwwVbXlzZXJ2aWNlLmV4YW1wbGUuY29tMB4XDTI0MTIxOTEz +Mzc1MVoXDTI1MTIxOTEzMzc1MVowIDEeMBwGA1UEAwwVbXlzZXJ2aWNlLmV4YW1w +bGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0QYuJsayILRI +hVT7G1DlitVSXnt1iw3gEXJZfe81Egz06fUbvXF6Yo1LJmwYpqe/rm+hf4FNUb8e +2O+LH2FieA9FkVe4P2gKOzw87A/KxvpV8stgNgl4LlqRCokbc1AzeE/NiLr5TcTD +RXm3DUcYxXxinprtDu2jftFysaOZmNAukvE/iL6qS3X6ggVEDDM7tY9n5FV2eJ4E +p0ImKfypi2aZYROxOK+v5x9ryFRMl4y07lMDvmtcV45uXYmfGNCgG9PNf91Kk/mh +JxEQbxycJwFoSi9XWljR8ahPdO11LXG7Dsj/RVbY8k2LdKNstl6Ae3aCpbe9u2Pj +vxYs1bVJuQIDAQABo1MwUTAdBgNVHQ4EFgQU+mRVN5HYJWgnpopReaLhf2cMcoYw +HwYDVR0jBBgwFoAU+mRVN5HYJWgnpopReaLhf2cMcoYwDwYDVR0TAQH/BAUwAwEB +/zANBgkqhkiG9w0BAQsFAAOCAQEABJpHVuc9tGhD04infRVlofvqXIUizTlOrjZX +vozW9pIhSWEHX8o+sJP8AMZLnrsdq+bm0HE0HvgYrw7Lb8pd4FpR46TkFHjeukoj +izqfgckjIBl2nwPGlynbKA0/U/rTCSxVt7XiAn+lgYUGIpOzNdk06/hRMitrMNB7 +t2C97NseVC4b1ZgyFrozsefCfUmD8IJF0+XJ4Wzmsh0jRrI8koCtVmPYnKn6vw1b +cZprg/97CWHYrsavd406wOB60CMtYl83Q16ucOF1dretDFqJC5kY+aFLvuqfag2+ +kIaoPV1MnGsxveQyyHdOsEatS5XOv/1OWcmnvePDPxcvb9jCcw== +-----END CERTIFICATE----- +`) + key := []byte(`-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDRBi4mxrIgtEiF +VPsbUOWK1VJee3WLDeARcll97zUSDPTp9Ru9cXpijUsmbBimp7+ub6F/gU1Rvx7Y +74sfYWJ4D0WRV7g/aAo7PDzsD8rG+lXyy2A2CXguWpEKiRtzUDN4T82IuvlNxMNF +ebcNRxjFfGKemu0O7aN+0XKxo5mY0C6S8T+IvqpLdfqCBUQMMzu1j2fkVXZ4ngSn +QiYp/KmLZplhE7E4r6/nH2vIVEyXjLTuUwO+a1xXjm5diZ8Y0KAb081/3UqT+aEn +ERBvHJwnAWhKL1daWNHxqE907XUtcbsOyP9FVtjyTYt0o2y2XoB7doKlt727Y+O/ +FizVtUm5AgMBAAECggEACak+l5f6Onj+u5vrjc4JyAaXW6ra6loSM9g8Uu3sHukW +plwoA7Pzp0u20CAxrP1Gpqw984/hSCCcb0Q2ItWMWLaC/YZni5W2WFnOyo3pzlPa +hmH4UNMT+ReCSfF/oW8w69QLcNEMjhfEu0i2iWBygIlA4SoRwC2Db6yEX7nLMwUB +6AICid9hfeACNRz/nq5ytdcHdmcB7Ptgb9jLiXr6RZw26g5AsRPHU3LdcyZAOXjP +aUHriHuHQFKAVkoEUxslvCB6ePCTCpB0bSAuzQbeGoY8fmvmNSCvJ1vrH5hiSUYp +Axtl5iNgFl5o9obb0eBYlY9x3pMSz0twdbCwfR7HAQKBgQDtWhmFm0NaJALoY+tq +lIIC0EOMSrcRIlgeXr6+g8womuDOMi5m/Nr5Mqt4mPOdP4HytrQb+a/ZmEm17KHh +mQb1vwH8ffirCBHbPNC1vwSNoxDKv9E6OysWlKiOzxPFSVZr3dKl2EMX6qi17n0l +LBrGXXaNPgYiHSmwBA5CZvvouQKBgQDhclGJfZfuoubQkUuz8yOA2uxalh/iUmQ/ +G8ac6/w7dmnL9pXehqCWh06SeC3ZvW7yrf7IIGx4sTJji2FzQ+8Ta6pPELMyBEXr +1VirIFrlNVMlMQEbZcbzdzEhchM1RUpZJtl3b4amvH21UcRB69d9klcDRisKoFRm +k0P9QLHpAQKBgQDh5J9nphZa4u0ViYtTW1XFIbs3+R/0IbCl7tww67TRbF3KQL4i +7EHna88ALumkXf3qJvKRsXgoaqS0jSqgUAjst8ZHLQkOldaQxneIkezedDSWEisp +9YgTrJYjnHefiyXB8VL63jE0wPOiewEF8Mzmv6sFz+L8cq7rQ2Di16qmmQKBgQDH +bvCwVxkrMpJK2O2GH8U9fOzu6bUE6eviY/jb4mp8U7EdjGJhuuieoM2iBoxQ/SID +rmYftYcfcWlo4+juJZ99p5W+YcCTs3IDQPUyVOnzr6uA0Avxp6RKxhsBQj+5tTUj +Dpn77P3JzB7MYqvhwPcdD3LH46+5s8FWCFpx02RPAQKBgARbngtggfifatcsMC7n +lSv/FVLH7LYQAHdoW/EH5Be7FeeP+eQvGXwh1dgl+u0VZO8FvI8RwFganpBRR2Nc +ZSBRIb0fSUlTvIsckSWjpEvUJUomJXyi4PIZAfNvd9/u1uLInQiCDtObwb6hnLTU +FHHEZ+dR4eMaJp6PhNm8hu2O +-----END PRIVATE KEY----- +`) + + kp, err := tls.X509KeyPair(cert, key) + if err != nil { + panic(err) + } + kp.Leaf, err = x509.ParseCertificate(kp.Certificate[0]) + if err != nil { + panic(err) + } + return kp +}() + +func hello(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Hello, %s!", samlsp.AttributeFromContext(r.Context(), "UserName")) +} + +func main() { + apiURL := os.Getenv("API_URL") + pat := readPAT(os.Getenv("PAT_FILE")) + domain := os.Getenv("API_DOMAIN") + loginURL := os.Getenv("LOGIN_URL") + idpURL := os.Getenv("IDP_URL") + host := os.Getenv("HOST") + port := os.Getenv("PORT") + + idpMetadataURL, err := url.Parse(idpURL) + if err != nil { + panic(err) + } + idpMetadata, err := samlsp.FetchMetadata(context.Background(), http.DefaultClient, + *idpMetadataURL) + if err != nil { + panic(fmt.Errorf("failed to fetch IDP metadata from %s: %w", idpURL, err)) + } + fmt.Printf("idpMetadata: %+v\n", idpMetadata) + rootURL, err := url.Parse(host + ":" + port) + if err != nil { + panic(err) + } + + samlSP, err := samlsp.New(samlsp.Options{ + URL: *rootURL, + Key: keyPair.PrivateKey.(*rsa.PrivateKey), + Certificate: keyPair.Leaf, + IDPMetadata: idpMetadata, + }) + if err != nil { + panic(err) + } + + server := &http.Server{ + Addr: ":" + port, + } + app := http.HandlerFunc(hello) + http.Handle("/hello", samlSP.RequireAccount(app)) + http.Handle("/saml/", samlSP) + go func() { + if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("HTTP server error: %v", err) + } + log.Println("Stopped serving new connections.") + }() + + metadata, err := xml.MarshalIndent(samlSP.ServiceProvider.Metadata(), "", " ") + if err != nil { + panic(err) + } + if err := createZitadelResources(apiURL, pat, domain, metadata, loginURL); err != nil { + panic(err) + } + + http.Handle("/healthy", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return })) + fmt.Println("/healthy returns 200 OK") + + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + <-sigChan + + shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownRelease() + + if err := server.Shutdown(shutdownCtx); err != nil { + log.Fatalf("HTTP shutdown error: %v", err) + } +} + +func readPAT(path string) string { + f, err := os.Open(path) + if err != nil { + panic(err) + } + pat, err := io.ReadAll(f) + if err != nil { + panic(err) + } + return strings.Trim(string(pat), "\n") +} + +func createZitadelResources(apiURL, pat, domain string, metadata []byte, loginURL string) error { + projectID, err := CreateProject(apiURL, pat, domain) + if err != nil { + return err + } + return CreateApp(apiURL, pat, domain, projectID, metadata, loginURL) +} + +type project struct { + ID string `json:"id"` +} +type createProject struct { + Name string `json:"name"` + ProjectRoleAssertion bool `json:"projectRoleAssertion"` + ProjectRoleCheck bool `json:"projectRoleCheck"` + HasProjectCheck bool `json:"hasProjectCheck"` + PrivateLabelingSetting string `json:"privateLabelingSetting"` +} + +func CreateProject(apiURL, pat, domain string) (string, error) { + createProject := &createProject{ + Name: "SAML", + ProjectRoleAssertion: false, + ProjectRoleCheck: false, + HasProjectCheck: false, + PrivateLabelingSetting: "PRIVATE_LABELING_SETTING_UNSPECIFIED", + } + resp, err := doRequestWithHeaders(apiURL+"/management/v1/projects", pat, domain, createProject) + if err != nil { + return "", err + } + data, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + defer resp.Body.Close() + + p := new(project) + if err := json.Unmarshal(data, p); err != nil { + return "", err + } + return p.ID, nil +} + +type createApp struct { + Name string `json:"name"` + MetadataXml string `json:"metadataXml"` + LoginVersion version `json:"loginVersion"` +} +type version struct { + LoginV2 loginV2 `json:"loginV2"` +} +type loginV2 struct { + BaseUri string `json:"baseUri"` +} + +func CreateApp(apiURL, pat, domain, projectID string, spMetadata []byte, loginURL string) error { + encoded := make([]byte, base64.URLEncoding.EncodedLen(len(spMetadata))) + base64.URLEncoding.Encode(encoded, spMetadata) + + createApp := &createApp{ + Name: "SAML", + MetadataXml: string(encoded), + LoginVersion: version{ + LoginV2: loginV2{ + BaseUri: loginURL, + }, + }, + } + _, err := doRequestWithHeaders(apiURL+"/management/v1/projects/"+projectID+"/apps/saml", pat, domain, createApp) + if err != nil { + return fmt.Errorf("error creating saml app with request %+v: %v", *createApp, err) + } + return err +} + +func doRequestWithHeaders(apiURL, pat, domain string, body any) (*http.Response, error) { + data, err := json.Marshal(body) + if err != nil { + return nil, err + } + req, err := http.NewRequest(http.MethodPost, apiURL, io.NopCloser(bytes.NewReader(data))) + if err != nil { + return nil, err + } + values := http.Header{} + values.Add("Authorization", "Bearer "+pat) + values.Add("x-forwarded-host", domain) + values.Add("Content-Type", "application/json") + req.Header = values + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/auth/ui/v2/apps/login/acceptance/setup/go.mod b/auth/ui/v2/apps/login/acceptance/setup/go.mod new file mode 100644 index 0000000..7be166e --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/setup/go.mod @@ -0,0 +1,3 @@ +module github.com/zitadel/typescript/apps/login-test-acceptance/setup + +go 1.23.3 diff --git a/auth/ui/v2/apps/login/acceptance/setup/go.sum b/auth/ui/v2/apps/login/acceptance/setup/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/auth/ui/v2/apps/login/acceptance/setup/main.go b/auth/ui/v2/apps/login/acceptance/setup/main.go new file mode 100644 index 0000000..38dd16d --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/setup/main.go @@ -0,0 +1,3 @@ +package main + +func main() {} diff --git a/auth/ui/v2/apps/login/acceptance/setup/setup.sh b/auth/ui/v2/apps/login/acceptance/setup/setup.sh new file mode 100644 index 0000000..9d1a04e --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/setup/setup.sh @@ -0,0 +1,139 @@ +#!/bin/sh + +set -e pipefail + +PAT_FILE=${PAT_FILE:-./pat/zitadel-admin-sa.pat} +LOGIN_BASE_URL=${LOGIN_BASE_URL:-"http://localhost:3000"} +ZITADEL_API_PROTOCOL="${ZITADEL_API_PROTOCOL:-http}" +ZITADEL_API_DOMAIN="${ZITADEL_API_DOMAIN:-localhost}" +ZITADEL_API_PORT="${ZITADEL_API_PORT:-8080}" +ZITADEL_API_URL="${ZITADEL_API_URL:-${ZITADEL_API_PROTOCOL}://${ZITADEL_API_DOMAIN}:${ZITADEL_API_PORT}}" +ZITADEL_API_INTERNAL_URL="${ZITADEL_API_INTERNAL_URL:-${ZITADEL_API_URL}}" +SINK_EMAIL_INTERNAL_URL="${SINK_EMAIL_INTERNAL_URL:-"http://sink:3333/email"}" +SINK_SMS_INTERNAL_URL="${SINK_SMS_INTERNAL_URL:-"http://sink:3333/sms"}" +SINK_NOTIFICATION_URL="${SINK_NOTIFICATION_URL:-"http://localhost:3333/notification"}" +WRITE_ENVIRONMENT_FILE=${WRITE_ENVIRONMENT_FILE:-$(dirname "$0")/../apps/login/.env.test.local} + +if [ -z "${PAT}" ]; then + echo "Reading PAT from file ${PAT_FILE}" + PAT=$(cat ${PAT_FILE}) +fi + +################################################################# +# ServiceAccount as Login Client +################################################################# + +SERVICEACCOUNT_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/management/v1/users/machine" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json" \ + -d "{\"userName\": \"login\", \"name\": \"Login v2\", \"description\": \"Serviceaccount for Login v2\", \"accessTokenType\": \"ACCESS_TOKEN_TYPE_BEARER\"}") +echo "Received ServiceAccount response: ${SERVICEACCOUNT_RESPONSE}" + +SERVICEACCOUNT_ID=$(echo ${SERVICEACCOUNT_RESPONSE} | jq -r '. | .userId') +echo "Received ServiceAccount ID: ${SERVICEACCOUNT_ID}" + +MEMBER_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/admin/v1/members" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json" \ + -d "{\"userId\": \"${SERVICEACCOUNT_ID}\", \"roles\": [\"IAM_LOGIN_CLIENT\"]}") +echo "Received Member response: ${MEMBER_RESPONSE}" + +SA_PAT_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/management/v1/users/${SERVICEACCOUNT_ID}/pats" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json" \ + -d "{\"expirationDate\": \"2519-04-01T08:45:00.000000Z\"}") +echo "Received Member response: ${MEMBER_RESPONSE}" + +SA_PAT=$(echo ${SA_PAT_RESPONSE} | jq -r '. | .token') +echo "Received ServiceAccount Token: ${SA_PAT}" + +################################################################# +# Environment files +################################################################# + +echo "Writing environment file ${WRITE_ENVIRONMENT_FILE}." + +echo "ZITADEL_API_URL=${ZITADEL_API_URL} +ZITADEL_SERVICE_USER_TOKEN=${SA_PAT} +ZITADEL_ADMIN_TOKEN=${PAT} +SINK_NOTIFICATION_URL=${SINK_NOTIFICATION_URL} +EMAIL_VERIFICATION=true +DEBUG=false +LOGIN_BASE_URL=${LOGIN_BASE_URL} +NODE_TLS_REJECT_UNAUTHORIZED=0 +ZITADEL_ADMIN_USER=${ZITADEL_ADMIN_USER:-"zitadel-admin@zitadel.localhost"} +NEXT_PUBLIC_BASE_PATH=/ui/v2/login +" > ${WRITE_ENVIRONMENT_FILE} + +echo "Wrote environment file ${WRITE_ENVIRONMENT_FILE}" +cat ${WRITE_ENVIRONMENT_FILE} + +################################################################# +# SMS provider with HTTP +################################################################# + +SMSHTTP_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/admin/v1/sms/http" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json" \ + -d "{\"endpoint\": \"${SINK_SMS_INTERNAL_URL}\", \"description\": \"test\"}") +echo "Received SMS HTTP response: ${SMSHTTP_RESPONSE}" + +SMSHTTP_ID=$(echo ${SMSHTTP_RESPONSE} | jq -r '. | .id') +echo "Received SMS HTTP ID: ${SMSHTTP_ID}" + +SMS_ACTIVE_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/admin/v1/sms/${SMSHTTP_ID}/_activate" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json") +echo "Received SMS active response: ${SMS_ACTIVE_RESPONSE}" + +################################################################# +# Email provider with HTTP +################################################################# + +EMAILHTTP_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/admin/v1/email/http" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json" \ + -d "{\"endpoint\": \"${SINK_EMAIL_INTERNAL_URL}\", \"description\": \"test\"}") +echo "Received Email HTTP response: ${EMAILHTTP_RESPONSE}" + +EMAILHTTP_ID=$(echo ${EMAILHTTP_RESPONSE} | jq -r '. | .id') +echo "Received Email HTTP ID: ${EMAILHTTP_ID}" + +EMAIL_ACTIVE_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/admin/v1/email/${EMAILHTTP_ID}/_activate" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json") +echo "Received Email active response: ${EMAIL_ACTIVE_RESPONSE}" + +################################################################# +# Wait for projection of default organization in ZITADEL +################################################################# + +DEFAULTORG_RESPONSE_RESULTS=0 +# waiting for default organization +until [ ${DEFAULTORG_RESPONSE_RESULTS} -eq 1 ] +do + DEFAULTORG_RESPONSE=$(curl -s --request POST \ + --url "${ZITADEL_API_INTERNAL_URL}/v2/organizations/_search" \ + --header "Authorization: Bearer ${PAT}" \ + --header "Host: ${ZITADEL_API_DOMAIN}" \ + --header "Content-Type: application/json" \ + -d "{\"queries\": [{\"defaultQuery\":{}}]}" ) + echo "Received default organization response: ${DEFAULTORG_RESPONSE}" + DEFAULTORG_RESPONSE_RESULTS=$(echo $DEFAULTORG_RESPONSE | jq -r '.result | length') + echo "Received default organization response result: ${DEFAULTORG_RESPONSE_RESULTS}" +done + diff --git a/auth/ui/v2/apps/login/acceptance/sink/go.mod b/auth/ui/v2/apps/login/acceptance/sink/go.mod new file mode 100644 index 0000000..1da7622 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/sink/go.mod @@ -0,0 +1,3 @@ +module github.com/zitadel/typescript/acceptance/sink + +go 1.24.0 diff --git a/auth/ui/v2/apps/login/acceptance/sink/go.sum b/auth/ui/v2/apps/login/acceptance/sink/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/auth/ui/v2/apps/login/acceptance/sink/main.go b/auth/ui/v2/apps/login/acceptance/sink/main.go new file mode 100644 index 0000000..f3795ba --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/sink/main.go @@ -0,0 +1,111 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "io" + "net/http" +) + +type serializableData struct { + ContextInfo map[string]interface{} `json:"contextInfo,omitempty"` + Args map[string]interface{} `json:"args,omitempty"` +} + +type response struct { + Recipient string `json:"recipient,omitempty"` +} + +func main() { + port := flag.String("port", "3333", "used port for the sink") + email := flag.String("email", "/email", "path for a sent email") + emailKey := flag.String("email-key", "recipientEmailAddress", "value in the sent context info of the email used as key to retrieve the notification") + sms := flag.String("sms", "/sms", "path for a sent sms") + smsKey := flag.String("sms-key", "recipientPhoneNumber", "value in the sent context info of the sms used as key to retrieve the notification") + notification := flag.String("notification", "/notification", "path to receive the notification") + flag.Parse() + + messages := make(map[string]serializableData) + + http.HandleFunc(*email, func(w http.ResponseWriter, r *http.Request) { + data, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + serializableData := serializableData{} + if err := json.Unmarshal(data, &serializableData); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + email, ok := serializableData.ContextInfo[*emailKey].(string) + if !ok { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + fmt.Println(email + ": " + string(data)) + messages[email] = serializableData + io.WriteString(w, "Email!\n") + }) + + http.HandleFunc(*sms, func(w http.ResponseWriter, r *http.Request) { + data, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + serializableData := serializableData{} + if err := json.Unmarshal(data, &serializableData); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + phone, ok := serializableData.ContextInfo[*smsKey].(string) + if !ok { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + fmt.Println(phone + ": " + string(data)) + messages[phone] = serializableData + io.WriteString(w, "SMS!\n") + }) + + http.HandleFunc(*notification, func(w http.ResponseWriter, r *http.Request) { + data, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + response := response{} + if err := json.Unmarshal(data, &response); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + msg, ok := messages[response.Recipient] + if !ok { + http.Error(w, "No messages found for recipient: "+response.Recipient, http.StatusNotFound) + return + } + serializableData, err := json.Marshal(msg) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, string(serializableData)) + }) + + fmt.Println("Starting server on", *port) + fmt.Println(*email, " for email handling") + fmt.Println(*sms, " for sms handling") + fmt.Println(*notification, " for retrieving notifications") + http.Handle("/healthy", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return })) + fmt.Println("/healthy returns 200 OK") + err := http.ListenAndServe(":"+*port, nil) + if err != nil { + panic("Server could not be started: " + err.Error()) + } +} diff --git a/auth/ui/v2/apps/login/acceptance/test-results/.gitignore b/auth/ui/v2/apps/login/acceptance/test-results/.gitignore new file mode 100644 index 0000000..bf27f31 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/test-results/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!.gitkeep diff --git a/auth/ui/v2/apps/login/acceptance/test-results/.gitkeep b/auth/ui/v2/apps/login/acceptance/test-results/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/auth/ui/v2/apps/login/acceptance/tests/admin.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/admin.spec.ts new file mode 100644 index 0000000..13b748f --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/admin.spec.ts @@ -0,0 +1,7 @@ +import { test } from "@playwright/test"; +import { loginScreenExpect, loginWithPassword } from "./login"; + +test("admin login", async ({ page }) => { + await loginWithPassword(page, process.env["ZITADEL_ADMIN_USER"], "Password1!"); + await loginScreenExpect(page, "ZITADEL Admin"); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/code-screen.ts b/auth/ui/v2/apps/login/acceptance/tests/code-screen.ts new file mode 100644 index 0000000..1889d3c --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/code-screen.ts @@ -0,0 +1,13 @@ +import { expect, Page } from "@playwright/test"; +import en from "../../locales/en.json"; + +const codeTextInput = "code-text-input"; + +export async function codeScreen(page: Page, code: string) { + await page.getByTestId(codeTextInput).pressSequentially(code); +} + +export async function codeScreenExpect(page: Page, code: string) { + await expect(page.getByTestId(codeTextInput)).toHaveValue(code); + await expect(page.getByTestId("error").locator("div")).toContainText(en.otp.errors.couldNotVerifyCode); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/code.ts b/auth/ui/v2/apps/login/acceptance/tests/code.ts new file mode 100644 index 0000000..e27d1f6 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/code.ts @@ -0,0 +1,17 @@ +import { Page } from "@playwright/test"; +import { codeScreen } from "./code-screen"; +import { getOtpFromSink } from "./sink"; + +export async function otpFromSink(page: Page, key: string) { + const c = await getOtpFromSink(key); + await code(page, c); +} + +export async function code(page: Page, code: string) { + await codeScreen(page, code); + await page.getByTestId("submit-button").click(); +} + +export async function codeResend(page: Page) { + await page.getByTestId("resend-button").click(); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/email-verify-screen.ts b/auth/ui/v2/apps/login/acceptance/tests/email-verify-screen.ts new file mode 100644 index 0000000..b077ecb --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/email-verify-screen.ts @@ -0,0 +1,12 @@ +import { expect, Page } from "@playwright/test"; + +const codeTextInput = "code-text-input"; + +export async function emailVerifyScreen(page: Page, code: string) { + await page.getByTestId(codeTextInput).pressSequentially(code); +} + +export async function emailVerifyScreenExpect(page: Page, code: string) { + await expect(page.getByTestId(codeTextInput)).toHaveValue(code); + await expect(page.getByTestId("error").locator("div")).toContainText("Could not verify email"); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/email-verify.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/email-verify.spec.ts new file mode 100644 index 0000000..2c546b8 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/email-verify.spec.ts @@ -0,0 +1,69 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { emailVerify, emailVerifyResend } from "./email-verify"; +import { emailVerifyScreenExpect } from "./email-verify-screen"; +import { loginScreenExpect, loginWithPassword } from "./login"; +import { getCodeFromSink } from "./sink"; +import { PasswordUser } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUser }>({ + user: async ({ page }, use) => { + const user = new PasswordUser({ + email: faker.internet.email(), + isEmailVerified: false, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + password: "Password1!", + passwordChangeRequired: false, + }); + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("user email not verified, verify", async ({ user, page }) => { + await loginWithPassword(page, user.getUsername(), user.getPassword()); + const c = await getCodeFromSink(user.getUsername()); + await emailVerify(page, c); + // wait for resend of the code + await page.waitForTimeout(2000); + await loginScreenExpect(page, user.getFullName()); +}); + +test("user email not verified, resend, verify", async ({ user, page }) => { + await loginWithPassword(page, user.getUsername(), user.getPassword()); + // auto-redirect on /verify + await emailVerifyResend(page); + const c = await getCodeFromSink(user.getUsername()); + // wait for resend of the code + await page.waitForTimeout(2000); + await emailVerify(page, c); + await loginScreenExpect(page, user.getFullName()); +}); + +test("user email not verified, resend, old code", async ({ user, page }) => { + await loginWithPassword(page, user.getUsername(), user.getPassword()); + const c = await getCodeFromSink(user.getUsername()); + await emailVerifyResend(page); + // wait for resend of the code + await page.waitForTimeout(2000); + await emailVerify(page, c); + await emailVerifyScreenExpect(page, c); +}); + +test("user email not verified, wrong code", async ({ user, page }) => { + await loginWithPassword(page, user.getUsername(), user.getPassword()); + // auto-redirect on /verify + const code = "wrong"; + await emailVerify(page, code); + await emailVerifyScreenExpect(page, code); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/email-verify.ts b/auth/ui/v2/apps/login/acceptance/tests/email-verify.ts new file mode 100644 index 0000000..5275e82 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/email-verify.ts @@ -0,0 +1,15 @@ +import { Page } from "@playwright/test"; +import { emailVerifyScreen } from "./email-verify-screen"; + +export async function startEmailVerify(page: Page, loginname: string) { + await page.goto("./verify"); +} + +export async function emailVerify(page: Page, code: string) { + await emailVerifyScreen(page, code); + await page.getByTestId("submit-button").click(); +} + +export async function emailVerifyResend(page: Page) { + await page.getByTestId("resend-button").click(); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-apple.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-apple.spec.ts new file mode 100644 index 0000000..32d3adb --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-apple.spec.ts @@ -0,0 +1,102 @@ +// Note for all tests, in case Apple doesn't deliver all relevant information per default +// We should add an action in the needed cases + +import test from "@playwright/test"; + +test("login with Apple IDP", async ({ page }) => { + test.skip(); + // Given an Apple IDP is configured on the organization + // Given the user has an Apple added as auth method + // User authenticates with Apple + // User is redirected back to login + // User is redirected to the app +}); + +test("login with Apple IDP - error", async ({ page }) => { + test.skip(); + // Given an Apple IDP is configured on the organization + // Given the user has an Apple added as auth method + // User is redirected to Apple + // User authenticates with Apple and gets an error + // User is redirect back to login + // An error is shown to the user "Something went wrong in Apple Login" +}); + +test("login with Apple IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Apple is configure on the organization as only authencation method + // Given idp Apple is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Apple + // User authenticates in Apple + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Apple IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Apple is configure on the organization as only authencation method + // Given idp Apple is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Apple + // User authenticates in Apple + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Apple IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Apple is configure on the organization as only authencation method + // Given idp Apple is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Apple + // User authenticates in Apple + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Apple IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Apple is configure on the organization as only authencation method + // Given idp Apple is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Apple + // User authenticates in Apple with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Apple IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Apple is configure on the organization as only authencation method + // Given idp Apple is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Apple + // User authenticates in Apple with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Apple IDP, no user linked, user link successful", async ({ page }) => { + test.skip(); + // Given idp Apple is configure on the organization as only authencation method + // Given idp Apple is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Apple + // User authenticates in Apple with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-generic-jwt.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-generic-jwt.spec.ts new file mode 100644 index 0000000..d68475a --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-generic-jwt.spec.ts @@ -0,0 +1,99 @@ +import test from "@playwright/test"; + +test("login with Generic JWT IDP", async ({ page }) => { + test.skip(); + // Given a Generic JWT IDP is configured on the organization + // Given the user has Generic JWT IDP added as auth method + // User authenticates with the Generic JWT IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with Generic JWT IDP - error", async ({ page }) => { + test.skip(); + // Given the Generic JWT IDP is configured on the organization + // Given the user has Generic JWT IDP added as auth method + // User is redirected to the Generic JWT IDP + // User authenticates with the Generic JWT IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Generic JWT IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Generic JWT is configure on the organization as only authencation method + // Given idp Generic JWT is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic JWT + // User authenticates in Generic JWT + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic JWT IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Generic JWT is configure on the organization as only authencation method + // Given idp Generic JWT is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic JWT + // User authenticates in Generic JWT + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic JWT IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Generic JWT is configure on the organization as only authencation method + // Given idp Generic JWT is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic JWT + // User authenticates in Generic JWT + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Generic JWT IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Generic JWT is configure on the organization as only authencation method + // Given idp Generic JWT is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Generic JWT + // User authenticates in Generic JWT with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic JWT IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Generic JWT is configure on the organization as only authencation method + // Given idp Generic JWT is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Generic JWT + // User authenticates in Generic JWT with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Generic JWT IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Generic JWT is configure on the organization as only authencation method + // Given idp Generic JWT is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Generic JWT + // User authenticates in Generic JWT with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-generic-oauth.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-generic-oauth.spec.ts new file mode 100644 index 0000000..24c25d0 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-generic-oauth.spec.ts @@ -0,0 +1,99 @@ +import test from "@playwright/test"; + +test("login with Generic OAuth IDP", async ({ page }) => { + test.skip(); + // Given a Generic OAuth IDP is configured on the organization + // Given the user has Generic OAuth IDP added as auth method + // User authenticates with the Generic OAuth IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with Generic OAuth IDP - error", async ({ page }) => { + test.skip(); + // Given the Generic OAuth IDP is configured on the organization + // Given the user has Generic OAuth IDP added as auth method + // User is redirected to the Generic OAuth IDP + // User authenticates with the Generic OAuth IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Generic OAuth IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Generic OAuth is configure on the organization as only authencation method + // Given idp Generic OAuth is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic OAuth + // User authenticates in Generic OAuth + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic OAuth IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Generic OAuth is configure on the organization as only authencation method + // Given idp Generic OAuth is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic OAuth + // User authenticates in Generic OAuth + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic OAuth IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Generic OAuth is configure on the organization as only authencation method + // Given idp Generic OAuth is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic OAuth + // User authenticates in Generic OAuth + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Generic OAuth IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Generic OAuth is configure on the organization as only authencation method + // Given idp Generic OAuth is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Generic OAuth + // User authenticates in Generic OAuth with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic OAuth IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Generic OAuth is configure on the organization as only authencation method + // Given idp Generic OAuth is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Generic OAuth + // User authenticates in Generic OAuth with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Generic OAuth IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Generic OAuth is configure on the organization as only authencation method + // Given idp Generic OAuth is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Generic OAuth + // User authenticates in Generic OAuth with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-generic-oidc.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-generic-oidc.spec.ts new file mode 100644 index 0000000..391481f --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-generic-oidc.spec.ts @@ -0,0 +1,101 @@ +// Note, we should use a provider such as Google to test this, where we know OIDC standard is properly implemented + +import test from "@playwright/test"; + +test("login with Generic OIDC IDP", async ({ page }) => { + test.skip(); + // Given a Generic OIDC IDP is configured on the organization + // Given the user has Generic OIDC IDP added as auth method + // User authenticates with the Generic OIDC IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with Generic OIDC IDP - error", async ({ page }) => { + test.skip(); + // Given the Generic OIDC IDP is configured on the organization + // Given the user has Generic OIDC IDP added as auth method + // User is redirected to the Generic OIDC IDP + // User authenticates with the Generic OIDC IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Generic OIDC IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Generic OIDC is configure on the organization as only authencation method + // Given idp Generic OIDC is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic OIDC + // User authenticates in Generic OIDC + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic OIDC IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Generic OIDC is configure on the organization as only authencation method + // Given idp Generic OIDC is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic OIDC + // User authenticates in Generic OIDC + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic OIDC IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Generic OIDC is configure on the organization as only authencation method + // Given idp Generic OIDC is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Generic OIDC + // User authenticates in Generic OIDC + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Generic OIDC IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Generic OIDC is configure on the organization as only authencation method + // Given idp Generic OIDC is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Generic OIDC + // User authenticates in Generic OIDC with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Generic OIDC IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Generic OIDC is configure on the organization as only authencation method + // Given idp Generic OIDC is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Generic OIDC + // User authenticates in Generic OIDC with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Generic OIDC IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Generic OIDC is configure on the organization as only authencation method + // Given idp Generic OIDC is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Generic OIDC + // User authenticates in Generic OIDC with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-github-enterprise.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-github-enterprise.spec.ts new file mode 100644 index 0000000..2c39092 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-github-enterprise.spec.ts @@ -0,0 +1,103 @@ +import test from "@playwright/test"; + +test("login with GitHub Enterprise IDP", async ({ page }) => { + test.skip(); + // Given a GitHub Enterprise IDP is configured on the organization + // Given the user has GitHub Enterprise IDP added as auth method + // User authenticates with the GitHub Enterprise IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with GitHub Enterprise IDP - error", async ({ page }) => { + test.skip(); + // Given the GitHub Enterprise IDP is configured on the organization + // Given the user has GitHub Enterprise IDP added as auth method + // User is redirected to the GitHub Enterprise IDP + // User authenticates with the GitHub Enterprise IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with GitHub Enterprise IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp GitHub Enterprise is configure on the organization as only authencation method + // Given idp GitHub Enterprise is configure with account creation alloweed, and automatic creation enabled + // Given ZITADEL Action is added to autofill missing user information + // Given no user exists yet + // User is automatically redirected to GitHub Enterprise + // User authenticates in GitHub Enterprise + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with GitHub Enterprise IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp GitHub Enterprise is configure on the organization as only authencation method + // Given idp GitHub Enterprise is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to GitHub Enterprise + // User authenticates in GitHub Enterprise + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with GitHub Enterprise IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp GitHub Enterprise is configure on the organization as only authencation method + // Given idp GitHub Enterprise is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to GitHub Enterprise + // User authenticates in GitHub Enterprise + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with GitHub Enterprise IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp GitHub Enterprise is configure on the organization as only authencation method + // Given idp GitHub Enterprise is configure with account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com exists + // User is automatically redirected to GitHub Enterprise + // User authenticates in GitHub Enterprise with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with GitHub Enterprise IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp GitHub Enterprise is configure on the organization as only authencation method + // Given idp GitHub Enterprise is configure with manually account linking not allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to GitHub Enterprise + // User authenticates in GitHub Enterprise with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with GitHub Enterprise IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp GitHub Enterprise is configure on the organization as only authencation method + // Given idp GitHub Enterprise is configure with manually account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to GitHub Enterprise + // User authenticates in GitHub Enterprise with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-github.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-github.spec.ts new file mode 100644 index 0000000..689e040 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-github.spec.ts @@ -0,0 +1,103 @@ +import test from "@playwright/test"; + +test("login with GitHub IDP", async ({ page }) => { + test.skip(); + // Given a GitHub IDP is configured on the organization + // Given the user has GitHub IDP added as auth method + // User authenticates with the GitHub IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with GitHub IDP - error", async ({ page }) => { + test.skip(); + // Given the GitHub IDP is configured on the organization + // Given the user has GitHub IDP added as auth method + // User is redirected to the GitHub IDP + // User authenticates with the GitHub IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with GitHub IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp GitHub is configure on the organization as only authencation method + // Given idp GitHub is configure with account creation alloweed, and automatic creation enabled + // Given ZITADEL Action is added to autofill missing user information + // Given no user exists yet + // User is automatically redirected to GitHub + // User authenticates in GitHub + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with GitHub IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp GitHub is configure on the organization as only authencation method + // Given idp GitHub is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to GitHub + // User authenticates in GitHub + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with GitHub IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp GitHub is configure on the organization as only authencation method + // Given idp GitHub is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to GitHub + // User authenticates in GitHub + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with GitHub IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp GitHub is configure on the organization as only authencation method + // Given idp GitHub is configure with account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com exists + // User is automatically redirected to GitHub + // User authenticates in GitHub with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with GitHub IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp GitHub is configure on the organization as only authencation method + // Given idp GitHub is configure with manually account linking not allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to GitHub + // User authenticates in GitHub with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with GitHub IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp GitHub is configure on the organization as only authencation method + // Given idp GitHub is configure with manually account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to GitHub + // User authenticates in GitHub with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-gitlab-self-hosted.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-gitlab-self-hosted.spec.ts new file mode 100644 index 0000000..1b05d5e --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-gitlab-self-hosted.spec.ts @@ -0,0 +1,103 @@ +import test from "@playwright/test"; + +test("login with GitLab Self-Hosted IDP", async ({ page }) => { + test.skip(); + // Given a GitLab Self-Hosted IDP is configured on the organization + // Given the user has GitLab Self-Hosted IDP added as auth method + // User authenticates with the GitLab Self-Hosted IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with GitLab Self-Hosted IDP - error", async ({ page }) => { + test.skip(); + // Given the GitLab Self-Hosted IDP is configured on the organization + // Given the user has GitLab Self-Hosted IDP added as auth method + // User is redirected to the GitLab Self-Hosted IDP + // User authenticates with the GitLab Self-Hosted IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Gitlab Self-Hosted IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Gitlab Self-Hosted is configure on the organization as only authencation method + // Given idp Gitlab Self-Hosted is configure with account creation alloweed, and automatic creation enabled + // Given ZITADEL Action is added to autofill missing user information + // Given no user exists yet + // User is automatically redirected to Gitlab Self-Hosted + // User authenticates in Gitlab Self-Hosted + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Gitlab Self-Hosted IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Gitlab Self-Hosted is configure on the organization as only authencation method + // Given idp Gitlab Self-Hosted is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Gitlab Self-Hosted + // User authenticates in Gitlab Self-Hosted + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Gitlab Self-Hosted IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Gitlab Self-Hosted is configure on the organization as only authencation method + // Given idp Gitlab Self-Hosted is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Gitlab Self-Hosted + // User authenticates in Gitlab Self-Hosted + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Gitlab Self-Hosted IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Gitlab Self-Hosted is configure on the organization as only authencation method + // Given idp Gitlab Self-Hosted is configure with account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Gitlab Self-Hosted + // User authenticates in Gitlab Self-Hosted with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Gitlab Self-Hosted IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Gitlab Self-Hosted is configure on the organization as only authencation method + // Given idp Gitlab Self-Hosted is configure with manually account linking not allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Gitlab Self-Hosted + // User authenticates in Gitlab Self-Hosted with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Gitlab Self-Hosted IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Gitlab Self-Hosted is configure on the organization as only authencation method + // Given idp Gitlab Self-Hosted is configure with manually account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Gitlab Self-Hosted + // User authenticates in Gitlab Self-Hosted with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-gitlab.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-gitlab.spec.ts new file mode 100644 index 0000000..fdb2358 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-gitlab.spec.ts @@ -0,0 +1,103 @@ +import test from "@playwright/test"; + +test("login with GitLab IDP", async ({ page }) => { + test.skip(); + // Given a GitLab IDP is configured on the organization + // Given the user has GitLab IDP added as auth method + // User authenticates with the GitLab IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with GitLab IDP - error", async ({ page }) => { + test.skip(); + // Given the GitLab IDP is configured on the organization + // Given the user has GitLab IDP added as auth method + // User is redirected to the GitLab IDP + // User authenticates with the GitLab IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Gitlab IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Gitlab is configure on the organization as only authencation method + // Given idp Gitlab is configure with account creation alloweed, and automatic creation enabled + // Given ZITADEL Action is added to autofill missing user information + // Given no user exists yet + // User is automatically redirected to Gitlab + // User authenticates in Gitlab + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Gitlab IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Gitlab is configure on the organization as only authencation method + // Given idp Gitlab is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Gitlab + // User authenticates in Gitlab + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Gitlab IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Gitlab is configure on the organization as only authencation method + // Given idp Gitlab is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Gitlab + // User authenticates in Gitlab + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Gitlab IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Gitlab is configure on the organization as only authencation method + // Given idp Gitlab is configure with account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Gitlab + // User authenticates in Gitlab with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Gitlab IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Gitlab is configure on the organization as only authencation method + // Given idp Gitlab is configure with manually account linking not allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Gitlab + // User authenticates in Gitlab with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Gitlab IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Gitlab is configure on the organization as only authencation method + // Given idp Gitlab is configure with manually account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Gitlab + // User authenticates in Gitlab with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-google.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-google.spec.ts new file mode 100644 index 0000000..8eb4d54 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-google.spec.ts @@ -0,0 +1,99 @@ +import test from "@playwright/test"; + +test("login with Google IDP", async ({ page }) => { + test.skip(); + // Given a Google IDP is configured on the organization + // Given the user has Google IDP added as auth method + // User authenticates with the Google IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with Google IDP - error", async ({ page }) => { + test.skip(); + // Given the Google IDP is configured on the organization + // Given the user has Google IDP added as auth method + // User is redirected to the Google IDP + // User authenticates with the Google IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Google IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Google is configure on the organization as only authencation method + // Given idp Google is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Google + // User authenticates in Google + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Google IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Google is configure on the organization as only authencation method + // Given idp Google is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Google + // User authenticates in Google + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Google IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Google is configure on the organization as only authencation method + // Given idp Google is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Google + // User authenticates in Google + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Google IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Google is configure on the organization as only authencation method + // Given idp Google is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Google + // User authenticates in Google with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Google IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Google is configure on the organization as only authencation method + // Given idp Google is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Google + // User authenticates in Google with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Google IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Google is configure on the organization as only authencation method + // Given idp Google is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Google + // User authenticates in Google with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-ldap.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-ldap.spec.ts new file mode 100644 index 0000000..0705ed4 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-ldap.spec.ts @@ -0,0 +1,99 @@ +import test from "@playwright/test"; + +test("login with LDAP IDP", async ({ page }) => { + test.skip(); + // Given a LDAP IDP is configured on the organization + // Given the user has LDAP IDP added as auth method + // User authenticates with the LDAP IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with LDAP IDP - error", async ({ page }) => { + test.skip(); + // Given the LDAP IDP is configured on the organization + // Given the user has LDAP IDP added as auth method + // User is redirected to the LDAP IDP + // User authenticates with the LDAP IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with LDAP IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp LDAP is configure on the organization as only authencation method + // Given idp LDAP is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to LDAP + // User authenticates in LDAP + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with LDAP IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp LDAP is configure on the organization as only authencation method + // Given idp LDAP is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to LDAP + // User authenticates in LDAP + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with LDAP IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp LDAP is configure on the organization as only authencation method + // Given idp LDAP is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to LDAP + // User authenticates in LDAP + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with LDAP IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp LDAP is configure on the organization as only authencation method + // Given idp LDAP is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to LDAP + // User authenticates in LDAP with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with LDAP IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp LDAP is configure on the organization as only authencation method + // Given idp LDAP is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to LDAP + // User authenticates in LDAP with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with LDAP IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp LDAP is configure on the organization as only authencation method + // Given idp LDAP is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to LDAP + // User authenticates in LDAP with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-microsoft.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-microsoft.spec.ts new file mode 100644 index 0000000..15d67c2 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-microsoft.spec.ts @@ -0,0 +1,102 @@ +// Note for all tests, in case Microsoft doesn't deliver all relevant information per default +// We should add an action in the needed cases + +import test from "@playwright/test"; + +test("login with Microsoft IDP", async ({ page }) => { + test.skip(); + // Given a Microsoft IDP is configured on the organization + // Given the user has Microsoft IDP added as auth method + // User authenticates with the Microsoft IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with Microsoft IDP - error", async ({ page }) => { + test.skip(); + // Given the Microsoft IDP is configured on the organization + // Given the user has Microsoft IDP added as auth method + // User is redirected to the Microsoft IDP + // User authenticates with the Microsoft IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with Microsoft IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp Microsoft is configure on the organization as only authencation method + // Given idp Microsoft is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Microsoft + // User authenticates in Microsoft + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Microsoft IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp Microsoft is configure on the organization as only authencation method + // Given idp Microsoft is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Microsoft + // User authenticates in Microsoft + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Microsoft IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp Microsoft is configure on the organization as only authencation method + // Given idp Microsoft is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to Microsoft + // User authenticates in Microsoft + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with Microsoft IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp Microsoft is configure on the organization as only authencation method + // Given idp Microsoft is configure with account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com exists + // User is automatically redirected to Microsoft + // User authenticates in Microsoft with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with Microsoft IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp Microsoft is configure on the organization as only authencation method + // Given idp Microsoft is configure with manually account linking not allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Microsoft + // User authenticates in Microsoft with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with Microsoft IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp Microsoft is configure on the organization as only authencation method + // Given idp Microsoft is configure with manually account linking allowed, and linking set to existing email + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to Microsoft + // User authenticates in Microsoft with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/idp-saml.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/idp-saml.spec.ts new file mode 100644 index 0000000..90d8d61 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/idp-saml.spec.ts @@ -0,0 +1,103 @@ +import test from "@playwright/test"; + +test("login with SAML IDP", async ({ page }) => { + test.skip(); + // Given a SAML IDP is configured on the organization + // Given the user has SAML IDP added as auth method + // User authenticates with the SAML IDP + // User is redirected back to login + // User is redirected to the app +}); + +test("login with SAML IDP - error", async ({ page }) => { + test.skip(); + // Given the SAML IDP is configured on the organization + // Given the user has SAML IDP added as auth method + // User is redirected to the SAML IDP + // User authenticates with the SAML IDP and gets an error + // User is redirected back to login + // An error is shown to the user "Something went wrong" +}); + +test("login with SAML IDP, no user existing - auto register", async ({ page }) => { + test.skip(); + // Given idp SAML is configure on the organization as only authencation method + // Given idp SAML is configure with account creation alloweed, and automatic creation enabled + // Given ZITADEL Action is added to autofill missing user information + // Given no user exists yet + // User is automatically redirected to SAML + // User authenticates in SAML + // User is redirect to ZITADEL login + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with SAML IDP, no user existing - auto register not possible", async ({ page }) => { + test.skip(); + // Given idp SAML is configure on the organization as only authencation method + // Given idp SAML is configure with account creation alloweed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to SAML + // User authenticates in SAML + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // User will see the registration page with pre filled user information + // User fills missing information + // User clicks register button + // User is created in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with SAML IDP, no user existing - auto register enabled - manual creation disabled, creation not possible", async ({ + page, +}) => { + test.skip(); + // Given idp SAML is configure on the organization as only authencation method + // Given idp SAML is configure with account creation not allowed, and automatic creation enabled + // Given no user exists yet + // User is automatically redirected to SAML + // User authenticates in SAML + // User is redirect to ZITADEL login + // Because of missing informaiton on the user auto creation is not possible + // Error message is shown, that registration of the user was not possible due to missing information +}); + +test("login with SAML IDP, no user linked - auto link", async ({ page }) => { + test.skip(); + // Given idp SAML is configure on the organization as only authencation method + // Given idp SAML is configure with account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com exists + // User is automatically redirected to SAML + // User authenticates in SAML with user@zitadel.com + // User is redirect to ZITADEL login + // User is linked with existing user in ZITADEL + // User is redirected to the app (default redirect url) +}); + +test("login with SAML IDP, no user linked, linking not possible", async ({ page }) => { + test.skip(); + // Given idp SAML is configure on the organization as only authencation method + // Given idp SAML is configure with manually account linking not allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to SAML + // User authenticates in SAML with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User will get an error message that account linking wasn't possible +}); + +test("login with SAML IDP, no user linked, linking successful", async ({ page }) => { + test.skip(); + // Given idp SAML is configure on the organization as only authencation method + // Given idp SAML is configure with manually account linking allowed, and linking set to existing email + // Given ZITADEL Action is added to autofill missing user information + // Given user with email address user@zitadel.com doesn't exists + // User is automatically redirected to SAML + // User authenticates in SAML with user@zitadel.com + // User is redirect to ZITADEL login + // User with email address user@zitadel.com can not be found + // User is prompted to link the account manually + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/login-configuration-possiblities.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/login-configuration-possiblities.spec.ts new file mode 100644 index 0000000..cc58dbc --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/login-configuration-possiblities.spec.ts @@ -0,0 +1,57 @@ +import test from "@playwright/test"; + +test("login with mfa setup, mfa setup prompt", async ({ page }) => { + test.skip(); + // Given the organization has enabled at least one mfa types + // Given the user has a password but no mfa registered + // User authenticates with login name and password + // User is prompted to setup a mfa, mfa providers are listed, the user can choose the provider +}); + +test("login with mfa setup, no mfa setup prompt", async ({ page }) => { + test.skip(); + // Given the organization has set "multifactor init check time" to 0 + // Given the organization has enabled mfa types + // Given the user has a password but no mfa registered + // User authenticates with loginname and password + // user is directly loged in and not prompted to setup mfa +}); + +test("login with mfa setup, force mfa for local authenticated users", async ({ page }) => { + test.skip(); + // Given the organization has enabled force mfa for local authentiacted users + // Given the organization has enabled all possible mfa types + // Given the user has a password but no mfa registered + // User authenticates with loginname and password + // User is prompted to setup a mfa, all possible mfa providers are listed, the user can choose the provider +}); + +test("login with mfa setup, force mfa - local user", async ({ page }) => { + test.skip(); + // Given the organization has enabled force mfa for local authentiacted users + // Given the organization has enabled all possible mfa types + // Given the user has a password but no mfa registered + // User authenticates with loginname and password + // User is prompted to setup a mfa, all possible mfa providers are listed, the user can choose the provider +}); + +test("login with mfa setup, force mfa - external user", async ({ page }) => { + test.skip(); + // Given the organization has enabled force mfa + // Given the organization has enabled all possible mfa types + // Given the user has an idp but no mfa registered + // enter login name + // redirect to configured external idp + // User is prompted to setup a mfa, all possible mfa providers are listed, the user can choose the provider +}); + +test("login with mfa setup, force mfa - local user, wrong password", async ({ page }) => { + test.skip(); + // Given the organization has a password lockout policy set to 1 on the max password attempts + // Given the user has only a password as auth methos + // enter login name + // enter wrong password + // User will get an error "Wrong password" + // enter password + // User will get an error "Max password attempts reached - user is locked. Please reach out to your administrator" +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/login.ts b/auth/ui/v2/apps/login/acceptance/tests/login.ts new file mode 100644 index 0000000..2076412 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/login.ts @@ -0,0 +1,41 @@ +import { expect, Page } from "@playwright/test"; +import { code, otpFromSink } from "./code"; +import { loginname } from "./loginname"; +import { password } from "./password"; +import { totp } from "./zitadel"; + +export async function startLogin(page: Page) { + await page.goto(`./loginname`); +} + +export async function loginWithPassword(page: Page, username: string, pw: string) { + await startLogin(page); + await loginname(page, username); + await password(page, pw); +} + +export async function loginWithPasskey(page: Page, authenticatorId: string, username: string) { + await startLogin(page); + await loginname(page, username); + // await passkey(page, authenticatorId); +} + +export async function loginScreenExpect(page: Page, fullName: string) { + await expect(page).toHaveURL(/.*signedin.*/); + await expect(page.getByRole("heading")).toContainText(fullName); +} + +export async function loginWithPasswordAndEmailOTP(page: Page, username: string, password: string, email: string) { + await loginWithPassword(page, username, password); + await otpFromSink(page, email); +} + +export async function loginWithPasswordAndPhoneOTP(page: Page, username: string, password: string, phone: string) { + await loginWithPassword(page, username, password); + await otpFromSink(page, phone); +} + +export async function loginWithPasswordAndTOTP(page: Page, username: string, password: string, secret: string) { + await loginWithPassword(page, username, password); + await code(page, totp(secret)); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/loginname-screen.ts b/auth/ui/v2/apps/login/acceptance/tests/loginname-screen.ts new file mode 100644 index 0000000..be41a28 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/loginname-screen.ts @@ -0,0 +1,12 @@ +import { expect, Page } from "@playwright/test"; + +const usernameTextInput = "username-text-input"; + +export async function loginnameScreen(page: Page, username: string) { + await page.getByTestId(usernameTextInput).pressSequentially(username); +} + +export async function loginnameScreenExpect(page: Page, username: string) { + await expect(page.getByTestId(usernameTextInput)).toHaveValue(username); + await expect(page.getByTestId("error").locator("div")).toContainText("User not found in the system"); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/loginname.ts b/auth/ui/v2/apps/login/acceptance/tests/loginname.ts new file mode 100644 index 0000000..2050ec1 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/loginname.ts @@ -0,0 +1,7 @@ +import { Page } from "@playwright/test"; +import { loginnameScreen } from "./loginname-screen"; + +export async function loginname(page: Page, username: string) { + await loginnameScreen(page, username); + await page.getByTestId("submit-button").click(); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/passkey.ts b/auth/ui/v2/apps/login/acceptance/tests/passkey.ts new file mode 100644 index 0000000..d8cda10 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/passkey.ts @@ -0,0 +1,109 @@ +import { expect, Page } from "@playwright/test"; +import { CDPSession } from "playwright-core"; + +interface session { + client: CDPSession; + authenticatorId: string; +} + +async function client(page: Page): Promise { + const cdpSession = await page.context().newCDPSession(page); + await cdpSession.send("WebAuthn.enable", { enableUI: false }); + const result = await cdpSession.send("WebAuthn.addVirtualAuthenticator", { + options: { + protocol: "ctap2", + transport: "internal", + hasResidentKey: true, + hasUserVerification: true, + isUserVerified: true, + automaticPresenceSimulation: true, + }, + }); + return { client: cdpSession, authenticatorId: result.authenticatorId }; +} + +export async function passkeyRegister(page: Page): Promise { + const session = await client(page); + + await passkeyNotExisting(session.client, session.authenticatorId); + await simulateSuccessfulPasskeyRegister(session.client, session.authenticatorId, () => + page.getByTestId("submit-button").click(), + ); + await passkeyRegistered(session.client, session.authenticatorId); + + return session.authenticatorId; +} + +export async function passkey(page: Page, authenticatorId: string) { + const cdpSession = await page.context().newCDPSession(page); + await cdpSession.send("WebAuthn.enable", { enableUI: false }); + + const signCount = await passkeyExisting(cdpSession, authenticatorId); + + await simulateSuccessfulPasskeyInput(cdpSession, authenticatorId, () => page.getByTestId("submit-button").click()); + + await passkeyUsed(cdpSession, authenticatorId, signCount); +} + +async function passkeyNotExisting(client: CDPSession, authenticatorId: string) { + const result = await client.send("WebAuthn.getCredentials", { authenticatorId }); + expect(result.credentials).toHaveLength(0); +} + +async function passkeyRegistered(client: CDPSession, authenticatorId: string) { + const result = await client.send("WebAuthn.getCredentials", { authenticatorId }); + expect(result.credentials).toHaveLength(1); + await passkeyUsed(client, authenticatorId, 0); +} + +async function passkeyExisting(client: CDPSession, authenticatorId: string): Promise { + const result = await client.send("WebAuthn.getCredentials", { authenticatorId }); + expect(result.credentials).toHaveLength(1); + return result.credentials[0].signCount; +} + +async function passkeyUsed(client: CDPSession, authenticatorId: string, signCount: number) { + const result = await client.send("WebAuthn.getCredentials", { authenticatorId }); + expect(result.credentials).toHaveLength(1); + expect(result.credentials[0].signCount).toBeGreaterThan(signCount); +} + +async function simulateSuccessfulPasskeyRegister( + client: CDPSession, + authenticatorId: string, + operationTrigger: () => Promise, +) { + // initialize event listeners to wait for a successful passkey input event + const operationCompleted = new Promise((resolve) => { + client.on("WebAuthn.credentialAdded", () => { + console.log("Credential Added!"); + resolve(); + }); + }); + + // perform a user action that triggers passkey prompt + await operationTrigger(); + + // wait to receive the event that the passkey was successfully registered or verified + await operationCompleted; +} + +async function simulateSuccessfulPasskeyInput( + client: CDPSession, + authenticatorId: string, + operationTrigger: () => Promise, +) { + // initialize event listeners to wait for a successful passkey input event + const operationCompleted = new Promise((resolve) => { + client.on("WebAuthn.credentialAsserted", () => { + console.log("Credential Asserted!"); + resolve(); + }); + }); + + // perform a user action that triggers passkey prompt + await operationTrigger(); + + // wait to receive the event that the passkey was successfully registered or verified + await operationCompleted; +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/password-screen.ts b/auth/ui/v2/apps/login/acceptance/tests/password-screen.ts new file mode 100644 index 0000000..fda6f6d --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/password-screen.ts @@ -0,0 +1,98 @@ +import { expect, Page } from "@playwright/test"; +import { getCodeFromSink } from "./sink"; + +const codeField = "code-text-input"; +const passwordField = "password-text-input"; +const passwordChangeField = "password-change-text-input"; +const passwordChangeConfirmField = "password-change-confirm-text-input"; +const passwordSetField = "password-set-text-input"; +const passwordSetConfirmField = "password-set-confirm-text-input"; +const lengthCheck = "length-check"; +const symbolCheck = "symbol-check"; +const numberCheck = "number-check"; +const uppercaseCheck = "uppercase-check"; +const lowercaseCheck = "lowercase-check"; +const equalCheck = "equal-check"; + +const matchText = "Matches"; +const noMatchText = "Doesn't match"; + +export async function changePasswordScreen(page: Page, password1: string, password2: string) { + await page.getByTestId(passwordChangeField).pressSequentially(password1); + await page.getByTestId(passwordChangeConfirmField).pressSequentially(password2); +} + +export async function passwordScreen(page: Page, password: string) { + await page.getByTestId(passwordField).pressSequentially(password); +} + +export async function passwordScreenExpect(page: Page, password: string) { + await expect(page.getByTestId(passwordField)).toHaveValue(password); + await expect(page.getByTestId("error").locator("div")).toContainText("Failed to authenticate."); +} + +export async function changePasswordScreenExpect( + page: Page, + password1: string, + password2: string, + length: boolean, + symbol: boolean, + number: boolean, + uppercase: boolean, + lowercase: boolean, + equals: boolean, +) { + await expect(page.getByTestId(passwordChangeField)).toHaveValue(password1); + await expect(page.getByTestId(passwordChangeConfirmField)).toHaveValue(password2); + + await checkComplexity(page, length, symbol, number, uppercase, lowercase, equals); +} + +async function checkComplexity( + page: Page, + length: boolean, + symbol: boolean, + number: boolean, + uppercase: boolean, + lowercase: boolean, + equals: boolean, +) { + await checkContent(page, lengthCheck, length); + await checkContent(page, symbolCheck, symbol); + await checkContent(page, numberCheck, number); + await checkContent(page, uppercaseCheck, uppercase); + await checkContent(page, lowercaseCheck, lowercase); + await checkContent(page, equalCheck, equals); +} + +async function checkContent(page: Page, testid: string, match: boolean) { + if (match) { + await expect(page.getByTestId(testid)).toContainText(matchText); + } else { + await expect(page.getByTestId(testid)).toContainText(noMatchText); + } +} + +export async function resetPasswordScreen(page: Page, username: string, password1: string, password2: string) { + const c = await getCodeFromSink(username); + await page.getByTestId(codeField).pressSequentially(c); + await page.getByTestId(passwordSetField).pressSequentially(password1); + await page.getByTestId(passwordSetConfirmField).pressSequentially(password2); +} + +export async function resetPasswordScreenExpect( + page: Page, + password1: string, + password2: string, + length: boolean, + symbol: boolean, + number: boolean, + uppercase: boolean, + lowercase: boolean, + equals: boolean, +) { + await expect(page.getByTestId(passwordSetField)).toHaveValue(password1); + await expect(page.getByTestId(passwordSetConfirmField)).toHaveValue(password2); + + await checkComplexity(page, length, symbol, number, uppercase, lowercase, equals); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/password.ts b/auth/ui/v2/apps/login/acceptance/tests/password.ts new file mode 100644 index 0000000..ccf3e50 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/password.ts @@ -0,0 +1,29 @@ +import { Page } from "@playwright/test"; +import { changePasswordScreen, passwordScreen, resetPasswordScreen } from "./password-screen"; + +const passwordSubmitButton = "submit-button"; +const passwordResetButton = "reset-button"; + +export async function startChangePassword(page: Page, loginname: string) { + await page.goto("./password/change?" + new URLSearchParams({ loginName: loginname })); +} + +export async function changePassword(page: Page, password: string) { + await changePasswordScreen(page, password, password); + await page.getByTestId(passwordSubmitButton).click(); +} + +export async function password(page: Page, password: string) { + await passwordScreen(page, password); + await page.getByTestId(passwordSubmitButton).click(); +} + +export async function startResetPassword(page: Page) { + await page.getByTestId(passwordResetButton).click(); +} + +export async function resetPassword(page: Page, username: string, password: string) { + await startResetPassword(page); + await resetPasswordScreen(page, username, password, password); + await page.getByTestId(passwordSubmitButton).click(); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/register-screen.ts b/auth/ui/v2/apps/login/acceptance/tests/register-screen.ts new file mode 100644 index 0000000..d14f5dc --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/register-screen.ts @@ -0,0 +1,27 @@ +import { Page } from "@playwright/test"; + +const passwordField = "password-text-input"; +const passwordConfirmField = "password-confirm-text-input"; + +export async function registerUserScreenPassword(page: Page, firstname: string, lastname: string, email: string) { + await registerUserScreen(page, firstname, lastname, email); + await page.getByTestId("password-radio").click(); +} + +export async function registerUserScreenPasskey(page: Page, firstname: string, lastname: string, email: string) { + await registerUserScreen(page, firstname, lastname, email); + await page.getByTestId("passkey-radio").click(); +} + +export async function registerPasswordScreen(page: Page, password1: string, password2: string) { + await page.getByTestId(passwordField).pressSequentially(password1); + await page.getByTestId(passwordConfirmField).pressSequentially(password2); +} + +export async function registerUserScreen(page: Page, firstname: string, lastname: string, email: string) { + await page.getByTestId("firstname-text-input").pressSequentially(firstname); + await page.getByTestId("lastname-text-input").pressSequentially(lastname); + await page.getByTestId("email-text-input").pressSequentially(email); + await page.getByTestId("privacy-policy-checkbox").check(); + await page.getByTestId("tos-checkbox").check(); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/register.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/register.spec.ts new file mode 100644 index 0000000..4ad7e9e --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/register.spec.ts @@ -0,0 +1,183 @@ +import { faker } from "@faker-js/faker"; +import { test } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { loginScreenExpect } from "./login"; +import { registerWithPasskey, registerWithPassword } from "./register"; +import { removeUserByUsername } from "./zitadel"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +test("register with password", async ({ page }) => { + const username = faker.internet.email(); + const password = "Password1!"; + const firstname = faker.person.firstName(); + const lastname = faker.person.lastName(); + + await registerWithPassword(page, firstname, lastname, username, password, password); + await loginScreenExpect(page, firstname + " " + lastname); + + // wait for projection of user + await page.waitForTimeout(10000); + await removeUserByUsername(username); +}); + +test("register with passkey", async ({ page }) => { + const username = faker.internet.email(); + const firstname = faker.person.firstName(); + const lastname = faker.person.lastName(); + + await registerWithPasskey(page, firstname, lastname, username); + await loginScreenExpect(page, firstname + " " + lastname); + + // wait for projection of user + await page.waitForTimeout(10000); + await removeUserByUsername(username); +}); + +test("register with username and password - only password enabled", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is not enabled + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // Only password is shown as an option - no passkey + // User enters "firstname", "lastname", "username" and "password" + // User is redirected to app (default redirect url) +}); + +test("register with username and password - wrong password not enough characters", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is not enabled + // Given password policy is set to 8 characters and must include number, symbol, lower and upper letter + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // Only password is shown as an option - no passkey + // User enters "firstname", "lastname", "username" and a password thats to short + // Error is shown "Password doesn't match the policy - it must have at least 8 characters" +}); + +test("register with username and password - wrong password number missing", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is not enabled + // Given password policy is set to 8 characters and must include number, symbol, lower and upper letter + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // Only password is shown as an option - no passkey + // User enters "firstname", "lastname", "username" and a password without a number + // Error is shown "Password doesn't match the policy - number missing" +}); + +test("register with username and password - wrong password upper case missing", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is not enabled + // Given password policy is set to 8 characters and must include number, symbol, lower and upper letter + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // Only password is shown as an option - no passkey + // User enters "firstname", "lastname", "username" and a password without an upper case + // Error is shown "Password doesn't match the policy - uppercase letter missing" +}); + +test("register with username and password - wrong password lower case missing", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is not enabled + // Given password policy is set to 8 characters and must include number, symbol, lower and upper letter + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // Only password is shown as an option - no passkey + // User enters "firstname", "lastname", "username" and a password without an lower case + // Error is shown "Password doesn't match the policy - lowercase letter missing" +}); + +test("register with username and password - wrong password symboo missing", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is not enabled + // Given password policy is set to 8 characters and must include number, symbol, lower and upper letter + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // Only password is shown as an option - no passkey + // User enters "firstname", "lastname", "username" and a password without an symbol + // Error is shown "Password doesn't match the policy - symbol missing" +}); + +test("register with username and password - password and passkey enabled", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is enabled + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // User enters "firstname", "lastname", "username" + // Password and passkey are shown as authentication option + // User clicks password + // User enters password + // User is redirected to app (default redirect url) +}); + +test("register with username and passkey - password and passkey enabled", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given on the default organization passkey is enabled + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration page + // User enters "firstname", "lastname", "username" + // Password and passkey are shown as authentication option + // User clicks passkey + // Passkey is opened automatically + // User verifies passkey + // User is redirected to app (default redirect url) +}); + +test("register with username and password - registration disabled", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization no idp is configured and enabled + // Given user doesn't exist + // Button "register new user" is not available +}); + +test("register with username and password - multiple registration options", async ({ page }) => { + test.skip(); + // Given on the default organization "username and password is allowed" is enabled + // Given on the default organization "username registeration allowed" is enabled + // Given on the default organization one idp is configured and enabled + // Given user doesn't exist + // Click on button "register new user" + // User is redirected to registration options + // Local User and idp button are shown + // User clicks idp button + // User enters "firstname", "lastname", "username" and "password" + // User clicks next + // User is redirected to app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/register.ts b/auth/ui/v2/apps/login/acceptance/tests/register.ts new file mode 100644 index 0000000..164a727 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/register.ts @@ -0,0 +1,39 @@ +import { Page } from "@playwright/test"; +import { emailVerify } from "./email-verify"; +import { passkeyRegister } from "./passkey"; +import { registerPasswordScreen, registerUserScreenPasskey, registerUserScreenPassword } from "./register-screen"; +import { getCodeFromSink } from "./sink"; + +export async function registerWithPassword( + page: Page, + firstname: string, + lastname: string, + email: string, + password1: string, + password2: string, +) { + await page.goto("./register"); + await registerUserScreenPassword(page, firstname, lastname, email); + await page.getByTestId("submit-button").click(); + await registerPasswordScreen(page, password1, password2); + await page.getByTestId("submit-button").click(); + await verifyEmail(page, email); +} + +export async function registerWithPasskey(page: Page, firstname: string, lastname: string, email: string): Promise { + await page.goto("./register"); + await registerUserScreenPasskey(page, firstname, lastname, email); + await page.getByTestId("submit-button").click(); + + // wait for projection of user + await page.waitForTimeout(10000); + const authId = await passkeyRegister(page); + + await verifyEmail(page, email); + return authId; +} + +async function verifyEmail(page: Page, email: string) { + const c = await getCodeFromSink(email); + await emailVerify(page, c); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/select-account.ts b/auth/ui/v2/apps/login/acceptance/tests/select-account.ts new file mode 100644 index 0000000..64bd7cd --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/select-account.ts @@ -0,0 +1,5 @@ +import { Page } from "@playwright/test"; + +export async function selectNewAccount(page: Page) { + await page.getByRole("link", { name: "Add another account" }).click(); +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/sink.ts b/auth/ui/v2/apps/login/acceptance/tests/sink.ts new file mode 100644 index 0000000..bc3336b --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/sink.ts @@ -0,0 +1,43 @@ +import { Gaxios, GaxiosResponse } from "gaxios"; + +const awaitNotification = new Gaxios({ + url: process.env.SINK_NOTIFICATION_URL, + method: "POST", + retryConfig: { + httpMethodsToRetry: ["POST"], + statusCodesToRetry: [[404, 404]], + retry: Number.MAX_SAFE_INTEGER, // totalTimeout limits the number of retries + totalTimeout: 10000, // 10 seconds + onRetryAttempt: (error) => { + console.warn(`Retrying request to sink notification service: ${error.message}`); + }, + }, +}); + +export async function getOtpFromSink(recipient: string): Promise { + return awaitNotification.request({ data: { recipient } }).then((response) => { + expectSuccess(response); + const otp = response?.data?.args?.otp; + if (!otp) { + throw new Error(`Response does not contain an otp property: ${JSON.stringify(response.data, null, 2)}`); + } + return otp; + }); +} + +export async function getCodeFromSink(recipient: string): Promise { + return awaitNotification.request({ data: { recipient } }).then((response) => { + expectSuccess(response); + const code = response?.data?.args?.code; + if (!code) { + throw new Error(`Response does not contain a code property: ${JSON.stringify(response.data, null, 2)}`); + } + return code; + }); +} + +function expectSuccess(response: GaxiosResponse): void { + if (response.status !== 200) { + throw new Error(`Expected HTTP status 200, but got: ${response.status} - ${response.statusText}`); + } +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/user.ts b/auth/ui/v2/apps/login/acceptance/tests/user.ts new file mode 100644 index 0000000..3b03291 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/user.ts @@ -0,0 +1,177 @@ +import { Page } from "@playwright/test"; +import { registerWithPasskey } from "./register"; +import { activateOTP, addTOTP, addUser, eventualNewUser, getUserByUsername, removeUser } from "./zitadel"; + +export interface userProps { + email: string; + isEmailVerified?: boolean; + firstName: string; + lastName: string; + organization: string; + password: string; + passwordChangeRequired?: boolean; + phone: string; + isPhoneVerified?: boolean; +} + +class User { + private readonly props: userProps; + private user: string; + + constructor(userProps: userProps) { + this.props = userProps; + } + + async ensure(page: Page) { + const response = await addUser(this.props); + + this.setUserId(response.userId); + } + + async cleanup() { + await removeUser(this.getUserId()); + } + + public setUserId(userId: string) { + this.user = userId; + } + + public getUserId() { + return this.user; + } + + public getUsername() { + return this.props.email; + } + + public getPassword() { + return this.props.password; + } + + public getFirstname() { + return this.props.firstName; + } + + public getLastname() { + return this.props.lastName; + } + + public getPhone() { + return this.props.phone; + } + + public getFullName() { + return `${this.props.firstName} ${this.props.lastName}`; + } +} + +export class PasswordUser extends User { + async ensure(page: Page) { + await super.ensure(page); + await eventualNewUser(this.getUserId()); + } +} + +export enum OtpType { + sms = "sms", + email = "email", +} + +export interface otpUserProps { + email: string; + isEmailVerified?: boolean; + firstName: string; + lastName: string; + organization: string; + password: string; + passwordChangeRequired?: boolean; + phone: string; + isPhoneVerified?: boolean; + type: OtpType; +} + +export class PasswordUserWithOTP extends User { + private type: OtpType; + + constructor(props: otpUserProps) { + super({ + email: props.email, + firstName: props.firstName, + lastName: props.lastName, + organization: props.organization, + password: props.password, + phone: props.phone, + isEmailVerified: props.isEmailVerified, + isPhoneVerified: props.isPhoneVerified, + passwordChangeRequired: props.passwordChangeRequired, + }); + this.type = props.type; + } + + async ensure(page: Page) { + await super.ensure(page); + await activateOTP(this.getUserId(), this.type); + await eventualNewUser(this.getUserId()); + } +} + +export class PasswordUserWithTOTP extends User { + private secret: string; + + async ensure(page: Page) { + await super.ensure(page); + this.secret = await addTOTP(this.getUserId()); + await eventualNewUser(this.getUserId()); + } + + public getSecret(): string { + return this.secret; + } +} + +export interface passkeyUserProps { + email: string; + firstName: string; + lastName: string; + organization: string; + phone: string; + isEmailVerified?: boolean; + isPhoneVerified?: boolean; +} + +export class PasskeyUser extends User { + private authenticatorId: string; + + constructor(props: passkeyUserProps) { + super({ + email: props.email, + firstName: props.firstName, + lastName: props.lastName, + organization: props.organization, + password: "", + phone: props.phone, + isEmailVerified: props.isEmailVerified, + isPhoneVerified: props.isPhoneVerified, + }); + } + + public async ensure(page: Page) { + const authId = await registerWithPasskey(page, this.getFirstname(), this.getLastname(), this.getUsername()); + this.authenticatorId = authId; + + // wait for projection of user + await page.waitForTimeout(10000); + } + + async cleanup() { + const resp: any = await getUserByUsername(this.getUsername()); + if (!resp || !resp.result || !resp.result[0]) { + return; + } + await removeUser(resp.result[0].userId); + } + + public getAuthenticatorId(): string { + return this.authenticatorId; + } +} diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-passkey.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-passkey.spec.ts new file mode 100644 index 0000000..dff1c65 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-passkey.spec.ts @@ -0,0 +1,43 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { loginScreenExpect, loginWithPasskey } from "./login"; +import { PasskeyUser } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasskeyUser }>({ + user: async ({ page }, use) => { + const user = new PasskeyUser({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + }); + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("username and passkey login", async ({ user, page }) => { + await loginWithPasskey(page, user.getAuthenticatorId(), user.getUsername()); + await loginScreenExpect(page, user.getFullName()); +}); + +test("username and passkey login, multiple auth methods", async ({ page }) => { + test.skip(); + // Given passkey and password is enabled on the organization of the user + // Given the user has password and passkey registered + // enter username + // passkey popup is directly shown + // user aborts passkey authentication + // user switches to password authentication + // user enters password + // user is redirected to app +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-change-required.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-change-required.spec.ts new file mode 100644 index 0000000..50605e5 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-change-required.spec.ts @@ -0,0 +1,41 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { loginScreenExpect, loginWithPassword } from "./login"; +import { changePassword } from "./password"; +import { PasswordUser } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUser }>({ + user: async ({ page }, use) => { + const user = new PasswordUser({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + password: "Password1!", + passwordChangeRequired: true, + }); + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("username and password login, change required", async ({ user, page }) => { + const changedPw = "ChangedPw1!"; + + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await page.waitForTimeout(10000); + await changePassword(page, changedPw); + await loginScreenExpect(page, user.getFullName()); + + await loginWithPassword(page, user.getUsername(), changedPw); + await loginScreenExpect(page, user.getFullName()); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-changed.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-changed.spec.ts new file mode 100644 index 0000000..dc29dc2 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-changed.spec.ts @@ -0,0 +1,54 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { loginScreenExpect, loginWithPassword } from "./login"; +import { changePassword, startChangePassword } from "./password"; +import { changePasswordScreen, changePasswordScreenExpect } from "./password-screen"; +import { PasswordUser } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUser }>({ + user: async ({ page }, use) => { + const user = new PasswordUser({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + password: "Password1!", + passwordChangeRequired: false, + }); + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("username and password changed login", async ({ user, page }) => { + const changedPw = "ChangedPw1!"; + await loginWithPassword(page, user.getUsername(), user.getPassword()); + + // wait for projection of token + await page.waitForTimeout(10000); + + await startChangePassword(page, user.getUsername()); + await changePassword(page, changedPw); + await loginScreenExpect(page, user.getFullName()); + + await loginWithPassword(page, user.getUsername(), changedPw); + await loginScreenExpect(page, user.getFullName()); +}); + +test("password change not with desired complexity", async ({ user, page }) => { + const changedPw1 = "change"; + const changedPw2 = "chang"; + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await startChangePassword(page, user.getUsername()); + await changePasswordScreen(page, changedPw1, changedPw2); + await changePasswordScreenExpect(page, changedPw1, changedPw2, false, false, false, false, true, false); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-otp_email.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-otp_email.spec.ts new file mode 100644 index 0000000..31e854c --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-otp_email.spec.ts @@ -0,0 +1,98 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { code, codeResend, otpFromSink } from "./code"; +import { codeScreenExpect } from "./code-screen"; +import { loginScreenExpect, loginWithPassword, loginWithPasswordAndEmailOTP } from "./login"; +import { OtpType, PasswordUserWithOTP } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUserWithOTP; sink: any }>({ + user: async ({ page }, use) => { + const user = new PasswordUserWithOTP({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + password: "Password1!", + passwordChangeRequired: false, + type: OtpType.email, + }); + + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test.skip("DOESN'T WORK: username, password and email otp login, enter code manually", async ({ user, page }) => { + // Given email otp is enabled on the organization of the user + // Given the user has only email otp configured as second factor + // User enters username + // User enters password + // User receives an email with a verification code + // User enters the code into the ui + // User is redirected to the app (default redirect url) + await loginWithPasswordAndEmailOTP(page, user.getUsername(), user.getPassword(), user.getUsername()); + await loginScreenExpect(page, user.getFullName()); +}); + +test("username, password and email otp login, click link in email", async ({ page }) => { + base.skip(); + // Given email otp is enabled on the organization of the user + // Given the user has only email otp configured as second factor + // User enters username + // User enters password + // User receives an email with a verification code + // User clicks link in the email + // User is redirected to the app (default redirect url) +}); + +test.skip("DOESN'T WORK: username, password and email otp login, resend code", async ({ user, page }) => { + // Given email otp is enabled on the organization of the user + // Given the user has only email otp configured as second factor + // User enters username + // User enters password + // User receives an email with a verification code + // User clicks resend code + // User receives a new email with a verification code + // User enters the new code in the ui + // User is redirected to the app (default redirect url) + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await codeResend(page); + await otpFromSink(page, user.getUsername()); + await loginScreenExpect(page, user.getFullName()); +}); + +test("username, password and email otp login, wrong code", async ({ user, page }) => { + // Given email otp is enabled on the organization of the user + // Given the user has only email otp configured as second factor + // User enters username + // User enters password + // User receives an email with a verification code + // User enters a wrong code + // Error message - "Invalid code" is shown + const c = "wrongcode"; + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await code(page, c); + await codeScreenExpect(page, c); +}); + +test("username, password and email otp login, multiple mfa options", async ({ page }) => { + base.skip(); + // Given OTP Email and OTP SMS is enabled on the organization of the user + // Given the user has OTP Email and OTP SMS configured as second factor + // User enters username + // User enters password + // User receives an email with a verification code + // User clicks button to use OTP SMS as second factor + // User receives a sms with a verification code + // User enters code in ui + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-otp_sms.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-otp_sms.spec.ts new file mode 100644 index 0000000..d6205bc --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-otp_sms.spec.ts @@ -0,0 +1,71 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { code } from "./code"; +import { codeScreenExpect } from "./code-screen"; +import { loginScreenExpect, loginWithPassword, loginWithPasswordAndPhoneOTP } from "./login"; +import { OtpType, PasswordUserWithOTP } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUserWithOTP; sink: any }>({ + user: async ({ page }, use) => { + const user = new PasswordUserWithOTP({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number({ style: "international" }), + isPhoneVerified: true, + password: "Password1!", + passwordChangeRequired: false, + type: OtpType.sms, + }); + + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test.skip("DOESN'T WORK: username, password and OTP SMS login, enter code manually", async ({ user, page }) => { + // Given OTP SMS is enabled on the organization of the user + // Given the user has only OTP SMS configured as second factor + // User enters username + // User enters password + // User receives a sms with a verification code + // User enters the code into the ui + // User is redirected to the app (default redirect url) + await loginWithPasswordAndPhoneOTP(page, user.getUsername(), user.getPassword(), user.getPhone()); + await loginScreenExpect(page, user.getFullName()); +}); + +test.skip("DOESN'T WORK: username, password and OTP SMS login, resend code", async ({ user, page }) => { + // Given OTP SMS is enabled on the organization of the user + // Given the user has only OTP SMS configured as second factor + // User enters username + // User enters password + // User receives a sms with a verification code + // User clicks resend code + // User receives a new sms with a verification code + // User is redirected to the app (default redirect url) + await loginWithPasswordAndPhoneOTP(page, user.getUsername(), user.getPassword(), user.getPhone()); + await loginScreenExpect(page, user.getFullName()); +}); + +test("username, password and OTP SMS login, wrong code", async ({ user, page }) => { + // Given OTP SMS is enabled on the organization of the user + // Given the user has only OTP SMS configured as second factor + // User enters username + // User enters password + // User receives a sms with a verification code + // User enters a wrong code + // Error message - "Invalid code" is shown + const c = "wrongcode"; + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await code(page, c); + await codeScreenExpect(page, c); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-set.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-set.spec.ts new file mode 100644 index 0000000..06ce42f --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-set.spec.ts @@ -0,0 +1,52 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { loginScreenExpect, loginWithPassword, startLogin } from "./login"; +import { loginname } from "./loginname"; +import { resetPassword, startResetPassword } from "./password"; +import { resetPasswordScreen, resetPasswordScreenExpect } from "./password-screen"; +import { PasswordUser } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUser }>({ + user: async ({ page }, use) => { + const user = new PasswordUser({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + password: "Password1!", + passwordChangeRequired: false, + }); + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("username and password set login", async ({ user, page }) => { + const changedPw = "ChangedPw1!"; + await startLogin(page); + await loginname(page, user.getUsername()); + await resetPassword(page, user.getUsername(), changedPw); + await loginScreenExpect(page, user.getFullName()); + + await loginWithPassword(page, user.getUsername(), changedPw); + await loginScreenExpect(page, user.getFullName()); +}); + +test("password set not with desired complexity", async ({ user, page }) => { + const changedPw1 = "change"; + const changedPw2 = "chang"; + await startLogin(page); + await loginname(page, user.getUsername()); + await startResetPassword(page); + await resetPasswordScreen(page, user.getUsername(), changedPw1, changedPw2); + await resetPasswordScreenExpect(page, changedPw1, changedPw2, false, false, false, false, true, false); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-totp.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-totp.spec.ts new file mode 100644 index 0000000..e495b16 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-totp.spec.ts @@ -0,0 +1,71 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { code } from "./code"; +import { codeScreenExpect } from "./code-screen"; +import { loginScreenExpect, loginWithPassword, loginWithPasswordAndTOTP } from "./login"; +import { PasswordUserWithTOTP } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUserWithTOTP; sink: any }>({ + user: async ({ page }, use) => { + const user = new PasswordUserWithTOTP({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number({ style: "international" }), + isPhoneVerified: true, + password: "Password1!", + passwordChangeRequired: false, + }); + + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("username, password and totp login", async ({ user, page }) => { + // Given totp is enabled on the organization of the user + // Given the user has only totp configured as second factor + // User enters username + // User enters password + // Screen for entering the code is shown directly + // User enters the code into the ui + // User is redirected to the app (default redirect url) + await loginWithPasswordAndTOTP(page, user.getUsername(), user.getPassword(), user.getSecret()); + await loginScreenExpect(page, user.getFullName()); +}); + +test("username, password and totp otp login, wrong code", async ({ user, page }) => { + // Given totp is enabled on the organization of the user + // Given the user has only totp configured as second factor + // User enters username + // User enters password + // Screen for entering the code is shown directly + // User enters a wrond code + // Error message - "Invalid code" is shown + const c = "wrongcode"; + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await code(page, c); + await codeScreenExpect(page, c); +}); + +test("username, password and totp login, multiple mfa options", async ({ page }) => { + test.skip(); + // Given totp and email otp is enabled on the organization of the user + // Given the user has totp and email otp configured as second factor + // User enters username + // User enters password + // Screen for entering the code is shown directly + // Button to switch to email otp is shown + // User clicks button to use email otp instead + // User receives an email with a verification code + // User enters code in ui + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password-u2f.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password-u2f.spec.ts new file mode 100644 index 0000000..dc23064 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password-u2f.spec.ts @@ -0,0 +1,26 @@ +import { test } from "@playwright/test"; + +test("username, password and u2f login", async ({ page }) => { + test.skip(); + // Given u2f is enabled on the organization of the user + // Given the user has only u2f configured as second factor + // User enters username + // User enters password + // Popup for u2f is directly opened + // User verifies u2f + // User is redirected to the app (default redirect url) +}); + +test("username, password and u2f login, multiple mfa options", async ({ page }) => { + test.skip(); + // Given u2f and semailms otp is enabled on the organization of the user + // Given the user has u2f and email otp configured as second factor + // User enters username + // User enters password + // Popup for u2f is directly opened + // User aborts u2f verification + // User clicks button to use email otp as second factor + // User receives an email with a verification code + // User enters code in ui + // User is redirected to the app (default redirect url) +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/username-password.spec.ts b/auth/ui/v2/apps/login/acceptance/tests/username-password.spec.ts new file mode 100644 index 0000000..ceb340f --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/username-password.spec.ts @@ -0,0 +1,157 @@ +import { faker } from "@faker-js/faker"; +import { test as base } from "@playwright/test"; +import dotenv from "dotenv"; +import path from "path"; +import { loginScreenExpect, loginWithPassword, startLogin } from "./login"; +import { loginname } from "./loginname"; +import { loginnameScreenExpect } from "./loginname-screen"; +import { password } from "./password"; +import { passwordScreenExpect } from "./password-screen"; +import { PasswordUser } from "./user"; + +// Read from ".env" file. +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +const test = base.extend<{ user: PasswordUser }>({ + user: async ({ page }, use) => { + const user = new PasswordUser({ + email: faker.internet.email(), + isEmailVerified: true, + firstName: faker.person.firstName(), + lastName: faker.person.lastName(), + organization: "", + phone: faker.phone.number(), + isPhoneVerified: false, + password: "Password1!", + passwordChangeRequired: false, + }); + await user.ensure(page); + await use(user); + await user.cleanup(); + }, +}); + +test("username and password login", async ({ user, page }) => { + await loginWithPassword(page, user.getUsername(), user.getPassword()); + await loginScreenExpect(page, user.getFullName()); +}); + +test("username and password login, unknown username", async ({ page }) => { + const username = "unknown"; + await startLogin(page); + await loginname(page, username); + await loginnameScreenExpect(page, username); +}); + +test("username and password login, wrong password", async ({ user, page }) => { + await startLogin(page); + await loginname(page, user.getUsername()); + await password(page, "wrong"); + await passwordScreenExpect(page, "wrong"); +}); + +test("username and password login, wrong username, ignore unknown usernames", async ({ user, page }) => { + test.skip(); + // Given user doesn't exist but ignore unknown usernames setting is set to true + // Given username password login is enabled on the users organization + // enter login name + // enter password + // redirect to loginname page --> error message username or password wrong +}); + +test("username and password login, initial password change", async ({ user, page }) => { + test.skip(); + // Given user is created and has changePassword set to true + // Given username password login is enabled on the users organization + // enter login name + // enter password + // create new password +}); + +test("username and password login, reset password hidden", async ({ user, page }) => { + test.skip(); + // Given the organization has enabled "Password reset hidden" in the login policy + // Given username password login is enabled on the users organization + // enter login name + // password reset link should not be shown on password screen +}); + +test("username and password login, reset password - enter code manually", async ({ user, page }) => { + test.skip(); + // Given user has forgotten password and clicks the forgot password button + // Given username password login is enabled on the users organization + // enter login name + // click password forgotten + // enter code from email + // user is redirected to app (default redirect url) +}); + +test("username and password login, reset password - click link", async ({ user, page }) => { + test.skip(); + // Given user has forgotten password and clicks the forgot password button, and then the link in the email + // Given username password login is enabled on the users organization + // enter login name + // click password forgotten + // click link in email + // set new password + // redirect to app (default redirect url) +}); + +test("username and password login, reset password, resend code", async ({ user, page }) => { + test.skip(); + // Given user has forgotten password and clicks the forgot password button and then resend code + // Given username password login is enabled on the users organization + // enter login name + // click password forgotten + // click resend code + // enter code from second email + // user is redirected to app (default redirect url) +}); + +test("email login enabled", async ({ user, page }) => { + test.skip(); + // Given user with the username "testuser", email test@zitadel.com and phone number 0711111111 exists + // Given no other user with the same email address exists + // enter email address "test@zitadel.com " in login screen + // user will get to password screen +}); + +test("email login disabled", async ({ user, page }) => { + test.skip(); + // Given user with the username "testuser", email test@zitadel.com and phone number 0711111111 exists + // Given no other user with the same email address exists + // enter email address "test@zitadel.com" in login screen + // user will see error message "user not found" +}); + +test("email login enabled - multiple users", async ({ user, page }) => { + test.skip(); + // Given user with the username "testuser", email test@zitadel.com and phone number 0711111111 exists + // Given a second user with the username "testuser2", email test@zitadel.com and phone number 0711111111 exists + // enter email address "test@zitadel.com" in login screen + // user will see error message "user not found" +}); + +test("phone login enabled", async ({ user, page }) => { + test.skip(); + // Given user with the username "testuser", email test@zitadel.com and phone number 0711111111 exists + // Given no other user with the same phon number exists + // enter phone number "0711111111" in login screen + // user will get to password screen +}); + +test("phone login disabled", async ({ user, page }) => { + test.skip(); + // Given user with the username "testuser", email test@zitadel.com and phone number 0711111111 exists + // Given no other user with the same phone number exists + // enter phone number "0711111111" in login screen + // user will see error message "user not found" +}); + +test("phone login enabled - multiple users", async ({ user, page }) => { + test.skip(); + // Given user with the username "testuser", email test@zitadel.com and phone number 0711111111 exists + // Given a second user with the username "testuser2", email test@zitadel.com and phone number 0711111111 exists + // enter phone number "0711111111" in login screen + // user will see error message "user not found" +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/welcome.ts b/auth/ui/v2/apps/login/acceptance/tests/welcome.ts new file mode 100644 index 0000000..34267c2 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/welcome.ts @@ -0,0 +1,6 @@ +import { test } from "@playwright/test"; + +test("login is accessible", async ({ page }) => { + await page.goto("./"); + await page.getByRole("heading", { name: "Welcome back!" }).isVisible(); +}); diff --git a/auth/ui/v2/apps/login/acceptance/tests/zitadel.ts b/auth/ui/v2/apps/login/acceptance/tests/zitadel.ts new file mode 100644 index 0000000..b252654 --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/tests/zitadel.ts @@ -0,0 +1,190 @@ +import { Authenticator } from "@otplib/core"; +import { createDigest, createRandomBytes } from "@otplib/plugin-crypto"; +import { keyDecoder, keyEncoder } from "@otplib/plugin-thirty-two"; // use your chosen base32 plugin +import axios from "axios"; +import dotenv from "dotenv"; +import { request } from "gaxios"; +import path from "path"; +import { OtpType, userProps } from "./user"; + +dotenv.config({ path: path.resolve(__dirname, "../../login/.env.test.local") }); + +export async function addUser(props: userProps) { + const body = { + username: props.email, + organization: { + orgId: props.organization, + }, + profile: { + givenName: props.firstName, + familyName: props.lastName, + }, + email: { + email: props.email, + isVerified: true, + }, + phone: { + phone: props.phone, + isVerified: true, + }, + password: { + password: props.password, + changeRequired: props.passwordChangeRequired ?? false, + }, + }; + if (!props.isEmailVerified) { + delete body.email.isVerified; + } + if (!props.isPhoneVerified) { + delete body.phone.isVerified; + } + + return await listCall(`${process.env.ZITADEL_API_URL}/v2/users/human`, body); +} + +export async function removeUserByUsername(username: string) { + const resp = await getUserByUsername(username); + if (!resp || !resp.result || !resp.result[0]) { + return; + } + await removeUser(resp.result[0].userId); +} + +export async function removeUser(id: string) { + await deleteCall(`${process.env.ZITADEL_API_URL}/v2/users/${id}`); +} + +async function deleteCall(url: string) { + try { + const response = await axios.delete(url, { + headers: { + Authorization: `Bearer ${process.env.ZITADEL_ADMIN_TOKEN}`, + }, + }); + + if (response.status >= 400 && response.status !== 404) { + const error = `HTTP Error: ${response.status} - ${response.statusText}`; + console.error(error); + throw new Error(error); + } + } catch (error) { + console.error("Error making request:", error); + throw error; + } +} + +export async function getUserByUsername(username: string): Promise { + const listUsersBody = { + queries: [ + { + userNameQuery: { + userName: username, + }, + }, + ], + }; + + return await listCall(`${process.env.ZITADEL_API_URL}/v2/users`, listUsersBody); +} + +async function listCall(url: string, data: any): Promise { + try { + const response = await axios.post(url, data, { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.ZITADEL_ADMIN_TOKEN}`, + }, + }); + + if (response.status >= 400) { + const error = `HTTP Error: ${response.status} - ${response.statusText}`; + console.error(error); + throw new Error(error); + } + + return response.data; + } catch (error) { + console.error("Error making request:", error); + throw error; + } +} + +export async function activateOTP(userId: string, type: OtpType) { + let url = "otp_"; + switch (type) { + case OtpType.sms: + url = url + "sms"; + break; + case OtpType.email: + url = url + "email"; + break; + } + + await pushCall(`${process.env.ZITADEL_API_URL}/v2/users/${userId}/${url}`, {}); +} + +async function pushCall(url: string, data: any) { + try { + const response = await axios.post(url, data, { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.ZITADEL_ADMIN_TOKEN}`, + }, + }); + + if (response.status >= 400) { + const error = `HTTP Error: ${response.status} - ${response.statusText}`; + console.error(error); + throw new Error(error); + } + } catch (error) { + console.error("Error making request:", error); + throw error; + } +} + +export async function addTOTP(userId: string): Promise { + const response = await listCall(`${process.env.ZITADEL_API_URL}/v2/users/${userId}/totp`, {}); + const code = totp(response.secret); + await pushCall(`${process.env.ZITADEL_API_URL}/v2/users/${userId}/totp/verify`, { code: code }); + return response.secret; +} + +export function totp(secret: string) { + const authenticator = new Authenticator({ + createDigest, + createRandomBytes, + keyDecoder, + keyEncoder, + }); + // google authenticator usage + const token = authenticator.generate(secret); + + // check if token can be used + if (!authenticator.verify({ token: token, secret: secret })) { + const error = `Generated token could not be verified`; + console.error(error); + throw new Error(error); + } + + return token; +} + +export async function eventualNewUser(id: string) { + return request({ + url: `${process.env.ZITADEL_API_URL}/v2/users/${id}`, + method: "GET", + headers: { + Authorization: `Bearer ${process.env.ZITADEL_ADMIN_TOKEN}`, + "Content-Type": "application/json", + }, + retryConfig: { + statusCodesToRetry: [[404, 404]], + retry: Number.MAX_SAFE_INTEGER, // totalTimeout limits the number of retries + totalTimeout: 10000, // 10 seconds + onRetryAttempt: (error) => { + console.warn(`Retrying to query new user ${id}: ${error.message}`); + }, + }, + }); +} diff --git a/auth/ui/v2/apps/login/acceptance/zitadel.yaml b/auth/ui/v2/apps/login/acceptance/zitadel.yaml new file mode 100644 index 0000000..ab718bf --- /dev/null +++ b/auth/ui/v2/apps/login/acceptance/zitadel.yaml @@ -0,0 +1,65 @@ +ExternalSecure: false +TLS.Enabled: false + +FirstInstance: + PatPath: /pat/zitadel-admin-sa.pat + Org: + Human: + UserName: zitadel-admin + FirstName: ZITADEL + LastName: Admin + Password: Password1! + PasswordChangeRequired: false + PreferredLanguage: en + Machine: + Machine: + Username: zitadel-admin-sa + Name: Admin + Pat.ExpirationDate: 2099-01-01T00:00:00Z + LoginClient: + Machine: + Username: login-client-sa + Name: Login Client + Pat.ExpirationDate: 2099-01-01T00:00:00Z + +DefaultInstance: + LoginPolicy: + AllowUsernamePassword: true # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_ALLOWUSERNAMEPASSWORD + AllowRegister: true # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_ALLOWREGISTER + AllowExternalIDP: true # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_ALLOWEXTERNALIDP + ForceMFA: false # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_FORCEMFA + HidePasswordReset: false # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_HIDEPASSWORDRESET + IgnoreUnknownUsernames: false # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_IGNOREUNKNOWNUSERNAMES + AllowDomainDiscovery: true # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_ALLOWDOMAINDISCOVERY + # 1 is allowed, 0 is not allowed + PasswordlessType: 1 # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_PASSWORDLESSTYPE + # DefaultRedirectURL is empty by default because we use the Management Console UI + DefaultRedirectURI: # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_DEFAULTREDIRECTURI + # 240h = 10d + PasswordCheckLifetime: 240h # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_PASSWORDCHECKLIFETIME + # 240h = 10d + ExternalLoginCheckLifetime: 240h # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_EXTERNALLOGINCHECKLIFETIME + # 720h = 30d + MfaInitSkipLifetime: 0h # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_MFAINITSKIPLIFETIME + SecondFactorCheckLifetime: 18h # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_SECONDFACTORCHECKLIFETIME + MultiFactorCheckLifetime: 12h # ZITADEL_DEFAULTINSTANCE_LOGINPOLICY_MULTIFACTORCHECKLIFETIME + PrivacyPolicy: + TOSLink: "https://zitadel.com/docs/legal/terms-of-service" + PrivacyLink: "https://zitadel.com/docs/legal/policies/privacy-policy" + HelpLink: "https://zitadel.com/docs" + SupportEmail: "support@zitadel.com" + DocsLink: "https://zitadel.com/docs" + +Database: + EventPushConnRatio: 0.2 # 4 + ProjectionSpoolerConnRatio: 0.3 # 6 + postgres: + Host: db + MaxOpenConns: 20 + MaxIdleConns: 20 + MaxConnLifetime: 1h + MaxConnIdleTime: 5m + User.Password: zitadel + +Logstore.Access.Stdout.Enabled: true +Log.Formatter.Format: json \ No newline at end of file diff --git a/auth/ui/v2/apps/login/checks/eslint-module-boundaries.mjs b/auth/ui/v2/apps/login/checks/eslint-module-boundaries.mjs new file mode 100644 index 0000000..26003a0 --- /dev/null +++ b/auth/ui/v2/apps/login/checks/eslint-module-boundaries.mjs @@ -0,0 +1,82 @@ +// Keeps Server Actions and server-only code in separate, recognizable places. +// +// - src/lib/actions/: only Server Actions. Every file starts with "use server", and every export is a +// public, unauthenticated endpoint, so its arguments must be treated as attacker-controlled. +// - src/lib/server/: server-only code. Every file imports "server-only" and none is a Server Action. +// - "use server" is not allowed anywhere else, neither as a file directive nor inline in a function. +// - Client components must not import from src/lib/server/. +// +// The build additionally checks the published actions against checks/server-actions.allowlist.json. + +const ACTIONS_DIR = "/src/lib/actions/"; +const SERVER_DIR = "/src/lib/server/"; +const SERVER_IMPORT = /^@\/lib\/server(\/|$)/; + +function directivesOf(program) { + return program.body + .filter((statement) => statement.type === "ExpressionStatement" && typeof statement.directive === "string") + .map((statement) => statement.directive); +} + +const moduleBoundaries = { + meta: { + type: "problem", + docs: { description: "Keep Server Actions in src/lib/actions and server-only code in src/lib/server" }, + messages: { + useServerOutsideActions: + '"use server" is only allowed in src/lib/actions/. Every export of such a module is a public endpoint; put the action there and the implementation in src/lib/server/.', + missingUseServer: 'Files in src/lib/actions/ must start with "use server".', + missingServerOnly: 'Files in src/lib/server/ must import "server-only".', + serverImportInClient: + "Client components must not import from src/lib/server/. Call a Server Action from src/lib/actions/ instead.", + }, + schema: [], + }, + create(context) { + const filename = context.filename.replaceAll("\\", "/"); + const isTest = /\.test\.tsx?$/.test(filename); + const inActions = filename.includes(ACTIONS_DIR); + const inServer = filename.includes(SERVER_DIR); + + return { + Program(program) { + if (isTest) { + return; + } + + const directives = directivesOf(program); + + if (inActions && !directives.includes("use server")) { + context.report({ node: program, messageId: "missingUseServer" }); + } + + if ( + inServer && + !program.body.some((statement) => statement.type === "ImportDeclaration" && statement.source.value === "server-only") + ) { + context.report({ node: program, messageId: "missingServerOnly" }); + } + + if (directives.includes("use client")) { + for (const statement of program.body) { + if (statement.type === "ImportDeclaration" && SERVER_IMPORT.test(statement.source.value)) { + context.report({ node: statement, messageId: "serverImportInClient" }); + } + } + } + }, + // file-level and function-level directives are both ExpressionStatements with a `directive` + "ExpressionStatement[directive='use server']"(node) { + if (!inActions) { + context.report({ node, messageId: "useServerOutsideActions" }); + } + }, + }; + }, +}; + +export default { + rules: { + "module-boundaries": moduleBoundaries, + }, +}; diff --git a/auth/ui/v2/apps/login/checks/server-actions.allowlist.json b/auth/ui/v2/apps/login/checks/server-actions.allowlist.json new file mode 100644 index 0000000..a62062b --- /dev/null +++ b/auth/ui/v2/apps/login/checks/server-actions.allowlist.json @@ -0,0 +1,58 @@ +{ + "src/lib/actions/device.ts": [ + "approveDeviceAuthorization", + "denyDeviceAuthorization" + ], + "src/lib/actions/flow.ts": [ + "completeFlowOrGetUrl" + ], + "src/lib/actions/idp-intent.ts": [ + "processIDPCallback" + ], + "src/lib/actions/idp.ts": [ + "createNewSessionForLDAP", + "redirectToIdp" + ], + "src/lib/actions/language.ts": [ + "setLanguageCookie" + ], + "src/lib/actions/loginname.ts": [ + "sendLoginname" + ], + "src/lib/actions/oidc.ts": [ + "getDeviceAuthorizationRequest" + ], + "src/lib/actions/otp.ts": [ + "addOTP" + ], + "src/lib/actions/passkeys.ts": [ + "registerPasskeyLink", + "sendPasskey", + "verifyPasskeyRegistration" + ], + "src/lib/actions/password.ts": [ + "changePassword", + "checkSessionAndSetPassword", + "resetPassword", + "sendPassword" + ], + "src/lib/actions/register.ts": [ + "registerUser", + "registerUserAndLinkToIDP" + ], + "src/lib/actions/session.ts": [ + "clearSession", + "continueWithSession", + "skipMFAAndContinueWithNextUrl", + "updateOrCreateSession" + ], + "src/lib/actions/u2f.ts": [ + "addU2F", + "verifyU2F" + ], + "src/lib/actions/verify.ts": [ + "resendVerification", + "sendVerification", + "verifyTOTP" + ] +} diff --git a/auth/ui/v2/apps/login/checks/server-actions.mjs b/auth/ui/v2/apps/login/checks/server-actions.mjs new file mode 100644 index 0000000..91e1e96 --- /dev/null +++ b/auth/ui/v2/apps/login/checks/server-actions.mjs @@ -0,0 +1,77 @@ +#!/usr/bin/env node +// Fails the build when a published Server Action lives outside src/lib/actions/, or when the set of +// published Server Actions differs from server-actions.allowlist.json. +// +// Next.js publishes every export of a "use server" module that the build graph reaches as a public, +// unauthenticated POST endpoint, whether or not a client component calls it. Internal helpers that +// trust their arguments must therefore never end up in that set. Any change to it has to be a +// deliberate, reviewed edit of the allowlist. +// +// Usage: node checks/server-actions.mjs [path/to/server-reference-manifest.json] + +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const manifestPath = process.argv[2] ?? join(here, "..", ".next", "server", "server-reference-manifest.json"); +const allowlistPath = join(here, "server-actions.allowlist.json"); +const ACTIONS_DIR = "src/lib/actions/"; + +function normalizeFilename(filename) { + // the manifest stores paths relative to the workspace root (e.g. apps/login/src/lib/actions/flow.ts) + const index = filename.indexOf("src/"); + return index === -1 ? filename : filename.slice(index); +} + +function published(manifest) { + const actions = new Set(); + for (const runtime of ["node", "edge"]) { + for (const entry of Object.values(manifest[runtime] ?? {})) { + actions.add(`${normalizeFilename(entry.filename)}#${entry.exportedName}`); + } + } + return actions; +} + +function allowed(allowlist) { + const actions = new Set(); + for (const [filename, names] of Object.entries(allowlist)) { + for (const name of names) { + actions.add(`${filename}#${name}`); + } + } + return actions; +} + +const actual = published(JSON.parse(readFileSync(manifestPath, "utf8"))); +const expected = allowed(JSON.parse(readFileSync(allowlistPath, "utf8"))); + +const outsideActionsDir = [...actual].filter((action) => !action.startsWith(ACTIONS_DIR)).sort(); +const unexpected = [...actual].filter((action) => !expected.has(action)).sort(); +const missing = [...expected].filter((action) => !actual.has(action)).sort(); + +if (outsideActionsDir.length || unexpected.length || missing.length) { + if (outsideActionsDir.length) { + console.error(`These Server Actions are published from outside ${ACTIONS_DIR}:`); + outsideActionsDir.forEach((action) => console.error(` ! ${action}`)); + console.error( + `Only modules in ${ACTIONS_DIR} may use "use server". Move the implementation to src/lib/server/ (import "server-only").`, + ); + } + if (unexpected.length) { + console.error("These exports are published as Server Actions but are not in checks/server-actions.allowlist.json:"); + unexpected.forEach((action) => console.error(` + ${action}`)); + console.error( + 'Every argument of a Server Action is attacker-controlled. Move internal helpers to a module without "use server"', + '(add import "server-only"), or add the action to the allowlist after reviewing that it derives identity and policy on the server.', + ); + } + if (missing.length) { + console.error("These allowlisted Server Actions are no longer published, remove them from the allowlist:"); + missing.forEach((action) => console.error(` - ${action}`)); + } + process.exit(1); +} + +console.log(`Server Actions match the allowlist (${actual.size} published).`); diff --git a/auth/ui/v2/apps/login/constants/csp.js b/auth/ui/v2/apps/login/constants/csp.js new file mode 100644 index 0000000..b488563 --- /dev/null +++ b/auth/ui/v2/apps/login/constants/csp.js @@ -0,0 +1,2 @@ +export const DEFAULT_CSP = + "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self'; frame-ancestors 'none'; object-src 'none'"; diff --git a/auth/ui/v2/apps/login/dockerized/await-api/await-api.integration.test.ts b/auth/ui/v2/apps/login/dockerized/await-api/await-api.integration.test.ts new file mode 100644 index 0000000..d334095 --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/await-api/await-api.integration.test.ts @@ -0,0 +1,176 @@ +import * as path from "path"; +import { fileURLToPath } from "node:url"; +import type { StartedNetwork } from "testcontainers"; +import { GenericContainer, Network, Wait, type StartedTestContainer } from "testcontainers"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const TEST_DIR = path.dirname(fileURLToPath(import.meta.url)); +const LOGIN_APP_DIR = path.join(TEST_DIR, "../.."); +const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`; + +const DOCKER_TIMEOUT = 180_000; + +/** + * Integration tests for ZITADEL_API_AWAITINITIALCONN support. + * + * When this environment variable is set (e.g. "30s", "5m"), the login + * container polls the ZITADEL API's /debug/ready endpoint before starting + * the Next.js server. This replaces the wait4x init container that was + * previously used in the Helm chart. + * + * The test suite uses a mock Zitadel server that returns 503 on /debug/ready + * for a configurable duration before switching to 200. Three scenarios are + * verified: the API becomes ready within the timeout, the timeout expires + * before the API is ready, and the variable is not set at all. + */ +describe("ZITADEL_API_AWAITINITIALCONN", () => { + beforeAll(async () => { + await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG); + }, DOCKER_TIMEOUT); + + describe("when the API becomes ready before the timeout", () => { + let network: StartedNetwork; + let mockZitadel: StartedTestContainer; + let container: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + network = await new Network().start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([ + { source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }, + ]) + .withEnvironment({ PORT: "8080", READY_AFTER_MS: "5000" }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + container = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + ZITADEL_API_AWAITINITIALCONN: "60s", + }) + .withStartupTimeout(120_000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${container.getHost()}:${container.getMappedPort(3000)}`; + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await container?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it("starts successfully after the API becomes ready", async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.status).toBe(200); + }); + }); + + describe("when the API does not become ready before the timeout", () => { + let network: StartedNetwork; + let mockZitadel: StartedTestContainer; + let container: StartedTestContainer; + + beforeAll(async () => { + network = await new Network().start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([ + { source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }, + ]) + .withEnvironment({ PORT: "8080", READY_AFTER_MS: "600000" }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + container = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + ZITADEL_API_AWAITINITIALCONN: "5s", + }) + .withStartupTimeout(30_000) + .withWaitStrategy(Wait.forLogMessage(/Timed out after 5s/)) + .start(); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await container?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it("logs the timeout error before exiting", async () => { + const stream = await container.logs(); + const logs = await new Promise((resolve) => { + let output = ""; + stream.on("data", (chunk: Buffer) => { output += chunk.toString(); }); + stream.on("end", () => resolve(output)); + setTimeout(() => { stream.destroy(); resolve(output); }, 5_000); + }); + expect(logs).toContain("Timed out after 5s waiting for API readiness"); + }); + }); + + describe("when the variable is not set", () => { + let network: StartedNetwork; + let mockZitadel: StartedTestContainer; + let container: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + network = await new Network().start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([ + { source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }, + ]) + .withEnvironment({ PORT: "8080", READY_AFTER_MS: "0" }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + container = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + }) + .withStartupTimeout(120_000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${container.getHost()}:${container.getMappedPort(3000)}`; + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await container?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it("starts without waiting", async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.status).toBe(200); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/dockerized/await-api/mock-zitadel-server.js b/auth/ui/v2/apps/login/dockerized/await-api/mock-zitadel-server.js new file mode 100644 index 0000000..d20fccd --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/await-api/mock-zitadel-server.js @@ -0,0 +1,66 @@ +/** + * Mock Zitadel server for testing ZITADEL_API_AWAITINITIALCONN. + * + * Returns 503 on /debug/ready until READY_AFTER_MS milliseconds have elapsed, + * then switches to 200. All other endpoints return minimal ConnectRPC-compatible + * responses so the login app can start normally once the readiness gate passes. + */ +const http = require("http"); + +const PORT = process.env.PORT || 8080; +const READY_AFTER_MS = parseInt(process.env.READY_AFTER_MS || "5000", 10); + +const startTime = Date.now(); + +const sendResponse = (res, statusCode, body) => { + res.writeHead(statusCode, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); +}; + +const server = http.createServer((req, res) => { + const { method, url } = req; + console.log(`[${new Date().toISOString()}] ${method} ${url}`); + + if (url === "/debug/ready") { + const elapsed = Date.now() - startTime; + if (elapsed < READY_AFTER_MS) { + console.log(` -> 503 (not ready, ${elapsed}ms / ${READY_AFTER_MS}ms)`); + sendResponse(res, 503, { status: "not ready" }); + } else { + console.log(` -> 200 (ready after ${elapsed}ms)`); + sendResponse(res, 200, { status: "ok" }); + } + return; + } + + if (url.includes("GetLoginSettings") || url.includes("SettingsService")) { + sendResponse(res, 200, { settings: {} }); + } else if (url.includes("GetBrandingSettings")) { + sendResponse(res, 200, { settings: {} }); + } else if (url.includes("SessionService") || url.includes("Session")) { + sendResponse(res, 200, { session: {} }); + } else if (url.includes("UserService") || url.includes("User")) { + sendResponse(res, 200, { user: {} }); + } else if (url.includes("OrganizationService") || url.includes("Organization")) { + sendResponse(res, 200, { result: [] }); + } else if (url.includes("IdentityProviderService") || url.includes("IdentityProvider")) { + sendResponse(res, 200, { identityProviders: [] }); + } else { + sendResponse(res, 200, {}); + } +}); + +server.on("error", (err) => console.error("Server error:", err)); + +server.listen(PORT, "0.0.0.0", () => { + console.log(`Mock Zitadel server listening on port ${PORT}`); + console.log(`Will become ready after ${READY_AFTER_MS}ms`); +}); + +process.on("SIGTERM", () => { + console.log("Shutting down mock server..."); + server.close(() => { + console.log("Mock server stopped"); + process.exit(0); + }); +}); diff --git a/auth/ui/v2/apps/login/dockerized/ca/ca.integration.test.ts b/auth/ui/v2/apps/login/dockerized/ca/ca.integration.test.ts new file mode 100644 index 0000000..9c857fb --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/ca/ca.integration.test.ts @@ -0,0 +1,182 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { + GenericContainer, + type StartedTestContainer, + Network, + Wait, +} from "testcontainers"; +import type { StartedNetwork } from "testcontainers"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { generateCertificates } from "./utils/tls.ts"; + +const TEST_DIR = path.dirname(new URL(import.meta.url).pathname); +const LOGIN_APP_DIR = path.join(TEST_DIR, "../.."); + +const SMOCKER_MOCK_PORT = 443; +const SMOCKER_ADMIN_PORT = 8081; + +/** + * Integration tests for custom CA certificate support in the login application. + * + * These tests verify that the Dockerfile correctly configures Node.js to trust + * custom Certificate Authorities via SSL_CERT_FILE, SSL_CERT_DIR, and the + * load-ssl-cert-dir.cjs preload script. + * + * OpenSSL (used by Node with --use-openssl-ca) only reads certs from + * SSL_CERT_DIR when they have hashed filenames (e.g. "9d66eef0.0"). Go's + * crypto/x509 reads any file. The preload script bridges this gap so that + * operators get the same behaviour with both the Go backend and the login + * container. + * + * We use Smocker as a TLS server whose certificate is signed by a test CA + * that is NOT in the system trust store. Each test block configures the + * login container differently and asserts whether the TLS handshake to + * Smocker succeeds or fails — verifying actual trust-store behaviour, not + * just environment variable values. + */ +const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`; + +async function testTlsConnection( + container: StartedTestContainer, + url: string, +): Promise<{ exitCode: number; output: string }> { + return container.exec([ + "node", + "-e", + `fetch('${url}').then(() => process.exit(0)).catch(() => process.exit(1))`, + ]); +} + +describe("Custom CA Certificate Integration", () => { + let network: StartedNetwork; + let mockServer: StartedTestContainer; + let certsDir: string; + + beforeAll(async () => { + certsDir = fs.mkdtempSync(path.join(os.tmpdir(), "ca-test-certs-")); + + const certs = generateCertificates(); + fs.writeFileSync(path.join(certsDir, "ca.crt"), certs.ca.cert); + fs.writeFileSync(path.join(certsDir, "server.key"), certs.server.key); + fs.writeFileSync(path.join(certsDir, "server.crt"), certs.server.cert); + + network = await new Network().start(); + + mockServer = await new GenericContainer("ghcr.io/smocker-dev/smocker") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withBindMounts([{ source: certsDir, target: "/certs", mode: "ro" }]) + .withEnvironment({ + SMOCKER_MOCK_SERVER_LISTEN_PORT: "443", + SMOCKER_CONFIG_LISTEN_PORT: "8081", + SMOCKER_TLS_ENABLE: "true", + SMOCKER_TLS_CERT_FILE: "/certs/server.crt", + SMOCKER_TLS_PRIVATE_KEY_FILE: "/certs/server.key", + }) + .withExposedPorts(SMOCKER_MOCK_PORT, SMOCKER_ADMIN_PORT) + .withStartupTimeout(120_000) + .withWaitStrategy(Wait.forLogMessage(/Starting mock server/)) + .start(); + + try { + await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG); + } catch (err) { + throw new Error(`Failed to build login Docker image: ${err instanceof Error ? err.message : err}`); + } + }, 180_000); + + afterAll(async () => { + await mockServer?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }); + + describe("when custom CA is provided via SSL_CERT_FILE", () => { + let container: StartedTestContainer; + + beforeAll(async () => { + container = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + SSL_CERT_FILE: "/etc/ssl/certs/custom-ca.crt", + }) + .withCopyFilesToContainer([ + { + source: path.join(certsDir, "ca.crt"), + target: "/etc/ssl/certs/custom-ca.crt", + }, + ]) + .withStartupTimeout(180_000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + }, 180_000); + + afterAll(async () => { + await container?.stop().catch(() => {}); + }); + + it("can establish TLS connection to server with custom CA", async () => { + const result = await testTlsConnection(container, "https://mock-zitadel/"); + expect(result.exitCode).toBe(0); + }); + }); + + describe("when custom CA is provided via SSL_CERT_DIR (non-hashed filename)", () => { + let container: StartedTestContainer; + let customCaDir: string; + + beforeAll(async () => { + customCaDir = fs.mkdtempSync(path.join(os.tmpdir(), "ca-dir-test-")); + fs.writeFileSync(path.join(customCaDir, "corp-root.crt"), fs.readFileSync(path.join(certsDir, "ca.crt"))); + + container = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + SSL_CERT_DIR: "/custom-certs", + }) + .withCopyFilesToContainer([ + { + source: path.join(customCaDir, "corp-root.crt"), + target: "/custom-certs/corp-root.crt", + }, + ]) + .withStartupTimeout(180_000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + }, 180_000); + + afterAll(async () => { + await container?.stop().catch(() => {}); + }); + + it("can establish TLS connection with non-hashed cert in SSL_CERT_DIR", async () => { + const result = await testTlsConnection(container, "https://mock-zitadel/"); + expect(result.exitCode).toBe(0); + }); + }); + + describe("when custom CA certificate is not provided", () => { + let container: StartedTestContainer; + + beforeAll(async () => { + container = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withStartupTimeout(180_000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + }, 180_000); + + afterAll(async () => { + await container?.stop().catch(() => {}); + }); + + it("cannot establish TLS connection without custom CA", async () => { + const result = await testTlsConnection(container, "https://mock-zitadel/"); + expect(result.exitCode).not.toBe(0); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/dockerized/ca/utils/tls.ts b/auth/ui/v2/apps/login/dockerized/ca/utils/tls.ts new file mode 100644 index 0000000..75445ee --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/ca/utils/tls.ts @@ -0,0 +1,87 @@ +import forge from "node-forge"; + +/** + * Generates a self-signed CA certificate and a server certificate signed by + * that CA, returning both as PEM-encoded strings alongside their private keys. + * + * This is intended for test and development environments where a trusted + * certificate chain is needed without relying on the openssl binary. The + * server certificate includes Subject Alternative Names so that TLS clients + * can verify the connection against the expected hostnames and IP addresses. + */ +export function generateCertificates({ + caCN = "Test CA", + serverCN = "mock-zitadel", + dns = ["mock-zitadel", "localhost"], + ips = ["127.0.0.1"], + days = 1, +} = {}) { + function createCert({ + subject, + issuer, + publicKey, + signingKey, + extensions, + serial = "01", + }: { + subject: forge.pki.CertificateField[]; + issuer: forge.pki.CertificateField[]; + publicKey: forge.pki.rsa.PublicKey; + signingKey: forge.pki.rsa.PrivateKey; + extensions?: forge.pki.CertificateField[]; + serial?: string; + }) { + const cert = forge.pki.createCertificate(); + cert.publicKey = publicKey; + cert.serialNumber = serial; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(Date.now() + days * 86400000); + cert.setSubject(subject); + cert.setIssuer(issuer); + if (extensions) { + cert.setExtensions(extensions); + } + cert.sign(signingKey, forge.md.sha256.create()); + return forge.pki.certificateToPem(cert); + } + + const caKeys = forge.pki.rsa.generateKeyPair(2048); + const serverKeys = forge.pki.rsa.generateKeyPair(2048); + const caSubject = [{ name: "commonName", value: caCN }]; + + return { + ca: { + cert: createCert({ + subject: caSubject, + issuer: caSubject, + publicKey: caKeys.publicKey, + signingKey: caKeys.privateKey, + extensions: [{ name: "basicConstraints", cA: true }], + }), + key: forge.pki.privateKeyToPem(caKeys.privateKey), + }, + server: { + cert: createCert({ + subject: [{ name: "commonName", value: serverCN }], + issuer: caSubject, + publicKey: serverKeys.publicKey, + signingKey: caKeys.privateKey, + serial: "02", + extensions: [ + { + name: "subjectAltName", + altNames: [ + ...dns.map(function (value) { + return { type: 2, value }; + }), + ...ips.map(function (ip) { + return { type: 7, ip }; + }), + ], + }, + ], + }), + key: forge.pki.privateKeyToPem(serverKeys.privateKey), + }, + }; +} diff --git a/auth/ui/v2/apps/login/dockerized/otel/mock-zitadel-server.js b/auth/ui/v2/apps/login/dockerized/otel/mock-zitadel-server.js new file mode 100644 index 0000000..ffa63a8 --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/otel/mock-zitadel-server.js @@ -0,0 +1,107 @@ +/** + * Mock Zitadel ConnectRPC server for testing trace propagation. + * Captures incoming headers and writes them to a file for test assertions. + */ +const http = require("http"); +const fs = require("fs"); +const path = require("path"); + +const PORT = process.env.PORT || 8080; +const OUTPUT_DIR = process.env.OUTPUT_DIR || "/tmp/otel"; +const HEADERS_FILE = path.join(OUTPUT_DIR, "captured-headers.json"); + +/** + * Safely stringify a value to JSON with XSS-preventing character escapes. + * + * Escapes `<`, `>`, `&`, and `/` to their Unicode equivalents to prevent + * script injection when the output is reflected in HTTP responses or + * embedded in HTML contexts. + * + * @param {unknown} value - The value to stringify + * @returns {string} JSON string with dangerous characters escaped + */ +function safeJsonStringify(value) { + return JSON.stringify(value, null, 2) + .replace(//g, "\\u003e") + .replace(/&/g, "\\u0026") + .replace(/\//g, "\\/"); +} + +// Store captured requests +const capturedRequests = []; + +const server = http.createServer((req, res) => { + const { method, url } = req; + + // Capture trace headers + const traceHeaders = { + timestamp: new Date().toISOString(), + method, + url, + traceparent: req.headers["traceparent"] || null, + tracestate: req.headers["tracestate"] || null, + baggage: req.headers["baggage"] || null, + contentType: req.headers["content-type"] || null, + }; + + capturedRequests.push(traceHeaders); + + // Write to file for test assertions + fs.mkdirSync(OUTPUT_DIR, { recursive: true }); + fs.writeFileSync(HEADERS_FILE, JSON.stringify(capturedRequests, null, 2)); + + console.log(`[${traceHeaders.timestamp}] ${method} ${url}`); + console.log(` traceparent: ${traceHeaders.traceparent || "(none)"}`); + + const sendResponse = (statusCode, contentType, body) => { + res.writeHead(statusCode, { "Content-Type": contentType }); + res.end(body); + }; + + // Health check + if (url.includes("/health") || url === "/") { + sendResponse(200, "application/json", safeJsonStringify({ status: "ok" })); + return; + } + + // Return captured headers (for debugging) + if (url === "/captured-headers") { + sendResponse(200, "application/json", safeJsonStringify(capturedRequests)); + return; + } + + // Mock ConnectRPC responses + // These are minimal responses to prevent the login app from crashing + if (url.includes("GetLoginSettings") || url.includes("SettingsService")) { + sendResponse(200, "application/json", safeJsonStringify({ settings: {} })); + } else if (url.includes("GetBrandingSettings")) { + sendResponse(200, "application/json", safeJsonStringify({ settings: {} })); + } else if (url.includes("SessionService") || url.includes("Session")) { + sendResponse(200, "application/json", safeJsonStringify({ session: {} })); + } else if (url.includes("UserService") || url.includes("User")) { + sendResponse(200, "application/json", safeJsonStringify({ user: {} })); + } else if (url.includes("OrganizationService") || url.includes("Organization")) { + sendResponse(200, "application/json", safeJsonStringify({ result: [] })); + } else if (url.includes("IdentityProviderService") || url.includes("IdentityProvider")) { + sendResponse(200, "application/json", safeJsonStringify({ identityProviders: [] })); + } else { + sendResponse(200, "application/json", safeJsonStringify({})); + } +}); + +server.on("error", (err) => console.error("Server error:", err)); + +server.listen(PORT, "0.0.0.0", () => { + console.log(`Mock Zitadel server listening on port ${PORT}`); + console.log(`Captured headers will be written to: ${HEADERS_FILE}`); +}); + +// Graceful shutdown +process.on("SIGTERM", () => { + console.log("Shutting down mock server..."); + server.close(() => { + console.log("Mock server stopped"); + process.exit(0); + }); +}); diff --git a/auth/ui/v2/apps/login/dockerized/otel/otel-collector-config.yaml b/auth/ui/v2/apps/login/dockerized/otel/otel-collector-config.yaml new file mode 100644 index 0000000..550c6bf --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/otel/otel-collector-config.yaml @@ -0,0 +1,43 @@ +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + batch: + timeout: 1s + send_batch_size: 1024 + +exporters: + debug: + verbosity: detailed + file/traces: + path: /tmp/otel/traces.json + flush_interval: 1s + file/metrics: + path: /tmp/otel/metrics.json + flush_interval: 1s + file/logs: + path: /tmp/otel/logs.json + flush_interval: 1s + +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +service: + extensions: [health_check] + pipelines: + traces: + receivers: [otlp] + processors: [batch] + exporters: [debug, file/traces] + metrics: + receivers: [otlp] + processors: [batch] + exporters: [debug, file/metrics] + logs: + receivers: [otlp] + processors: [batch] + exporters: [debug, file/logs] diff --git a/auth/ui/v2/apps/login/dockerized/otel/otel.integration.test.ts b/auth/ui/v2/apps/login/dockerized/otel/otel.integration.test.ts new file mode 100644 index 0000000..7f1bd83 --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/otel/otel.integration.test.ts @@ -0,0 +1,1765 @@ +import * as fs from "fs"; +import * as path from "path"; +import type { StartedNetwork } from "testcontainers"; +import { GenericContainer, Network, Wait, type StartedTestContainer } from "testcontainers"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const TEST_DIR = path.dirname(new URL(import.meta.url).pathname); +const OUTPUT_DIR = path.join(TEST_DIR, "output"); +const LOGIN_APP_DIR = path.join(TEST_DIR, "../.."); + +const DOCKER_TIMEOUT = 180000; +const TEST_TIMEOUT = 30000; + +const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`; + +function readTraces(): string { + try { + return fs.readFileSync(path.join(OUTPUT_DIR, "traces.json"), "utf-8"); + } catch { + return ""; + } +} + +function readMetrics(): string { + try { + return fs.readFileSync(path.join(OUTPUT_DIR, "metrics.json"), "utf-8"); + } catch { + return ""; + } +} + +function readLogs(): string { + try { + return fs.readFileSync(path.join(OUTPUT_DIR, "logs.json"), "utf-8"); + } catch { + return ""; + } +} + +function readCapturedHeaders(): Array<{ traceparent: string | null; url: string; method: string }> { + try { + return JSON.parse(fs.readFileSync(path.join(OUTPUT_DIR, "captured-headers.json"), "utf-8")); + } catch { + return []; + } +} + +async function waitForFile(filePath: string, maxAttempts = 30, delayMs = 1000): Promise { + for (let i = 0; i < maxAttempts; i++) { + try { + const stat = fs.statSync(filePath); + if (stat.size > 0) { + console.log(`[waitForFile] ${path.basename(filePath)} ready (${stat.size} bytes, attempt ${i + 1})`); + return true; + } + console.log(`[waitForFile] ${path.basename(filePath)} exists but empty (attempt ${i + 1})`); + } catch { + if (i === 0 || i % 10 === 0) { + console.log(`[waitForFile] ${path.basename(filePath)} not found (attempt ${i + 1})`); + } + } + await new Promise((r) => setTimeout(r, delayMs)); + } + console.log(`[waitForFile] ${path.basename(filePath)} timed out after ${maxAttempts} attempts`); + return false; +} + +async function getContainerLogs(container: StartedTestContainer, timeoutMs = 2000): Promise { + const stream = await container.logs(); + return new Promise((resolve) => { + let output = ""; + const timeout = setTimeout(() => { + stream.destroy(); + resolve(output); + }, timeoutMs); + stream.on("data", (chunk: Buffer) => { + output += chunk.toString(); + }); + stream.on("end", () => { + clearTimeout(timeout); + resolve(output); + }); + stream.on("error", () => { + clearTimeout(timeout); + resolve(output); + }); + }); +} + +describe("OpenTelemetry Integration", () => { + let network: StartedNetwork; + let otelCollector: StartedTestContainer; + let mockZitadel: StartedTestContainer; + let loginApp: StartedTestContainer; + let appUrl: string; + let prometheusUrl: string; + + beforeAll(async () => { + if (fs.existsSync(OUTPUT_DIR)) { + fs.rmSync(OUTPUT_DIR, { recursive: true }); + } + fs.mkdirSync(OUTPUT_DIR, { recursive: true }); + + fs.writeFileSync(path.join(OUTPUT_DIR, "traces.json"), ""); + fs.writeFileSync(path.join(OUTPUT_DIR, "logs.json"), ""); + fs.writeFileSync(path.join(OUTPUT_DIR, "metrics.json"), ""); + + network = await new Network().start(); + + otelCollector = await new GenericContainer("otel/opentelemetry-collector-contrib:0.145.0") + .withNetwork(network) + .withNetworkAliases("otel-collector") + .withUser("0:0") + .withCommand(["--config=/etc/otel-collector-config.yaml"]) + .withCopyFilesToContainer([ + { source: path.join(TEST_DIR, "otel-collector-config.yaml"), target: "/etc/otel-collector-config.yaml" }, + ]) + .withBindMounts([{ source: OUTPUT_DIR, target: "/tmp/otel" }]) + .withExposedPorts(4318, 8888, 13133) + .withWaitStrategy(Wait.forHttp("/", 13133)) + .start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }]) + .withBindMounts([{ source: OUTPUT_DIR, target: "/tmp/otel" }]) + .withEnvironment({ + PORT: "8080", + OUTPUT_DIR: "/tmp/otel", + }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + try { + await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG); + } catch (err) { + throw new Error(`Failed to build login Docker image: ${err instanceof Error ? err.message : err}`); + } + + loginApp = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000, 9464) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token-for-otel-integration-tests", + OTEL_SERVICE_NAME: "zitadel-login-test", + OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318", + OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf", + OTEL_EXPORTER_OTLP_HEADERS: "x-test-header=test-value-123,x-another-header=another-value", + OTEL_LOG_LEVEL: "info", + OTEL_METRICS_EXPORTER: "otlp,prometheus", + OTEL_LOGS_EXPORTER: "otlp", + OTEL_EXPORTER_PROMETHEUS_PORT: "9464", + OTEL_BSP_SCHEDULE_DELAY: "1000", + OTEL_METRIC_EXPORT_INTERVAL: "5000", + DEBUG: "true", + }) + .withStartupTimeout(120000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(3000)}`; + prometheusUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(9464)}/metrics`; + + console.log(`[PORTS] APP_URL: ${appUrl}`); + console.log(`[PORTS] PROMETHEUS_URL: ${prometheusUrl}`); + + await fetch(`${appUrl}/ui/v2/login/otel-test`); + await fetch(`${appUrl}/ui/v2/login/loginname`, { redirect: "manual" }); + await fetch(`${appUrl}/ui/v2/login/healthy`); + await fetch(`${appUrl}/ui/v2/login/ready`); + await fetch(`${appUrl}/ui/v2/login/this-does-not-exist-404`); + + await new Promise((r) => setTimeout(r, 3000)); + + const tracesReady = await waitForFile(path.join(OUTPUT_DIR, "traces.json"), 60, 1000); + if (!tracesReady) throw new Error("Traces file not found"); + const logsReady = await waitForFile(path.join(OUTPUT_DIR, "logs.json"), 60, 1000); + if (!logsReady) throw new Error("Logs file not found"); + const metricsReady = await waitForFile(path.join(OUTPUT_DIR, "metrics.json"), 60, 1000); + if (!metricsReady) throw new Error("Metrics file not found"); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await loginApp?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await otelCollector?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + describe("Traces", () => { + describe("OTLP Export", () => { + it( + "exports spans to collector", + () => { + expect(readTraces().length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + + it( + "contains valid trace IDs", + () => { + expect(readTraces()).toMatch(/"traceId":"[a-f0-9]{32}"/); + }, + TEST_TIMEOUT, + ); + + it( + "contains valid span IDs", + () => { + expect(readTraces()).toMatch(/"spanId":"[a-f0-9]{16}"/); + }, + TEST_TIMEOUT, + ); + + it( + "contains start timestamps", + () => { + expect(readTraces()).toContain("startTimeUnixNano"); + }, + TEST_TIMEOUT, + ); + + it( + "contains end timestamps", + () => { + expect(readTraces()).toContain("endTimeUnixNano"); + }, + TEST_TIMEOUT, + ); + + it( + "contains span status", + () => { + expect(readTraces()).toContain('"status"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains span kind", + () => { + expect(readTraces()).toContain('"kind"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains custom test spans", + () => { + expect(readTraces()).toContain("test-span"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Span Attributes", () => { + it( + "contains http.method", + () => { + expect(readTraces()).toContain('"http.method"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains http.url", + () => { + expect(readTraces()).toContain('"http.url"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains http.status_code", + () => { + expect(readTraces()).toContain('"http.status_code"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains http.target", + () => { + expect(readTraces()).toContain('"http.target"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains net.host.name", + () => { + expect(readTraces()).toContain('"net.host.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains net.host.port", + () => { + expect(readTraces()).toContain('"net.host.port"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains custom test.attribute", + () => { + expect(readTraces()).toContain('"test.attribute"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains custom test.timestamp", + () => { + expect(readTraces()).toContain('"test.timestamp"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Span Status", () => { + it( + "contains status code OK", + () => { + expect(readTraces()).toContain('"code":1'); + }, + TEST_TIMEOUT, + ); + + it( + "contains status code ERROR", + () => { + expect(readTraces()).toContain('"code":2'); + }, + TEST_TIMEOUT, + ); + + it( + "contains error message on failed spans", + () => { + expect(readTraces()).toContain('"message"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Span Hierarchy", () => { + it( + "contains parent span IDs", + () => { + expect(readTraces()).toContain('"parentSpanId"'); + }, + TEST_TIMEOUT, + ); + + it( + "has child spans linked to parent", + () => { + const traces = readTraces(); + const parentMatches = traces.match(/"parentSpanId":"([a-f0-9]{16})"/g) || []; + expect(parentMatches.length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + }); + + describe("Span Filtering", () => { + it( + "HTTP instrumentation excludes /healthy", + () => { + const tracesContent = readTraces(); + const traceObjects = tracesContent + .split("\n") + .filter((line) => line.trim()) + .map((line) => JSON.parse(line)); + + const allResourceSpans = traceObjects.flatMap((t) => t.resourceSpans || []); + + const httpSpans = allResourceSpans + .flatMap((rs: { scopeSpans: Array<{ scope: { name: string }; spans: unknown[] }> }) => rs.scopeSpans) + .filter((ss: { scope: { name: string } }) => ss.scope.name === "@opentelemetry/instrumentation-http") + .flatMap((ss: { spans: unknown[] }) => ss.spans); + const healthySpans = httpSpans.filter( + (s: { attributes?: Array<{ key: string; value: { stringValue?: string } }> }) => + s.attributes?.some( + (a: { key: string; value: { stringValue?: string } }) => + a.key === "http.target" && a.value.stringValue?.includes("/healthy"), + ), + ); + expect(healthySpans).toHaveLength(0); + }, + TEST_TIMEOUT, + ); + + it( + "HTTP instrumentation excludes /ready", + () => { + const tracesContent = readTraces(); + const traceObjects = tracesContent + .split("\n") + .filter((line) => line.trim()) + .map((line) => JSON.parse(line)); + + const allResourceSpans = traceObjects.flatMap((t) => t.resourceSpans || []); + + const httpSpans = allResourceSpans + .flatMap((rs: { scopeSpans: Array<{ scope: { name: string }; spans: unknown[] }> }) => rs.scopeSpans) + .filter((ss: { scope: { name: string } }) => ss.scope.name === "@opentelemetry/instrumentation-http") + .flatMap((ss: { spans: unknown[] }) => ss.spans); + const readySpans = httpSpans.filter( + (s: { attributes?: Array<{ key: string; value: { stringValue?: string } }> }) => + s.attributes?.some( + (a: { key: string; value: { stringValue?: string } }) => + a.key === "http.target" && a.value.stringValue?.includes("/ready"), + ), + ); + expect(readySpans).toHaveLength(0); + }, + TEST_TIMEOUT, + ); + + it( + "includes /otel-test in traces", + () => { + const traces = readTraces(); + expect(traces).toContain("otel-test"); + }, + TEST_TIMEOUT, + ); + + it( + "includes /loginname in traces", + () => { + const traces = readTraces(); + expect(traces).toContain("loginname"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Span Events", () => { + it( + "contains exception events", + () => { + expect(readTraces()).toContain('"name":"exception"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains exception.type attribute", + () => { + expect(readTraces()).toContain('"exception.type"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains exception.message attribute", + () => { + expect(readTraces()).toContain('"exception.message"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains exception.stacktrace attribute", + () => { + expect(readTraces()).toContain('"exception.stacktrace"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("gRPC Spans", () => { + it( + "contains rpc.system attribute", + () => { + expect(readTraces()).toContain('"rpc.system"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains rpc.service attribute", + () => { + expect(readTraces()).toContain('"rpc.service"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains rpc.method attribute", + () => { + expect(readTraces()).toContain('"rpc.method"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains server.address attribute", + () => { + expect(readTraces()).toContain('"server.address"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains rpc.grpc.status_code attribute", + () => { + expect(readTraces()).toContain('"rpc.grpc.status_code"'); + }, + TEST_TIMEOUT, + ); + + it( + "identifies grpc as rpc system", + () => { + expect(readTraces()).toContain('"grpc"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("HTTP Status Codes", () => { + it( + "records HTTP 200 status", + () => { + expect(readTraces()).toContain('"intValue":"200"'); + }, + TEST_TIMEOUT, + ); + + it( + "records HTTP 404 status", + () => { + expect(readTraces()).toContain('"intValue":"404"'); + }, + TEST_TIMEOUT, + ); + + it( + "records OK status text", + () => { + expect(readTraces()).toContain('"OK"'); + }, + TEST_TIMEOUT, + ); + + it( + "records NOT FOUND status text", + () => { + expect(readTraces()).toContain('"NOT FOUND"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Trace Propagation", () => { + it( + "propagates traceparent to backend calls", + () => { + const requests = readCapturedHeaders(); + const backendCalls = requests.filter((r) => r.traceparent !== null); + expect(backendCalls.length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + + it( + "uses W3C traceparent format", + () => { + const requests = readCapturedHeaders(); + const grpcCalls = requests.filter((r) => r.traceparent !== null); + grpcCalls.forEach((r) => expect(r.traceparent).toMatch(/^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/)); + }, + TEST_TIMEOUT, + ); + + it( + "uses traceparent version 00", + () => { + const requests = readCapturedHeaders(); + const grpcCalls = requests.filter((r) => r.traceparent !== null); + grpcCalls.forEach((r) => expect(r.traceparent).toMatch(/^00-/)); + }, + TEST_TIMEOUT, + ); + + it( + "sets sampled flag to 01", + () => { + const requests = readCapturedHeaders(); + const grpcCalls = requests.filter((r) => r.traceparent !== null); + grpcCalls.forEach((r) => expect(r.traceparent).toMatch(/-01$/)); + }, + TEST_TIMEOUT, + ); + + it( + "maintains trace ID consistency", + () => { + const requests = readCapturedHeaders(); + const backendCalls = requests.filter((r) => r.traceparent !== null); + const traceIds = backendCalls.map((r) => r.traceparent!.split("-")[1]); + const uniqueIds = new Set(traceIds); + expect(uniqueIds.size).toBeLessThan(traceIds.length); + }, + TEST_TIMEOUT, + ); + }); + + describe("Resource Attributes", () => { + it( + "contains service.name", + () => { + expect(readTraces()).toContain('"zitadel-login-test"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains deployment.environment.name", + () => { + expect(readTraces()).toContain('"deployment.environment.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.runtime.name", + () => { + expect(readTraces()).toContain('"nodejs"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.runtime.version", + () => { + expect(readTraces()).toContain('"process.runtime.version"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains container.id when running in container", + () => { + expect(readTraces()).toContain('"container.id"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains host.name", + () => { + expect(readTraces()).toContain('"host.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains host.arch", + () => { + expect(readTraces()).toContain('"host.arch"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.pid", + () => { + expect(readTraces()).toContain('"process.pid"'); + }, + TEST_TIMEOUT, + ); + }); + }); + + describe("Metrics", () => { + describe("OTLP Export", () => { + it( + "exports metrics to collector", + () => { + expect(readMetrics().length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + + it( + "contains timestamps", + () => { + expect(readMetrics()).toContain("timeUnixNano"); + }, + TEST_TIMEOUT, + ); + + it( + "contains data points", + () => { + expect(readMetrics()).toContain("dataPoints"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Prometheus Endpoint", () => { + it( + "returns HTTP 200", + async () => { + const response = await fetch(prometheusUrl); + expect(response.status).toBe(200); + }, + TEST_TIMEOUT, + ); + + it( + "returns text/plain content type", + async () => { + const response = await fetch(prometheusUrl); + expect(response.headers.get("content-type")).toContain("text/plain"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Runtime Metrics", () => { + it( + "exposes nodejs_eventloop_utilization", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("nodejs_eventloop_utilization"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes nodejs_eventloop_delay", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("nodejs_eventloop_delay"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes v8js_memory_heap_used", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("v8js_memory_heap_used"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes v8js_memory_heap_limit", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("v8js_memory_heap_limit"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes v8js_gc_duration", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("v8js_gc_duration"); + }, + TEST_TIMEOUT, + ); + }); + + describe("HTTP Metrics", () => { + it( + "exposes http_server_duration", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_duration"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes http_server_duration_sum", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_duration_sum"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes http_server_duration_count", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_duration_count"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes http_server_duration_bucket", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_duration_bucket"); + }, + TEST_TIMEOUT, + ); + + it( + "records status code 200", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('http_status_code="200"'); + }, + TEST_TIMEOUT, + ); + + it( + "records status code 404", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('http_status_code="404"'); + }, + TEST_TIMEOUT, + ); + + it( + "records HTTP GET method", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('http_method="GET"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Application Metrics", () => { + it( + "exposes http_server_requests_total", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_requests_total"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes http_server_active_requests", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_active_requests"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes login_auth_attempts_total", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("login_auth_attempts_total"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes login_auth_successes_total", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("login_auth_successes_total"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes login_session_creation_duration", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("login_session_creation_duration"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes http_server_response_status_total", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_response_status_total"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes http_server_request_duration_seconds", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("http_server_request_duration_seconds"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Custom Test Metrics", () => { + it( + "exposes otel_test_requests_total", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("otel_test_requests_total"); + }, + TEST_TIMEOUT, + ); + + it( + "exposes otel_test_duration_seconds", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain("otel_test_duration_seconds"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Metric Labels", () => { + it( + "includes method label on auth metrics", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('method="test"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes organization label on auth metrics", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('organization="test-org"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes route label on request metrics", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('route="/otel-test"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes success label on session metrics", + async () => { + const response = await fetch(prometheusUrl); + expect(await response.text()).toContain('success="true"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Resource Attributes", () => { + it( + "contains service.name", + () => { + expect(readMetrics()).toContain('"zitadel-login-test"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains deployment.environment.name", + () => { + expect(readMetrics()).toContain('"deployment.environment.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.runtime.name", + () => { + expect(readMetrics()).toContain('"nodejs"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.runtime.version", + () => { + expect(readMetrics()).toContain('"process.runtime.version"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains container.id when running in container", + () => { + expect(readMetrics()).toContain('"container.id"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains host.name", + () => { + expect(readMetrics()).toContain('"host.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains host.arch", + () => { + expect(readMetrics()).toContain('"host.arch"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.pid", + () => { + expect(readMetrics()).toContain('"process.pid"'); + }, + TEST_TIMEOUT, + ); + }); + }); + + describe("Logs", () => { + describe("OTLP Export", () => { + it( + "exports logs to collector", + () => { + expect(readLogs().length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + + it( + "contains timestamps", + () => { + expect(readLogs()).toContain("timeUnixNano"); + }, + TEST_TIMEOUT, + ); + + it( + "contains severity", + () => { + expect(readLogs()).toContain("severityNumber"); + }, + TEST_TIMEOUT, + ); + + it( + "contains body", + () => { + expect(readLogs()).toContain("body"); + }, + TEST_TIMEOUT, + ); + }); + + describe("Log Content", () => { + it( + "contains OTEL test log message", + () => { + expect(readLogs()).toContain("OTEL test endpoint called"); + }, + TEST_TIMEOUT, + ); + + it( + "contains test completed log message", + () => { + expect(readLogs()).toContain("OTEL test completed successfully"); + }, + TEST_TIMEOUT, + ); + + it( + "contains INFO severity level", + () => { + const logs = readLogs(); + expect(logs).toContain('"severityText":"info"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains severity number 9 for INFO", + () => { + expect(readLogs()).toContain('"severityNumber":9'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Log-Trace Correlation", () => { + it( + "includes traceId in log records", + () => { + expect(readLogs()).toContain('"traceId"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes spanId in log records", + () => { + expect(readLogs()).toContain('"spanId"'); + }, + TEST_TIMEOUT, + ); + + it( + "has valid trace ID format", + () => { + expect(readLogs()).toMatch(/"traceId":"[a-f0-9]{32}"/); + }, + TEST_TIMEOUT, + ); + + it( + "has valid span ID format", + () => { + expect(readLogs()).toMatch(/"spanId":"[a-f0-9]{16}"/); + }, + TEST_TIMEOUT, + ); + + it( + "includes trace_id attribute", + () => { + expect(readLogs()).toContain('"trace_id"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes span_id attribute", + () => { + expect(readLogs()).toContain('"span_id"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes trace_flags attribute", + () => { + expect(readLogs()).toContain('"trace_flags"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Log Attributes", () => { + it( + "includes context attribute", + () => { + expect(readLogs()).toContain('"context"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes service attribute", + () => { + expect(readLogs()).toContain('"service"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes timestamp attribute", + () => { + expect(readLogs()).toContain('"timestamp"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes custom test attribute", + () => { + expect(readLogs()).toContain('"test"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes duration attribute", + () => { + expect(readLogs()).toContain('"duration"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("Resource Attributes", () => { + it( + "contains service.name", + () => { + expect(readLogs()).toContain('"zitadel-login-test"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains deployment.environment.name", + () => { + expect(readLogs()).toContain('"deployment.environment.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.runtime.name", + () => { + expect(readLogs()).toContain('"nodejs"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.runtime.version", + () => { + expect(readLogs()).toContain('"process.runtime.version"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains container.id when running in container", + () => { + expect(readLogs()).toContain('"container.id"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains host.name", + () => { + expect(readLogs()).toContain('"host.name"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains host.arch", + () => { + expect(readLogs()).toContain('"host.arch"'); + }, + TEST_TIMEOUT, + ); + + it( + "contains process.pid", + () => { + expect(readLogs()).toContain('"process.pid"'); + }, + TEST_TIMEOUT, + ); + }); + }); +}); + +describe("OpenTelemetry Disabled", () => { + let network: StartedNetwork; + let mockZitadel: StartedTestContainer; + let loginApp: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + network = await new Network().start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }]) + .withEnvironment({ + PORT: "8080", + }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + loginApp = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000, 9464) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + OTEL_SDK_DISABLED: "true", + }) + .withStartupTimeout(120000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(3000)}`; + console.log(`[OTEL DISABLED] APP_URL: ${appUrl}`); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await loginApp?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + describe("Application Health", () => { + it( + "starts successfully with OTEL_SDK_DISABLED=true", + async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.ok).toBe(true); + }, + TEST_TIMEOUT, + ); + + it( + "responds to health checks", + async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.status).toBe(200); + }, + TEST_TIMEOUT, + ); + }); + + describe("Metrics Endpoint", () => { + it( + "metrics endpoint is not available when OTEL is disabled", + async () => { + const metricsUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(9464)}/metrics`; + try { + await fetch(metricsUrl); + expect.fail("Metrics endpoint should not be available"); + } catch (error) { + expect(error).toBeDefined(); + } + }, + TEST_TIMEOUT, + ); + }); + + describe("Logging", () => { + it( + "outputs logs to console via Winston", + async () => { + await fetch(`${appUrl}/ui/v2/login/healthy`); + await new Promise((resolve) => setTimeout(resolve, 1000)); + const logOutput = await getContainerLogs(loginApp); + expect(logOutput.length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + + it( + "does not contain OTEL SDK initialization logs", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).not.toContain("OpenTelemetry SDK started"); + expect(logOutput).not.toContain("Exporter"); + }, + TEST_TIMEOUT, + ); + }); +}); + +describe("Log Level Configuration", () => { + describe("OTEL Disabled", () => { + describe("LOG_LEVEL=debug", () => { + let network: StartedNetwork; + let mockZitadel: StartedTestContainer; + let loginApp: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + network = await new Network().start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }]) + .withEnvironment({ + PORT: "8080", + }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + loginApp = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + OTEL_SDK_DISABLED: "true", + LOG_LEVEL: "debug", + }) + .withStartupTimeout(120000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(3000)}`; + console.log(`[OTEL_DISABLED + LOG_LEVEL=debug] APP_URL: ${appUrl}`); + + await fetch(`${appUrl}/ui/v2/login/healthy`); + await fetch(`${appUrl}/ui/v2/login/otel-test`); + await new Promise((r) => setTimeout(r, 1000)); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await loginApp?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it( + "starts successfully", + async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.ok).toBe(true); + }, + TEST_TIMEOUT, + ); + + it( + "includes info level logs in console", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).toContain('"level":"info"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("LOG_LEVEL=warn", () => { + let network: StartedNetwork; + let mockZitadel: StartedTestContainer; + let loginApp: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + network = await new Network().start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }]) + .withEnvironment({ + PORT: "8080", + }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + loginApp = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + OTEL_SDK_DISABLED: "true", + LOG_LEVEL: "warn", + }) + .withStartupTimeout(120000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(3000)}`; + console.log(`[OTEL_DISABLED + LOG_LEVEL=warn] APP_URL: ${appUrl}`); + + await fetch(`${appUrl}/ui/v2/login/healthy`); + await new Promise((r) => setTimeout(r, 1000)); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await loginApp?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it( + "starts successfully", + async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.ok).toBe(true); + }, + TEST_TIMEOUT, + ); + + it( + "does not include info level logs in console", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).not.toContain('"level":"info"'); + }, + TEST_TIMEOUT, + ); + + it( + "does not include debug level logs in console", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).not.toContain('"level":"debug"'); + }, + TEST_TIMEOUT, + ); + }); + }); + + describe("OTEL Enabled", () => { + const OTEL_LOG_OUTPUT_DIR = path.join(OUTPUT_DIR, "loglevel"); + + describe("LOG_LEVEL=debug", () => { + let network: StartedNetwork; + let otelCollector: StartedTestContainer; + let mockZitadel: StartedTestContainer; + let loginApp: StartedTestContainer; + let appUrl: string; + let logOutputDir: string; + + beforeAll(async () => { + logOutputDir = path.join(OTEL_LOG_OUTPUT_DIR, "debug"); + if (fs.existsSync(logOutputDir)) { + fs.rmSync(logOutputDir, { recursive: true }); + } + fs.mkdirSync(logOutputDir, { recursive: true }); + fs.writeFileSync(path.join(logOutputDir, "logs.json"), ""); + + network = await new Network().start(); + + otelCollector = await new GenericContainer("otel/opentelemetry-collector-contrib:0.145.0") + .withNetwork(network) + .withNetworkAliases("otel-collector") + .withUser("0:0") + .withCommand(["--config=/etc/otel-collector-config.yaml"]) + .withCopyFilesToContainer([ + { source: path.join(TEST_DIR, "otel-collector-config.yaml"), target: "/etc/otel-collector-config.yaml" }, + ]) + .withBindMounts([{ source: logOutputDir, target: "/tmp/otel" }]) + .withExposedPorts(4318, 13133) + .withWaitStrategy(Wait.forHttp("/", 13133)) + .start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }]) + .withEnvironment({ + PORT: "8080", + }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + loginApp = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + OTEL_SERVICE_NAME: "zitadel-login-loglevel-debug", + OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318", + OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf", + OTEL_LOG_LEVEL: "debug", + OTEL_LOGS_EXPORTER: "otlp", + OTEL_BSP_SCHEDULE_DELAY: "1000", + }) + .withStartupTimeout(120000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(3000)}`; + console.log(`[OTEL_ENABLED + LOG_LEVEL=debug] APP_URL: ${appUrl}`); + + await fetch(`${appUrl}/ui/v2/login/healthy`); + await fetch(`${appUrl}/ui/v2/login/otel-test`); + await new Promise((r) => setTimeout(r, 3000)); + + await waitForFile(path.join(logOutputDir, "logs.json"), 30, 1000); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await loginApp?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await otelCollector?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it( + "starts successfully", + async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.ok).toBe(true); + }, + TEST_TIMEOUT, + ); + + it( + "exports logs to OTLP collector", + () => { + const logs = fs.readFileSync(path.join(logOutputDir, "logs.json"), "utf-8"); + expect(logs.length).toBeGreaterThan(0); + }, + TEST_TIMEOUT, + ); + + it( + "includes info level logs in OTLP export", + () => { + const logs = fs.readFileSync(path.join(logOutputDir, "logs.json"), "utf-8"); + expect(logs).toContain('"severityText":"info"'); + }, + TEST_TIMEOUT, + ); + + it( + "includes info level logs in console", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).toContain('"level":"info"'); + }, + TEST_TIMEOUT, + ); + }); + + describe("LOG_LEVEL=warn", () => { + let network: StartedNetwork; + let otelCollector: StartedTestContainer; + let mockZitadel: StartedTestContainer; + let loginApp: StartedTestContainer; + let appUrl: string; + let logOutputDir: string; + + beforeAll(async () => { + logOutputDir = path.join(OTEL_LOG_OUTPUT_DIR, "warn"); + if (fs.existsSync(logOutputDir)) { + fs.rmSync(logOutputDir, { recursive: true }); + } + fs.mkdirSync(logOutputDir, { recursive: true }); + fs.writeFileSync(path.join(logOutputDir, "logs.json"), ""); + + network = await new Network().start(); + + otelCollector = await new GenericContainer("otel/opentelemetry-collector-contrib:0.145.0") + .withNetwork(network) + .withNetworkAliases("otel-collector") + .withUser("0:0") + .withCommand(["--config=/etc/otel-collector-config.yaml"]) + .withCopyFilesToContainer([ + { source: path.join(TEST_DIR, "otel-collector-config.yaml"), target: "/etc/otel-collector-config.yaml" }, + ]) + .withBindMounts([{ source: logOutputDir, target: "/tmp/otel" }]) + .withExposedPorts(4318, 13133) + .withWaitStrategy(Wait.forHttp("/", 13133)) + .start(); + + mockZitadel = await new GenericContainer("node:20-alpine") + .withNetwork(network) + .withNetworkAliases("mock-zitadel") + .withCopyFilesToContainer([{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" }]) + .withEnvironment({ + PORT: "8080", + }) + .withCommand(["node", "/app/server.js"]) + .withExposedPorts(8080) + .withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening")) + .start(); + + loginApp = await new GenericContainer(LOGIN_IMAGE_TAG) + .withNetwork(network) + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_API_URL: "http://mock-zitadel:8080", + ZITADEL_SERVICE_USER_TOKEN: "test-token", + OTEL_SERVICE_NAME: "zitadel-login-loglevel-warn", + OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318", + OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf", + OTEL_LOG_LEVEL: "warn", + OTEL_LOGS_EXPORTER: "otlp", + OTEL_BSP_SCHEDULE_DELAY: "1000", + }) + .withStartupTimeout(120000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${loginApp.getHost()}:${loginApp.getMappedPort(3000)}`; + console.log(`[OTEL_ENABLED + LOG_LEVEL=warn] APP_URL: ${appUrl}`); + + await fetch(`${appUrl}/ui/v2/login/healthy`); + await fetch(`${appUrl}/ui/v2/login/otel-test`); + await new Promise((r) => setTimeout(r, 3000)); + }, DOCKER_TIMEOUT); + + afterAll(async () => { + await loginApp?.stop().catch(() => {}); + await mockZitadel?.stop().catch(() => {}); + await otelCollector?.stop().catch(() => {}); + await network?.stop().catch(() => {}); + }, DOCKER_TIMEOUT); + + it( + "starts successfully", + async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.ok).toBe(true); + }, + TEST_TIMEOUT, + ); + + it( + "does not include info level logs in console", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).not.toContain('"level":"info"'); + }, + TEST_TIMEOUT, + ); + + it( + "does not include debug level logs in console", + async () => { + const logOutput = await getContainerLogs(loginApp); + expect(logOutput).not.toContain('"level":"debug"'); + }, + TEST_TIMEOUT, + ); + + it( + "does not export info level logs to OTLP", + () => { + const logsPath = path.join(logOutputDir, "logs.json"); + if (fs.existsSync(logsPath)) { + const logs = fs.readFileSync(logsPath, "utf-8"); + expect(logs).not.toContain('"severityText":"info"'); + } + }, + TEST_TIMEOUT, + ); + + it( + "does not export debug level logs to OTLP", + () => { + const logsPath = path.join(logOutputDir, "logs.json"); + if (fs.existsSync(logsPath)) { + const logs = fs.readFileSync(logsPath, "utf-8"); + expect(logs).not.toContain('"severityText":"debug"'); + } + }, + TEST_TIMEOUT, + ); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/dockerized/ssl/tls.integration.test.ts b/auth/ui/v2/apps/login/dockerized/ssl/tls.integration.test.ts new file mode 100644 index 0000000..4dc6ab0 --- /dev/null +++ b/auth/ui/v2/apps/login/dockerized/ssl/tls.integration.test.ts @@ -0,0 +1,119 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { GenericContainer, type StartedTestContainer, Wait } from "testcontainers"; +import * as https from "node:https"; +import * as fs from "fs"; +import * as path from "path"; +import { fileURLToPath } from "node:url"; +import { generateCertificates } from "../ca/utils/tls.ts"; + +const TEST_DIR = path.dirname(fileURLToPath(import.meta.url)); +const OUTPUT_DIR = path.join(TEST_DIR, "output"); +const CERTS_DIR = path.join(OUTPUT_DIR, "certs"); +const LOGIN_APP_DIR = path.join(TEST_DIR, "../.."); +const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`; + +/** + * Integration tests for TLS support in the login application. + * + * These tests verify that the login container can serve traffic over HTTPS + * when configured with ZITADEL_TLS_ENABLED, ZITADEL_TLS_CERTPATH, and + * ZITADEL_TLS_KEYPATH environment variables. This is essential for deployments + * where the login application must terminate TLS itself rather than relying on + * a reverse proxy. + * + * The test suite builds the login container image and runs it in two modes: + * HTTP (default) and HTTPS (with TLS enabled). For HTTPS mode, a self-signed + * certificate is generated and mounted into the container. The tests verify + * that the application starts correctly and responds to health checks in both + * modes. + */ +describe("Login Container TLS Support", () => { + let loginImage: GenericContainer; + + beforeAll(async () => { + if (fs.existsSync(OUTPUT_DIR)) { + fs.rmSync(OUTPUT_DIR, { recursive: true }); + } + fs.mkdirSync(CERTS_DIR, { recursive: true }); + + const certs = generateCertificates({ + serverCN: "localhost", + dns: ["localhost"], + ips: ["127.0.0.1"], + }); + + fs.writeFileSync(path.join(CERTS_DIR, "server.crt"), certs.server.cert); + fs.writeFileSync(path.join(CERTS_DIR, "server.key"), certs.server.key); + + await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG); + loginImage = new GenericContainer(LOGIN_IMAGE_TAG); + }); + + describe("when TLS is not enabled", () => { + let container: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + container = await loginImage + .withExposedPorts(3000) + .withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000)) + .start(); + + appUrl = `http://${container.getHost()}:${container.getMappedPort(3000)}`; + }); + + afterAll(async () => { + await container?.stop(); + }); + + it("returns 200 from healthy endpoint", async () => { + const response = await fetch(`${appUrl}/ui/v2/login/healthy`); + expect(response.status).toBe(200); + }); + }); + + describe("when TLS is enabled", () => { + let container: StartedTestContainer; + let appUrl: string; + + beforeAll(async () => { + container = await loginImage + .withExposedPorts(3000) + .withEnvironment({ + ZITADEL_TLS_ENABLED: "true", + ZITADEL_TLS_CERTPATH: "/certs/server.crt", + ZITADEL_TLS_KEYPATH: "/certs/server.key", + }) + .withCopyFilesToContainer([ + { + source: path.join(CERTS_DIR, "server.crt"), + target: "/certs/server.crt", + }, + { + source: path.join(CERTS_DIR, "server.key"), + target: "/certs/server.key", + }, + ]) + .withWaitStrategy(Wait.forLogMessage(/Ready on https/)) + .start(); + + appUrl = `https://${container.getHost()}:${container.getMappedPort(3000)}`; + }); + + afterAll(async () => { + await container?.stop(); + }); + + it("returns 200 from healthy endpoint over HTTPS", async () => { + const response = await new Promise((resolve, reject) => { + https + .get(`${appUrl}/ui/v2/login/healthy`, { rejectUnauthorized: false }, (res) => { + res.resume(); + resolve(res); + }) + .on("error", reject); + }); + expect(response.statusCode).toBe(200); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/eslint.config.mjs b/auth/ui/v2/apps/login/eslint.config.mjs new file mode 100644 index 0000000..c5969bb --- /dev/null +++ b/auth/ui/v2/apps/login/eslint.config.mjs @@ -0,0 +1,160 @@ +import js from "@eslint/js"; +import nextPlugin from "@next/eslint-plugin-next"; +import tsPlugin from "@typescript-eslint/eslint-plugin"; +import tsParser from "@typescript-eslint/parser"; +import prettierConfig from "eslint-config-prettier/flat"; +import importPlugin from "eslint-plugin-import"; +import reactHooksPlugin from "eslint-plugin-react-hooks"; +import globals from "globals"; +import moduleBoundaries from "./checks/eslint-module-boundaries.mjs"; + +export default [ + { + ignores: [ + "node_modules/**", + ".next/**", + "dockerized/**", + "cypress/**", + "acceptance/**", + "integration/**", + "vitest.config*.ts", + "next-env.d.ts", + ], + }, + js.configs.recommended, + nextPlugin.configs["core-web-vitals"], + { + files: ["**/*.{ts,tsx,jsx}"], + plugins: { + "react-hooks": reactHooksPlugin, + }, + rules: { + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "error", + }, + }, + { + files: ["**/*.{js,mjs,cjs}"], + languageOptions: { + globals: { + ...globals.browser, + ...globals.node, + }, + }, + }, + { + files: ["**/*.{ts,tsx}"], + plugins: { + "@typescript-eslint": tsPlugin, + import: importPlugin, + }, + languageOptions: { + parser: tsParser, + ecmaVersion: "latest", + sourceType: "module", + parserOptions: { + ecmaFeatures: { jsx: true }, + project: "./tsconfig.json", + }, + }, + settings: { + "import/resolver": { + typescript: true, + }, + }, + rules: { + ...tsPlugin.configs.recommended.rules, + ...importPlugin.configs.recommended.rules, + "no-unused-vars": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + }, + ], + "no-undef": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/ban-ts-comment": "off", + "@next/next/no-img-element": "off", + "no-restricted-imports": [ + "error", + { + paths: [ + { + name: "next/image", + message: + "Use of next/image is forbidden. Use regular elements instead.", + }, + ], + }, + ], + }, + }, + // Server Actions live in src/lib/actions, server-only code in src/lib/server + { + files: ["src/**/*.{ts,tsx}"], + plugins: { + login: moduleBoundaries, + }, + rules: { + "login/module-boundaries": "error", + }, + }, + // Server components and server actions: must use logger, not console.* + { + files: [ + "src/lib/server/**/*.ts", + "src/lib/actions/**/*.ts", + "src/app/**/route.ts", + "src/proxy.ts", + ], + rules: { + "no-console": "warn", + }, + }, + // instrumentation.ts uses console.log during OTEL initialization (before logger is available) + { + files: ["src/instrumentation.ts"], + rules: { + "no-console": "off", + }, + }, + // Client components: logger import is forbidden (enforced by server-only at build time) + { + files: ["src/components/**/*.tsx"], + rules: { + "no-restricted-imports": [ + "error", + { + paths: [ + { + name: "next/image", + message: + "Use of next/image is forbidden. Use regular elements instead.", + }, + { + name: "@/lib/server/logger", + message: + "Cannot import logger in client components. Use console.* instead. The logger uses 'server-only' and will fail at build time.", + }, + ], + }, + ], + }, + }, + // Test files: allow console.* + { + files: [ + "**/*.test.ts", + "**/*.test.tsx", + "**/*.spec.ts", + "**/*.spec.tsx", + "**/tests/**/*", + ], + rules: { + "no-console": "off", + }, + }, + prettierConfig, +]; diff --git a/auth/ui/v2/apps/login/locales/ar.json b/auth/ui/v2/apps/login/locales/ar.json new file mode 100644 index 0000000..700b903 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/ar.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "رجوع", + "title": "تسجيل الدخول باستخدام Zitadel" + }, + "accounts": { + "title": "الحسابات", + "description": "حدد الحساب الذي تريد استخدامه.", + "addAnother": "إضافة حساب آخر", + "noResults": "لم يتم العثور على حسابات", + "verified": "تم التحقق", + "expired": "منتهي الصلاحية" + }, + "logout": { + "title": "تسجيل الخروج", + "description": "انقر فوق حساب لإنهاء الجلسة", + "noResults": "لم يتم العثور على حسابات", + "clear": "إنهاء الجلسة", + "verifiedAt": "آخر نشاط: {time}", + "success": { + "title": "تم تسجيل الخروج بنجاح", + "description": "لقد قمت بتسجيل الخروج بنجاح." + } + }, + "loginname": { + "title": "مرحباً بعودتك!", + "description": "أدخل بيانات الدخول الخاصة بك.", + "register": "تسجيل مستخدم جديد", + "submit": "متابعة", + "labels": { + "loginname": "اسم الدخول", + "username": "اسم المستخدم", + "usernameOrPhoneNumber": "اسم المستخدم أو رقم الهاتف", + "usernameOrEmail": "اسم المستخدم أو البريد الإلكتروني" + }, + "required": { + "loginName": "هذا الحقل مطلوب" + }, + "errors": { + "internalError": "حدث خطأ داخلي", + "couldNotGetLoginSettings": "تعذر الحصول على إعدادات تسجيل الدخول", + "couldNotSearchUsers": "تعذر البحث عن المستخدمين", + "couldNotGetDomain": "تعذر الحصول على النطاق", + "couldNotGetHost": "تعذر الحصول على المضيف", + "couldNotStartIDPFlow": "تعذر بدء تدفق مزود الهوية (IDP)", + "moreThanOneUserFound": "تم العثور على أكثر من مستخدم. يرجى تقديم معرف فريد.", + "userNotFound": "المستخدم غير موجود في النظام", + "couldNotCreateSession": "تعذر إنشاء جلسة للمستخدم", + "initialUserNotSupported": "المستخدم الأولي غير مدعوم", + "localAuthenticationNotAllowed": "المصادقة المحلية غير مسموح بها! اتصل بالمسؤول لمزيد من المعلومات.", + "passkeysNotAllowed": "مفاتيح المرور غير مسموح بها! اتصل بالمسؤول لمزيد من المعلومات.", + "couldNotFindIdentityProvider": "تعذر العثور على مزود الهوية.", + "userNotActive": "المستخدم غير نشط. اتصل بالمسؤول لمزيد من المعلومات." + } + }, + "zitadel": { + "errors": { + "errorOccured": "حدث خطأ", + "multipleUsersFound": "تم العثور على مستخدمين متعددين", + "userNotFound": "المستخدم غير موجود في النظام" + } + }, + "password": { + "verify": { + "title": "كلمة المرور", + "description": "أدخل كلمة المرور الخاصة بك.", + "resetPassword": "إعادة تعيين كلمة المرور", + "submit": "متابعة", + "labels": { + "password": "كلمة المرور" + }, + "required": { + "password": "هذا الحقل مطلوب" + }, + "errors": { + "couldNotVerifyPassword": "تعذر التحقق من كلمة المرور", + "couldNotResetPassword": "تعذر إعادة تعيين كلمة المرور" + }, + "info": { + "passwordResetSent": "تمت إعادة تعيين كلمة المرور. يرجى التحقق من بريدك الإلكتروني" + } + }, + "set": { + "title": "تعيين كلمة المرور", + "description": "تعيين كلمة المرور لحسابك", + "codeSent": "تم إرسال رمز جديد إلى عنوان بريدك الإلكتروني.", + "noCodeReceived": "لم تستلم رمزاً؟", + "resend": "إعادة إرسال الرمز", + "submit": "متابعة", + "labels": { + "code": "الرمز", + "newPassword": "كلمة المرور الجديدة", + "confirmPassword": "تأكيد كلمة المرور" + }, + "required": { + "code": "هذا الحقل مطلوب", + "newPassword": "عليك تقديم كلمة مرور!", + "confirmPassword": "هذا الحقل مطلوب" + }, + "errors": { + "couldNotSetPassword": "تعذر تعيين كلمة المرور", + "couldNotResetPassword": "تعذر إعادة تعيين كلمة المرور", + "couldNotVerifyPassword": "تعذر التحقق من كلمة المرور" + } + }, + "change": { + "title": "تغيير كلمة المرور", + "description": "تعيين كلمة المرور لحسابك", + "submit": "متابعة", + "labels": { + "currentPassword": "كلمة المرور الحالية", + "newPassword": "كلمة المرور الجديدة", + "confirmPassword": "تأكيد كلمة المرور" + }, + "required": { + "currentPassword": "عليك تقديم كلمة المرور الحالية!", + "newPassword": "عليك تقديم كلمة مرور جديدة!", + "confirmPassword": "هذا الحقل مطلوب" + }, + "errors": { + "currentPasswordInvalid": "كلمة المرور الحالية غير صحيحة.", + "couldNotChangePassword": "تعذر تغيير كلمة المرور", + "couldNotVerifyPassword": "تعذر التحقق من كلمة المرور", + "unknownError": "خطأ غير معروف" + } + }, + "complexity": { + "length": "يجب أن تكون على الأقل {minLength} حرفاً.", + "hasSymbol": "يجب أن تتضمن رمزاً.", + "hasNumber": "يجب أن تتضمن رقماً.", + "hasUppercase": "يجب أن تتضمن حرفاً كبيراً.", + "hasLowercase": "يجب أن تتضمن حرفاً صغيراً.", + "equals": "تأكيد كلمة المرور متطابق.", + "matches": "مطابق", + "doesNotMatch": "غير مطابق" + }, + "errors": { + "noHostFound": "لم يتم العثور على مضيف", + "couldNotSendResetLink": "تعذر إرسال رابط إعادة تعيين كلمة المرور", + "couldNotCreateSessionForUser": "تعذر إنشاء جلسة للمستخدم", + "couldNotVerifyPassword": "تعذر التحقق من كلمة المرور", + "failedToAuthenticate": "فشلت المصادقة. لقد استهلكت {failedAttempts} من {maxPasswordAttempts} محاولة لكلمة المرور.{lockoutMessage}", + "failedToAuthenticateNoLimit": "فشلت المصادقة.", + "accountLockedContactAdmin": " اتصل بالمسؤول لفتح قفل حسابك", + "userNotFound": "المستخدم غير موجود في النظام", + "initialUserNotSupported": "المستخدم الأولي غير مدعوم", + "userInitialStateNotSupported": "حالة المستخدم الأولية غير مدعومة", + "codeOrVerificationRequired": "عليك تقديم رمز أو الحصول على فحص تحقق صالح للمستخدم", + "verificationRequired": "يجب إجراء فحص التحقق من المستخدم", + "couldNotLoadSession": "تعذر تحميل الجلسة", + "couldNotLoadAuthMethods": "تعذر تحميل طرق المصادقة", + "failedPrecondition": "فشل الشرط المسبق", + "sessionNotValid": "الجلسة غير صالحة", + "passwordVerificationMissing": "التحقق من كلمة المرور مفقود.", + "passwordVerificationTooOld": "التحقق من كلمة المرور قديم جدًا. يرجى التحقق من كلمة المرور مرة أخرى.", + "passwordResetNotAllowed": "إعادة تعيين كلمة المرور غير مسموح بها. اتصل بالمسؤول لمزيد من المعلومات.", + "localAuthenticationNotAllowed": "المصادقة المحلية غير مسموح بها! اتصل بالمسؤول لمزيد من المعلومات." + } + }, + "idp": { + "title": "تسجيل الدخول باستخدام SSO", + "description": "حدد أحد المزودين التاليين لتسجيل الدخول", + "orSignInWith": "أو تسجيل الدخول باستخدام", + "signInWithApple": "تسجيل الدخول باستخدام Apple", + "signInWithGoogle": "تسجيل الدخول باستخدام Google", + "signInWithAzureAD": "تسجيل الدخول باستخدام AzureAD", + "signInWithGithub": "تسجيل الدخول باستخدام GitHub", + "signInWithGitlab": "تسجيل الدخول باستخدام GitLab", + "signInWithZitadel": "تسجيل الدخول باستخدام Zitadel", + "loginError": { + "title": "فشل تسجيل الدخول", + "description": "حدث خطأ أثناء محاولة تسجيل الدخول." + }, + "linkingError": { + "title": "فشل ربط الحساب", + "description": "حدث خطأ أثناء محاولة ربط حسابك." + }, + "completeRegister": { + "title": "أكمل بياناتك", + "description": "تحتاج إلى إكمال تسجيلك من خلال توفير عنوان بريدك الإلكتروني واسمك." + }, + "accountNotFound": { + "title": "الحساب غير موجود", + "description": "لم نتمكن من العثور على حساب مرتبط ببيانات اعتماد مزود الهوية الخاص بك.", + "info": "لم يتم العثور على حساب موجود. يرجى تسجيل الدخول بحساب موجود أو الاتصال بالمسؤول للحصول على المساعدة.", + "backToLogin": "العودة إلى تسجيل الدخول" + }, + "registrationFailed": { + "title": "التسجيل غير متاح", + "description": "لم نتمكن من إكمال عملية التسجيل.", + "info": "تعذر تحديد المنظمة للتسجيل. يرجى الاتصال بالمسؤول للحصول على المساعدة.", + "backToLogin": "العودة إلى تسجيل الدخول" + }, + "processing": { + "message": "جاري معالجة المصادقة...", + "noRedirect": "لم يتم إرجاع إعادة توجيه أو خطأ من الخادم", + "unexpectedError": "حدث خطأ غير متوقع" + }, + "errors": { + "missingParameters": "معلمات مطلوبة مفقودة", + "missingIdpInfo": "معلومات IDP مفقودة", + "idpNotFound": "مزود الهوية غير موجود", + "linkingNotAllowed": "الربط غير مسموح به لمزود الهوية هذا", + "linkingFailed": "فشل ربط مزود الهوية بالحساب", + "autoLinkingFailed": "فشل ربط الحساب تلقائياً", + "userCreationFailed": "فشل إنشاء حساب المستخدم", + "orgResolutionFailed": "تعذر تحديد المنظمة للتسجيل", + "sessionCreationFailed": "تعذر إنشاء الجلسة أو تحديد إعادة التوجيه", + "unknownError": "حدث خطأ غير معروف" + } + }, + "ldap": { + "title": "تسجيل الدخول LDAP", + "description": "أدخل بيانات اعتماد LDAP الخاصة بك.", + "submit": "متابعة", + "labels": { + "username": "اسم المستخدم", + "password": "كلمة المرور" + }, + "required": { + "username": "هذا الحقل مطلوب", + "password": "هذا الحقل مطلوب" + } + }, + "mfa": { + "verify": { + "title": "التحقق من هويتك", + "description": "اختر أحد العوامل التالية.", + "noResults": "لا توجد عوامل ثانية متاحة للإعداد." + }, + "set": { + "title": "إعداد المصادقة الثنائية", + "description": "اختر أحد العوامل الثانية التالية.", + "skip": "تخطي" + } + }, + "otp": { + "verify": { + "title": "التحقق من المصادقة الثنائية", + "totpDescription": "أدخل الرمز من تطبيق المصادقة الخاص بك.", + "smsDescription": "أدخل الرمز الذي تلقيته عبر الرسائل القصيرة.", + "emailDescription": "أدخل الرمز الذي تلقيته عبر البريد الإلكتروني.", + "noCodeReceived": "لم تستلم رمزاً؟", + "resendCode": "إعادة إرسال الرمز", + "resendCodeIn": "إعادة إرسال الرمز ({seconds} ث)", + "submit": "متابعة", + "labels": { + "code": "الرمز" + }, + "required": { + "code": "هذا الحقل مطلوب" + } + }, + "set": { + "title": "إعداد المصادقة الثنائية", + "totpDescription": "امسح رمز الاستجابة السريعة باستخدام تطبيق المصادقة الخاص بك.", + "smsDescription": "أدخل رقم هاتفك لتلقي رمز عبر الرسائل القصيرة.", + "emailDescription": "أدخل عنوان بريدك الإلكتروني لتلقي رمز عبر البريد الإلكتروني.", + "totpRegisterDescription": "امسح رمز الاستجابة السريعة أو انتقل إلى عنوان URL يدوياً.", + "emailAddDescription": "استخدم رمزًا لمرة واحدة يُرسل إلى عنوان بريدك الإلكتروني الموثق كعامل ثانٍ.", + "smsAddDescription": "استخدم رمزًا لمرة واحدة يُرسل إلى رقم هاتفك الموثق كعامل ثانٍ.", + "add": "إضافة", + "emailAdded": "تمت إضافة الرمز عبر البريد الإلكتروني.", + "smsAdded": "تمت إضافة الرمز عبر الرسائل القصيرة.", + "submit": "متابعة", + "labels": { + "code": "الرمز" + }, + "required": { + "code": "هذا الحقل مطلوب" + } + }, + "errors": { + "couldNotRequestChallenge": "تعذر طلب تحدي OTP", + "couldNotVerifyCode": "تعذر التحقق من رمز OTP", + "couldNotGetSession": "تعذر تحميل جلستك. يرجى تسجيل الدخول مرة أخرى.", + "invalidMethod": "هذا العامل الثاني غير مدعوم.", + "couldNotAddEmail": "تعذرت إضافة الرمز عبر البريد الإلكتروني.", + "couldNotAddSms": "تعذرت إضافة الرمز عبر الرسائل القصيرة.", + "emailNotVerified": "وثّق عنوان بريدك الإلكتروني قبل إضافة الرموز عبر البريد الإلكتروني.", + "phoneNotVerified": "وثّق رقم هاتفك قبل إضافة الرموز عبر الرسائل القصيرة." + } + }, + "passkey": { + "verify": { + "title": "المصادقة باستخدام مفتاح مرور", + "description": "سيطلب جهازك بصمة إصبعك، أو وجهك، أو قفل الشاشة", + "usePassword": "استخدم كلمة المرور", + "submit": "متابعة", + "errors": { + "couldNotRequestChallenge": "تعذر طلب تحدي مفتاح المرور", + "couldNotVerifyPasskey": "تعذر التحقق من مفتاح المرور", + "noResponseReceived": "فشل التحقق من مفتاح المرور - لم يتم استلام أي استجابة", + "noRedirectProvided": "اكتمل التحقق من مفتاح المرور ولكن لم يتم توفير إعادة توجيه", + "couldNotRetrievePasskey": "حدث خطأ أثناء استرداد مفتاح المرور", + "verificationCancelled": "تم إلغاء التحقق من مفتاح المرور", + "verificationFailed": "حدث خطأ أثناء التحقق من مفتاح المرور", + "couldNotFindSession": "تعذر العثور على الجلسة", + "couldNotUpdateSession": "تعذر تحديث الجلسة", + "userNotFound": "المستخدم غير موجود في النظام", + "couldNotDetermineRedirect": "تعذر تحديد عنوان URL لإعادة التوجيه بعد التحقق من مفتاح المرور" + } + }, + "set": { + "title": "إعداد مفتاح مرور", + "description": "سيطلب جهازك بصمة إصبعك، أو وجهك، أو قفل الشاشة", + "info": { + "description": "مفتاح المرور هو طريقة مصادقة على جهاز مثل بصمة الإصبع، Apple FaceID أو ما شابه. ", + "link": "المصادقة بدون كلمة مرور" + }, + "skip": "تخطي", + "submit": "متابعة" + } + }, + "u2f": { + "verify": { + "title": "التحقق من المصادقة الثنائية", + "description": "تحقق من حسابك باستخدام جهازك." + }, + "set": { + "title": "إعداد المصادقة الثنائية", + "description": "إعداد جهاز كعامل ثانٍ.", + "submit": "متابعة" + } + }, + "register": { + "methods": { + "passkey": "مفتاح مرور", + "password": "كلمة المرور" + }, + "disabled": { + "title": "التسجيل معطل", + "description": "التسجيل معطل. يرجى الاتصال بالمسؤول." + }, + "missingdata": { + "title": "بيانات مفقودة", + "description": "قدم البريد الإلكتروني والاسم الأول والأخير للتسجيل." + }, + "title": "تسجيل", + "description": "أنشئ حساب ZITADEL الخاص بك.", + "noMethodAvailableWarning": "لا توجد طريقة مصادقة متاحة. يرجى الاتصال بالمسؤول.", + "selectMethod": "حدد الطريقة التي ترغب في المصادقة بها", + "agreeTo": "للتسجيل يجب عليك الموافقة على الشروط والأحكام", + "termsOfService": "شروط الخدمة", + "privacyPolicy": "سياسة الخصوصية", + "submit": "متابعة", + "password": { + "title": "تعيين كلمة المرور", + "description": "تعيين كلمة المرور لحسابك", + "submit": "متابعة", + "labels": { + "password": "كلمة المرور", + "confirmPassword": "تأكيد كلمة المرور" + }, + "required": { + "password": "عليك تقديم كلمة مرور!", + "confirmPassword": "هذا الحقل مطلوب" + } + }, + "labels": { + "firstname": "الاسم الأول", + "lastname": "اسم العائلة", + "email": "البريد الإلكتروني" + }, + "required": { + "firstname": "هذا الحقل مطلوب", + "lastname": "هذا الحقل مطلوب", + "email": "هذا الحقل مطلوب" + }, + "errors": { + "couldNotCreateUser": "تعذر إنشاء المستخدم", + "couldNotCreateSession": "تعذر إنشاء الجلسة", + "userNotFound": "المستخدم غير موجود في النظام", + "couldNotLinkIDP": "تعذر ربط IDP بالمستخدم", + "couldNotRegisterUser": "تعذر تسجيل المستخدم", + "sessionMismatch": "بدأ التسجيل في متصفح آخر. يرجى تسجيل الدخول مرة أخرى باستخدام موفر الهوية الخاص بك." + } + }, + "invite": { + "title": "دعوة مستخدم", + "description": "قدم عنوان البريد الإلكتروني واسم المستخدم الذي تريد دعوته.", + "info": "سيتلقى المستخدم بريداً إلكترونياً يحتوي على مزيد من التعليمات.", + "notAllowed": "إعداداتك لا تسمح لك بدعوة المستخدمين.", + "submit": "متابعة", + "success": { + "title": "تمت دعوة المستخدم", + "description": "تم إرسال البريد الإلكتروني بنجاح.", + "verified": "تمت دعوة المستخدم وقد تحقق بالفعل من بريده الإلكتروني.", + "notVerifiedYet": "تمت دعوة المستخدم. سيتلقى بريداً إلكترونياً يحتوي على مزيد من التعليمات.", + "submit": "دعوة مستخدم آخر" + } + }, + "signedin": { + "title": "مرحباً {user}!", + "description": "أنت مسجل الدخول.", + "continue": "متابعة", + "error": { + "title": "خطأ", + "description": "حدث خطأ أثناء محاولة تسجيل الدخول." + } + }, + "verify": { + "userIdMissing": "لم يتم تقديم userId!", + "successTitle": "تم التحقق من المستخدم", + "successDescription": "تم التحقق من المستخدم بنجاح.", + "successContinue": "متابعة", + "setupAuthenticator": "إعداد المصادق", + "verify": { + "title": "التحقق من المستخدم", + "description": "أدخل الرمز المقدم في البريد الإلكتروني للتحقق.", + "noCodeReceived": "لم تستلم رمزاً؟", + "resendCode": "إعادة إرسال الرمز", + "codeSent": "تم إرسال رمز للتو إلى عنوان بريدك الإلكتروني.", + "submit": "متابعة", + "labels": { + "code": "الرمز" + }, + "required": { + "code": "هذا الحقل مطلوب" + } + }, + "errors": { + "couldNotResendEmail": "تعذر إعادة إرسال البريد الإلكتروني", + "couldNotVerifyUser": "تعذر التحقق من المستخدم", + "couldNotVerifyInvite": "تعذر التحقق من الدعوة", + "couldNotVerifyEmail": "تعذر التحقق من البريد الإلكتروني", + "couldNotVerify": "تعذر التحقق", + "couldNotLoadUser": "تعذر تحميل المستخدم", + "couldNotLoadAuthenticators": "تعذر تحميل المصادقين المحتملين", + "couldNotCreateSession": "تعذر إنشاء الجلسة", + "noHostFound": "لم يتم العثور على مضيف", + "userAlreadyVerified": "تم التحقق من المستخدم بالفعل!", + "couldNotResendInvite": "تعذر إعادة إرسال الدعوة", + "inviteSendFailed": "فشل إرسال بريد الدعوة الإلكتروني", + "emailSendFailed": "فشل إرسال بريد التحقق الإلكتروني", + "contextMissing": "حدث خطأ. يرجى المحاولة مرة أخرى." + } + }, + "authenticator": { + "title": "اختيار طريقة المصادقة", + "description": "حدد الطريقة التي ترغب في المصادقة بها", + "noMethodsAvailable": "لا توجد طرق مصادقة متاحة", + "allSetup": "لقد قمت بالفعل بإعداد مصادق!", + "linkWithIDP": "أو الربط مع مزود هوية", + "methods": { + "totp": "تطبيق المصادقة", + "u2f": "العامل الثاني العالمي", + "otpEmail": "رمز عبر البريد الإلكتروني", + "otpSms": "رمز عبر الرسائل القصيرة", + "passkey": "مفاتيح المرور", + "password": "كلمة المرور" + } + }, + "device": { + "usercode": { + "title": "رمز الجهاز", + "description": "أدخل الرمز المعروض على تطبيقك أو جهازك.", + "submit": "متابعة", + "labels": { + "code": "الرمز" + }, + "required": { + "code": "هذا الحقل مطلوب" + } + }, + "request": { + "title": "{appName} يود الاتصال", + "description": "{appName} سيكون لديه حق الوصول إلى:", + "disclaimer": "بالنقر فوق سماح، فإنك تسمح لـ {appName} و Zitadel استخدام معلوماتك وفقاً لشروط الخدمة وسياسات الخصوصية الخاصة بكل منهما. يمكنك إلغاء هذا الوصول في أي وقت.", + "submit": "سماح", + "deny": "رفض" + }, + "scope": { + "openid": "التحقق من هويتك.", + "email": "عرض عنوان بريدك الإلكتروني.", + "profile": "عرض معلومات ملفك الشخصي الكاملة.", + "offline_access": "السماح بالوصول دون اتصال إلى حسابك." + } + }, + "error": { + "noUserCode": "لم يتم تقديم رمز مستخدم!", + "noDeviceRequest": "لم يتم العثور على طلب جهاز.", + "unknownContext": "تعذر الحصول على سياق المستخدم. تأكد من إدخال اسم المستخدم أولاً أو تقديم loginName كمعلمة بحث.", + "sessionExpired": "انتهت صلاحية جلستك أو تتطلب إعادة المصادقة. يرجى تسجيل الدخول مرة أخرى.", + "failedLoading": "فشل تحميل البيانات. يرجى المحاولة مرة أخرى.", + "tryagain": "حاول مرة أخرى", + "couldNotContinueSession": "تعذر المتابعة مع الجلسة - معلومات المستخدم مفقودة", + "couldNotClearSession": "تعذر إنهاء الجلسة. يرجى المحاولة مرة أخرى." + } +} diff --git a/auth/ui/v2/apps/login/locales/de.json b/auth/ui/v2/apps/login/locales/de.json new file mode 100644 index 0000000..3b99cec --- /dev/null +++ b/auth/ui/v2/apps/login/locales/de.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Zurück", + "title": "Anmelden mit Zitadel" + }, + "accounts": { + "title": "Konten", + "description": "Wählen Sie das Konto aus, das Sie verwenden möchten.", + "addAnother": "Ein weiteres Konto hinzufügen", + "noResults": "Keine Konten gefunden", + "verified": "verifiziert", + "expired": "abgelaufen" + }, + "logout": { + "title": "Logout", + "description": "Wählen Sie den Account aus, das Sie entfernen möchten", + "noResults": "Keine Konten gefunden", + "clear": "Session beenden", + "verifiedAt": "Zuletzt aktiv: {time}", + "success": { + "title": "Logout erfolgreich", + "description": "Sie haben sich erfolgreich abgemeldet." + } + }, + "loginname": { + "title": "Willkommen zurück!", + "description": "Geben Sie Ihre Anmeldedaten ein.", + "register": "Neuen Benutzer registrieren", + "submit": "Weiter", + "labels": { + "loginname": "Loginname", + "username": "Benutzername", + "usernameOrPhoneNumber": "Benutzername oder Telefonnummer", + "usernameOrEmail": "Benutzername oder E-Mail" + }, + "required": { + "loginName": "Dieses Feld ist erforderlich" + }, + "errors": { + "internalError": "Ein interner Fehler ist aufgetreten", + "couldNotGetLoginSettings": "Anmeldeeinstellungen konnten nicht abgerufen werden", + "couldNotSearchUsers": "Benutzer konnten nicht durchsucht werden", + "couldNotGetDomain": "Domain konnte nicht abgerufen werden", + "couldNotGetHost": "Host konnte nicht abgerufen werden", + "couldNotStartIDPFlow": "IDP-Ablauf konnte nicht gestartet werden", + "moreThanOneUserFound": "Mehr als ein Benutzer gefunden. Bitte geben Sie einen eindeutigen Identifikator an.", + "userNotFound": "Benutzer im System nicht gefunden", + "couldNotCreateSession": "Sitzung für Benutzer konnte nicht erstellt werden", + "initialUserNotSupported": "Initialer Benutzer wird nicht unterstützt", + "localAuthenticationNotAllowed": "Lokale Authentifizierung nicht zulässig! Wenden Sie sich für weitere Informationen an Ihren Administrator.", + "passkeysNotAllowed": "Passkeys nicht zulässig! Wenden Sie sich für weitere Informationen an Ihren Administrator.", + "couldNotFindIdentityProvider": "Identitätsanbieter konnte nicht gefunden werden.", + "userNotActive": "Das Benutzerkonto ist inaktiv. Wenden Sie sich für weitere Informationen an Ihren Administrator." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Ein Fehler ist aufgetreten", + "multipleUsersFound": "Mehrere Benutzer gefunden", + "userNotFound": "Benutzer im System nicht gefunden" + } + }, + "password": { + "verify": { + "title": "Passwort", + "description": "Geben Sie Ihr Passwort ein.", + "resetPassword": "Passwort zurücksetzen", + "submit": "Weiter", + "labels": { + "password": "Passwort" + }, + "required": { + "password": "Dieses Feld ist erforderlich" + }, + "errors": { + "couldNotVerifyPassword": "Passwort konnte nicht verifiziert werden", + "couldNotResetPassword": "Passwort konnte nicht zurückgesetzt werden" + }, + "info": { + "passwordResetSent": "Passwort wurde zurückgesetzt. Bitte prüfen Sie Ihre E-Mails" + } + }, + "set": { + "title": "Passwort festlegen", + "description": "Legen Sie das Passwort für Ihr Konto fest", + "codeSent": "Ein neuer Code wurde an Ihre E-Mail-Adresse gesendet.", + "noCodeReceived": "Keinen Code erhalten?", + "resend": "Erneut senden", + "submit": "Weiter", + "labels": { + "code": "Code", + "newPassword": "Neues Passwort", + "confirmPassword": "Neues Passwort wiederholen" + }, + "required": { + "code": "Dieses Feld ist erforderlich", + "newPassword": "Bitte geben Sie ein Passwort ein!", + "confirmPassword": "Dieses Feld ist erforderlich" + }, + "errors": { + "couldNotSetPassword": "Passwort konnte nicht gesetzt werden", + "couldNotResetPassword": "Passwort konnte nicht zurückgesetzt werden", + "couldNotVerifyPassword": "Passwort konnte nicht verifiziert werden" + } + }, + "change": { + "title": "Passwort ändern", + "description": "Legen Sie das Passwort für Ihr Konto fest", + "submit": "Weiter", + "labels": { + "currentPassword": "Aktuelles Passwort", + "newPassword": "Neues Passwort", + "confirmPassword": "Neues Passwort wiederholen" + }, + "required": { + "currentPassword": "Bitte geben Sie Ihr aktuelles Passwort ein!", + "newPassword": "Bitte geben Sie ein neues Passwort ein!", + "confirmPassword": "Dieses Feld ist erforderlich" + }, + "errors": { + "currentPasswordInvalid": "Das aktuelle Passwort ist falsch.", + "couldNotChangePassword": "Passwort konnte nicht geändert werden", + "couldNotVerifyPassword": "Passwort konnte nicht verifiziert werden", + "unknownError": "Unbekannter Fehler" + } + }, + "complexity": { + "length": "Muss mindestens {minLength} Zeichen lang sein.", + "hasSymbol": "Muss ein Symbol enthalten.", + "hasNumber": "Muss eine Zahl enthalten.", + "hasUppercase": "Muss einen Großbuchstaben enthalten.", + "hasLowercase": "Muss einen Kleinbuchstaben enthalten.", + "equals": "Passwortbestätigung stimmt überein.", + "matches": "Stimmt überein", + "doesNotMatch": "Stimmt nicht überein" + }, + "errors": { + "noHostFound": "Kein Host gefunden", + "couldNotSendResetLink": "Passwort-Zurücksetzungslink konnte nicht gesendet werden", + "couldNotCreateSessionForUser": "Sitzung für Benutzer konnte nicht erstellt werden", + "couldNotVerifyPassword": "Passwort konnte nicht verifiziert werden", + "failedToAuthenticate": "Authentifizierung fehlgeschlagen. Sie haben {failedAttempts} von {maxPasswordAttempts} Passwortversuchen.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Authentifizierung fehlgeschlagen.", + "accountLockedContactAdmin": " Kontaktieren Sie Ihren Administrator, um Ihr Konto zu entsperren", + "userNotFound": "Benutzer nicht im System gefunden", + "initialUserNotSupported": "Initialbenutzer wird nicht unterstützt", + "userInitialStateNotSupported": "Anfangszustand des Benutzers wird nicht unterstützt", + "codeOrVerificationRequired": "Sie müssen einen Code angeben oder eine gültige Benutzerverifizierung durchführen", + "verificationRequired": "Die Benutzerverifizierung muss durchgeführt werden", + "couldNotLoadSession": "Sitzung konnte nicht geladen werden", + "couldNotLoadAuthMethods": "Authentifizierungsmethoden konnten nicht geladen werden", + "failedPrecondition": "Vorbedingung fehlgeschlagen", + "sessionNotValid": "Sitzung ist nicht gültig", + "passwordVerificationMissing": "Passwort-Verifizierung fehlt.", + "passwordVerificationTooOld": "Passwort-Verifizierung ist zu alt. Bitte verifizieren Sie Ihr Passwort erneut.", + "passwordResetNotAllowed": "Das Zurücksetzen des Passworts ist nicht zulässig. Wenden Sie sich für weitere Informationen an Ihren Administrator.", + "localAuthenticationNotAllowed": "Lokale Authentifizierung nicht zulässig! Wenden Sie sich für weitere Informationen an Ihren Administrator." + } + }, + "idp": { + "title": "Mit SSO anmelden", + "description": "Wählen Sie einen der folgenden Anbieter, um sich anzumelden", + "orSignInWith": "oder melden Sie sich an mit", + "signInWithApple": "Mit Apple anmelden", + "signInWithGoogle": "Mit Google anmelden", + "signInWithAzureAD": "Mit AzureAD anmelden", + "signInWithGithub": "Mit GitHub anmelden", + "signInWithGitlab": "Mit GitLab anmelden", + "signInWithZitadel": "Mit Zitadel anmelden", + "loginError": { + "title": "Anmeldung fehlgeschlagen", + "description": "Beim Anmelden ist ein Fehler aufgetreten." + }, + "linkingError": { + "title": "Konto-Verknüpfung fehlgeschlagen", + "description": "Beim Verknüpfen Ihres Kontos ist ein Fehler aufgetreten." + }, + "completeRegister": { + "title": "Registrierung abschließen", + "description": "Bitte vervollständige die Registrierung, um dein Konto zu erstellen." + }, + "accountNotFound": { + "title": "Konto nicht gefunden", + "description": "Wir konnten kein Konto finden, das mit Ihren Identitätsanbieter-Anmeldedaten verknüpft ist.", + "info": "Es wurde kein bestehendes Konto gefunden. Bitte melden Sie sich mit einem bestehenden Konto an oder wenden Sie sich an Ihren Administrator.", + "backToLogin": "Zurück zur Anmeldung" + }, + "registrationFailed": { + "title": "Registrierung nicht verfügbar", + "description": "Wir konnten den Registrierungsprozess nicht abschließen.", + "info": "Die Organisation für die Registrierung konnte nicht ermittelt werden. Bitte wenden Sie sich an Ihren Administrator.", + "backToLogin": "Zurück zur Anmeldung" + }, + "processing": { + "message": "Authentifizierung wird verarbeitet...", + "noRedirect": "Keine Weiterleitung oder Fehler vom Server erhalten", + "unexpectedError": "Ein unerwarteter Fehler ist aufgetreten" + }, + "errors": { + "missingParameters": "Erforderliche Parameter fehlen", + "missingIdpInfo": "IDP-Informationen fehlen", + "idpNotFound": "Identitätsanbieter nicht gefunden", + "linkingNotAllowed": "Verknüpfung ist für diesen Identitätsanbieter nicht erlaubt", + "linkingFailed": "Verknüpfung des Identitätsanbieters zum Konto fehlgeschlagen", + "autoLinkingFailed": "Automatische Verknüpfung des Kontos fehlgeschlagen", + "userCreationFailed": "Erstellen des Benutzerkontos fehlgeschlagen", + "orgResolutionFailed": "Organisation für Registrierung konnte nicht ermittelt werden", + "sessionCreationFailed": "Sitzung konnte nicht erstellt oder Weiterleitung konnte nicht ermittelt werden", + "unknownError": "Ein unbekannter Fehler ist aufgetreten" + } + }, + "ldap": { + "title": "LDAP Login", + "description": "Geben Sie Ihre LDAP-Anmeldedaten ein.", + "submit": "Weiter", + "labels": { + "username": "Benutzername", + "password": "Passwort" + }, + "required": { + "username": "Dieses Feld ist erforderlich", + "password": "Dieses Feld ist erforderlich" + } + }, + "mfa": { + "verify": { + "title": "Bestätigen Sie Ihre Identität", + "description": "Wählen Sie einen der folgenden Faktoren.", + "noResults": "Keine zweiten Faktoren verfügbar, um sie einzurichten." + }, + "set": { + "title": "2-Faktor einrichten", + "description": "Wählen Sie einen der folgenden zweiten Faktoren.", + "skip": "Überspringen" + } + }, + "otp": { + "verify": { + "title": "2-Faktor bestätigen", + "totpDescription": "Geben Sie den Code aus Ihrer Authentifizierungs-App ein.", + "smsDescription": "Geben Sie den Code ein, den Sie per SMS erhalten haben.", + "emailDescription": "Geben Sie den Code ein, den Sie per E-Mail erhalten haben.", + "noCodeReceived": "Keinen Code erhalten?", + "resendCode": "Code erneut senden", + "resendCodeIn": "Code erneut senden ({seconds}s)", + "submit": "Weiter", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dieses Feld ist erforderlich" + } + }, + "set": { + "title": "2-Faktor einrichten", + "totpDescription": "Scannen Sie den QR-Code mit Ihrer Authentifizierungs-App.", + "smsDescription": "Geben Sie Ihre Telefonnummer ein, um einen Code per SMS zu erhalten.", + "emailDescription": "Geben Sie Ihre E-Mail-Adresse ein, um einen Code per E-Mail zu erhalten.", + "totpRegisterDescription": "Scannen Sie den QR-Code oder navigieren Sie manuell zur URL.", + "emailAddDescription": "Verwenden Sie einen Einmalcode, der an Ihre verifizierte E-Mail-Adresse gesendet wird, als zweiten Faktor.", + "smsAddDescription": "Verwenden Sie einen Einmalcode, der an Ihre verifizierte Telefonnummer gesendet wird, als zweiten Faktor.", + "add": "Hinzufügen", + "emailAdded": "Code per E-Mail hinzugefügt.", + "smsAdded": "Code per SMS hinzugefügt.", + "submit": "Weiter", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dieses Feld ist erforderlich" + } + }, + "errors": { + "couldNotRequestChallenge": "OTP-Challenge konnte nicht angefordert werden", + "couldNotVerifyCode": "OTP-Code konnte nicht verifiziert werden", + "couldNotGetSession": "Ihre Sitzung konnte nicht geladen werden. Bitte melden Sie sich erneut an.", + "invalidMethod": "Dieser zweite Faktor wird nicht unterstützt.", + "couldNotAddEmail": "Code per E-Mail konnte nicht hinzugefügt werden.", + "couldNotAddSms": "Code per SMS konnte nicht hinzugefügt werden.", + "emailNotVerified": "Verifizieren Sie Ihre E-Mail-Adresse, bevor Sie Codes per E-Mail hinzufügen.", + "phoneNotVerified": "Verifizieren Sie Ihre Telefonnummer, bevor Sie Codes per SMS hinzufügen." + } + }, + "passkey": { + "verify": { + "title": "Mit einem Passkey authentifizieren", + "description": "Ihr Gerät wird nach Ihrem Fingerabdruck, Gesicht oder Bildschirmsperre fragen", + "usePassword": "Passwort verwenden", + "submit": "Weiter", + "errors": { + "couldNotRequestChallenge": "Passkey-Challenge konnte nicht angefordert werden", + "couldNotVerifyPasskey": "Passkey konnte nicht verifiziert werden", + "noResponseReceived": "Passkey-Verifizierung fehlgeschlagen - keine Antwort erhalten", + "noRedirectProvided": "Passkey-Verifizierung abgeschlossen, aber keine Weiterleitung bereitgestellt", + "couldNotRetrievePasskey": "Fehler beim Abrufen des Passkeys", + "verificationCancelled": "Passkey-Verifizierung wurde abgebrochen", + "verificationFailed": "Fehler bei der Passkey-Verifizierung", + "couldNotFindSession": "Sitzung konnte nicht gefunden werden", + "couldNotUpdateSession": "Sitzung konnte nicht aktualisiert werden", + "userNotFound": "Benutzer nicht im System gefunden", + "couldNotDetermineRedirect": "Weiterleitungs-URL nach Passkey-Verifizierung konnte nicht ermittelt werden" + } + }, + "set": { + "title": "Passkey einrichten", + "description": "Ihr Gerät wird nach Ihrem Fingerabdruck, Gesicht oder Bildschirmsperre fragen", + "info": { + "description": "Ein Passkey ist eine Authentifizierungsmethode auf einem Gerät wie Ihr Fingerabdruck, Apple FaceID oder ähnliches.", + "link": "Passkey-Authentifizierung" + }, + "skip": "Überspringen", + "submit": "Weiter" + } + }, + "u2f": { + "verify": { + "title": "2-Faktor bestätigen", + "description": "Bestätigen Sie Ihr Konto mit Ihrem Gerät." + }, + "set": { + "title": "2-Faktor einrichten", + "description": "Richten Sie ein Gerät als zweiten Faktor ein.", + "submit": "Weiter" + } + }, + "register": { + "methods": { + "passkey": "Passkey", + "password": "Passwort" + }, + "disabled": { + "title": "Registrierung deaktiviert", + "description": "Die Registrierung ist deaktiviert. Bitte wenden Sie sich an den Administrator." + }, + "missingdata": { + "title": "Registrierung fehlgeschlagen", + "description": "Einige Daten fehlen. Bitte überprüfen Sie Ihre Eingaben." + }, + "title": "Registrieren", + "description": "Erstellen Sie Ihr Zitadel-Konto.", + "noMethodAvailableWarning": "Keine Authentifizierungsmethode verfügbar. Bitte wenden Sie sich an den Administrator.", + "selectMethod": "Wählen Sie die Methode, mit der Sie sich authentifizieren möchten", + "agreeTo": "Um sich zu registrieren, müssen Sie den Nutzungsbedingungen zustimmen", + "termsOfService": "Nutzungsbedingungen", + "privacyPolicy": "Datenschutzrichtlinie", + "submit": "Weiter", + "password": { + "title": "Passwort festlegen", + "description": "Legen Sie das Passwort für Ihr Konto fest", + "submit": "Weiter", + "labels": { + "password": "Passwort", + "confirmPassword": "Neues Passwort wiederholen" + }, + "required": { + "password": "Bitte geben Sie ein Passwort ein!", + "confirmPassword": "Dieses Feld ist erforderlich" + } + }, + "labels": { + "firstname": "Vorname", + "lastname": "Nachname", + "email": "E-Mail" + }, + "required": { + "firstname": "Dieses Feld ist erforderlich", + "lastname": "Dieses Feld ist erforderlich", + "email": "Dieses Feld ist erforderlich" + }, + "errors": { + "couldNotCreateUser": "Benutzer konnte nicht erstellt werden", + "couldNotCreateSession": "Sitzung konnte nicht erstellt werden", + "userNotFound": "Benutzer nicht im System gefunden", + "couldNotLinkIDP": "IDP konnte nicht mit dem Benutzer verknüpft werden", + "couldNotRegisterUser": "Benutzer konnte nicht registriert werden", + "sessionMismatch": "Die Registrierung wurde in einem anderen Browser gestartet. Bitte melden Sie sich erneut bei Ihrem Identitätsanbieter an." + } + }, + "invite": { + "title": "Benutzer einladen", + "description": "Geben Sie die E-Mail-Adresse des Benutzers ein, den Sie einladen möchten.", + "info": "Der Benutzer erhält eine E-Mail mit einem Link, um sich zu registrieren.", + "notAllowed": "Sie haben keine Berechtigung, Benutzer einzuladen.", + "submit": "Einladen", + "success": { + "title": "Einladung erfolgreich", + "description": "Der Benutzer wurde erfolgreich eingeladen.", + "verified": "Der Benutzer wurde eingeladen und hat seine E-Mail bereits verifiziert.", + "notVerifiedYet": "Der Benutzer wurde eingeladen. Er erhält eine E-Mail mit weiteren Anweisungen.", + "submit": "Weiteren Benutzer einladen" + } + }, + "signedin": { + "title": "Willkommen {user}!", + "description": "Sie sind angemeldet.", + "continue": "Weiter", + "error": { + "title": "Fehler", + "description": "Ein Fehler ist aufgetreten." + } + }, + "verify": { + "userIdMissing": "Keine Benutzer-ID angegeben!", + "successTitle": "Benutzer verifiziert", + "successDescription": "Der Benutzer wurde erfolgreich verifiziert.", + "successContinue": "Weiter", + "setupAuthenticator": "Authentifikator einrichten", + "verify": { + "title": "Benutzer verifizieren", + "description": "Geben Sie den Code ein, der in der Bestätigungs-E-Mail angegeben ist.", + "noCodeReceived": "Keinen Code erhalten?", + "resendCode": "Code erneut senden", + "codeSent": "Ein Code wurde gerade an Ihre E-Mail-Adresse gesendet.", + "submit": "Weiter", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dieses Feld ist erforderlich" + } + }, + "errors": { + "couldNotResendEmail": "E-Mail konnte nicht erneut gesendet werden", + "couldNotVerifyUser": "Benutzer konnte nicht verifiziert werden", + "couldNotVerifyInvite": "Einladung konnte nicht verifiziert werden", + "couldNotVerifyEmail": "E-Mail konnte nicht verifiziert werden", + "couldNotVerify": "Konnte nicht verifizieren", + "couldNotLoadUser": "Benutzer konnte nicht geladen werden", + "couldNotLoadAuthenticators": "Mögliche Authentifikatoren konnten nicht geladen werden", + "couldNotCreateSession": "Sitzung konnte nicht erstellt werden", + "noHostFound": "Kein Host gefunden", + "userAlreadyVerified": "Benutzer ist bereits verifiziert!", + "couldNotResendInvite": "Einladung konnte nicht erneut gesendet werden", + "inviteSendFailed": "Einladungs-E-Mail konnte nicht gesendet werden", + "emailSendFailed": "Verifizierungs-E-Mail konnte nicht gesendet werden", + "contextMissing": "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut." + } + }, + "authenticator": { + "title": "Authentifizierungsmethode auswählen", + "description": "Wählen Sie die Methode, mit der Sie sich authentifizieren möchten.", + "noMethodsAvailable": "Keine Authentifizierungsmethoden verfügbar", + "allSetup": "Sie haben bereits einen Authentifikator eingerichtet!", + "linkWithIDP": "oder verknüpfe mit einem Identitätsanbieter", + "methods": { + "totp": "Authentifizierungs-App", + "u2f": "Universeller zweiter Faktor", + "otpEmail": "Code per E-Mail", + "otpSms": "Code per SMS", + "passkey": "Passkeys", + "password": "Passwort" + } + }, + "device": { + "usercode": { + "title": "Gerätecode", + "description": "Geben Sie den Code ein.", + "submit": "Weiter", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dieses Feld ist erforderlich" + } + }, + "request": { + "title": "{appName} möchte eine Verbindung herstellen:", + "disclaimer": "{appName} hat Zugriff auf:", + "description": "Durch Klicken auf Zulassen erlauben Sie {appName} und Zitadel, Ihre Informationen gemäß ihren jeweiligen Nutzungsbedingungen und Datenschutzrichtlinien zu verwenden. Sie können diesen Zugriff jederzeit widerrufen.", + "submit": "Zulassen", + "deny": "Ablehnen" + }, + "scope": { + "openid": "Überprüfen Ihrer Identität.", + "email": "Zugriff auf Ihre E-Mail-Adresse.", + "profile": "Zugriff auf Ihre vollständigen Profilinformationen.", + "offline_access": "Erlauben Sie den Offline-Zugriff auf Ihr Konto." + } + }, + "error": { + "noUserCode": "Kein Benutzercode angegeben!", + "noDeviceRequest": " Es wurde keine Geräteanforderung gefunden. Bitte überprüfen Sie die URL.", + "unknownContext": "Der Kontext des Benutzers konnte nicht ermittelt werden. Stellen Sie sicher, dass Sie zuerst den Benutzernamen eingeben oder einen loginName als Suchparameter angeben.", + "sessionExpired": "Ihre Sitzung ist abgelaufen oder erfordert eine erneute Authentifizierung. Bitte melden Sie sich erneut an.", + "failedLoading": "Daten konnten nicht geladen werden. Bitte versuchen Sie es erneut.", + "tryagain": "Erneut versuchen", + "couldNotContinueSession": "Sitzung konnte nicht fortgesetzt werden - fehlende Benutzerinformationen", + "couldNotClearSession": "Die Sitzung konnte nicht beendet werden. Bitte versuchen Sie es erneut." + } +} diff --git a/auth/ui/v2/apps/login/locales/en.json b/auth/ui/v2/apps/login/locales/en.json new file mode 100644 index 0000000..cbde557 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/en.json @@ -0,0 +1,491 @@ +{ + "common": { + "back": "Back", + "title": "Login with Zitadel" + }, + "accounts": { + "title": "Accounts", + "description": "Select the account you want to use.", + "addAnother": "Add another account", + "noResults": "No accounts found", + "verified": "verified", + "expired": "expired" + }, + "logout": { + "title": "Logout", + "description": "Click an account to end the session", + "noResults": "No accounts found", + "clear": "End Session", + "verifiedAt": "Last active: {time}", + "success": { + "title": "Logout successful", + "description": "You have successfully logged out." + } + }, + "loginname": { + "title": "Welcome back!", + "description": "Enter your login details.", + "register": "Register new user", + "submit": "Continue", + "labels": { + "loginname": "Loginname", + "username": "Username", + "usernameOrPhoneNumber": "Username or phone number", + "usernameOrEmail": "Username or email" + }, + "required": { + "loginName": "This field is required" + }, + "errors": { + "internalError": "An internal error occurred", + "couldNotGetLoginSettings": "Could not get login settings", + "couldNotSearchUsers": "Could not search users", + "couldNotGetDomain": "Could not get domain", + "couldNotGetHost": "Could not get host", + "couldNotStartIDPFlow": "Could not start IDP flow", + "moreThanOneUserFound": "More than one user found. Provide a unique identifier.", + "userNotFound": "User not found in the system", + "couldNotCreateSession": "Could not create session for user", + "initialUserNotSupported": "Initial User not supported", + "localAuthenticationNotAllowed": "Local authentication is not allowed! Contact your administrator for more information.", + "passkeysNotAllowed": "Passkeys not allowed! Contact your administrator for more information.", + "couldNotFindIdentityProvider": "Could not find identity provider.", + "userNotActive": "User is not active. Contact your administrator for more information." + } + }, + "zitadel": { + "errors": { + "errorOccured": "An error occurred", + "multipleUsersFound": "Multiple users found", + "userNotFound": "User not found in the system" + } + }, + "password": { + "verify": { + "title": "Password", + "description": "Enter your password.", + "resetPassword": "Reset Password", + "submit": "Continue", + "labels": { + "password": "Password" + }, + "required": { + "password": "This field is required" + }, + "errors": { + "couldNotVerifyPassword": "Could not verify password", + "couldNotResetPassword": "Could not reset password" + }, + "info": { + "passwordResetSent": "Password was reset. Please check your email" + } + }, + "set": { + "title": "Set Password", + "description": "Set the password for your account", + "codeSent": "A new code has been sent to your email address.", + "noCodeReceived": "Didn't receive a code?", + "resend": "Resend code", + "submit": "Continue", + "labels": { + "code": "Code", + "newPassword": "New Password", + "confirmPassword": "Confirm Password" + }, + "required": { + "code": "This field is required", + "newPassword": "You have to provide a password!", + "confirmPassword": "This field is required" + }, + "errors": { + "couldNotSetPassword": "Could not set password", + "couldNotResetPassword": "Could not reset password", + "couldNotVerifyPassword": "Could not verify password" + } + }, + "change": { + "title": "Change Password", + "description": "Set the password for your account", + "submit": "Continue", + "labels": { + "currentPassword": "Current Password", + "newPassword": "New Password", + "confirmPassword": "Confirm Password" + }, + "required": { + "currentPassword": "You have to provide your current password!", + "newPassword": "You have to provide a new password!", + "confirmPassword": "This field is required" + }, + "errors": { + "currentPasswordInvalid": "Current password is incorrect.", + "couldNotChangePassword": "Could not change password", + "couldNotVerifyPassword": "Could not verify password", + "unknownError": "Unknown error" + } + }, + "complexity": { + "length": "Must be at least {minLength} characters long.", + "hasSymbol": "Must include a symbol.", + "hasNumber": "Must include a number.", + "hasUppercase": "Must include an uppercase letter.", + "hasLowercase": "Must include a lowercase letter.", + "equals": "Password confirmation matched.", + "matches": "Matches", + "doesNotMatch": "Doesn't match" + }, + "errors": { + "noHostFound": "No host found", + "couldNotSendResetLink": "Could not send Password Reset Link", + "couldNotCreateSessionForUser": "Could not create session for user", + "couldNotVerifyPassword": "Could not verify password", + "failedToAuthenticate": "Failed to authenticate. You had {failedAttempts} of {maxPasswordAttempts} password attempts.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Failed to authenticate.", + "accountLockedContactAdmin": " Contact your administrator to unlock your account", + "userNotFound": "User not found in the system", + "initialUserNotSupported": "Initial User not supported", + "userInitialStateNotSupported": "User Initial State is not supported", + "codeOrVerificationRequired": "You have to provide a code or have a valid User Verification Check", + "verificationRequired": "User Verification Check has to be done", + "couldNotLoadSession": "Could not load session", + "couldNotLoadAuthMethods": "Could not load auth methods", + "failedPrecondition": "Failed precondition", + "sessionNotValid": "Session is not valid", + "passwordVerificationMissing": "Password verification is missing.", + "passwordVerificationTooOld": "Password verification is too old. Please verify your password again.", + "passwordResetNotAllowed": "Password reset is not allowed. Contact your administrator for more information.", + "localAuthenticationNotAllowed": "Local authentication is not allowed! Contact your administrator for more information." + } + }, + "idp": { + "title": "Sign in with SSO", + "description": "Select one of the following providers to sign in", + "orSignInWith": "or sign in with", + "signInWithApple": "Sign in with Apple", + "signInWithGoogle": "Sign in with Google", + "signInWithAzureAD": "Sign in with AzureAD", + "signInWithGithub": "Sign in with GitHub", + "signInWithGitlab": "Sign in with GitLab", + "signInWithZitadel": "Sign in with Zitadel", + "loginError": { + "title": "Login failed", + "description": "An error occurred while trying to login." + }, + "linkingError": { + "title": "Account linking failed", + "description": "An error occurred while trying to link your account." + }, + "completeRegister": { + "title": "Complete your data", + "description": "You need to complete your registration by providing your email address and name." + }, + "accountNotFound": { + "title": "Account Not Found", + "description": "We couldn't find an account associated with your identity provider credentials.", + "info": "No existing account was found. Please sign in with an existing account or contact your administrator for assistance.", + "backToLogin": "Back to Login" + }, + "registrationFailed": { + "title": "Registration Not Available", + "description": "We couldn't complete the registration process.", + "info": "Unable to determine the organization for registration. Please contact your administrator for assistance.", + "backToLogin": "Back to Login" + }, + "processing": { + "message": "Processing authentication...", + "noRedirect": "No redirect or error returned from server", + "unexpectedError": "An unexpected error occurred" + }, + "errors": { + "missingParameters": "Missing required parameters", + "missingIdpInfo": "IDP information missing", + "idpNotFound": "Identity provider not found", + "linkingNotAllowed": "Linking is not allowed for this identity provider", + "linkingFailed": "Failed to link identity provider to account", + "autoLinkingFailed": "Failed to automatically link account", + "userCreationFailed": "Failed to create user account", + "orgResolutionFailed": "Could not determine organization for registration", + "sessionCreationFailed": "Could not create session or determine redirect", + "unknownError": "An unknown error occurred" + } + }, + "ldap": { + "title": "LDAP Login", + "description": "Enter your LDAP credentials.", + "submit": "Continue", + "labels": { + "username": "Username", + "password": "Password" + }, + "required": { + "username": "This field is required", + "password": "This field is required" + } + }, + "mfa": { + "verify": { + "title": "Verify your identity", + "description": "Choose one of the following factors.", + "noResults": "No second factors available to setup." + }, + "set": { + "title": "Set up 2-Factor", + "description": "Choose one of the following second factors.", + "skip": "Skip" + } + }, + "otp": { + "verify": { + "title": "Verify 2-Factor", + "totpDescription": "Enter the code from your authenticator app.", + "smsDescription": "Enter the code you received via SMS.", + "emailDescription": "Enter the code you received via email.", + "noCodeReceived": "Didn't receive a code?", + "resendCode": "Resend code", + "resendCodeIn": "Resend code ({seconds}s)", + "submit": "Continue", + "labels": { + "code": "Code" + }, + "required": { + "code": "This field is required" + } + }, + "set": { + "title": "Set up 2-Factor", + "totpDescription": "Scan the QR code with your authenticator app.", + "smsDescription": "Enter your phone number to receive a code via SMS.", + "emailDescription": "Enter your email address to receive a code via email.", + "totpRegisterDescription": "Scan the QR Code or navigate to the URL manually.", + "emailAddDescription": "Use a one-time code sent to your verified email address as a second factor.", + "smsAddDescription": "Use a one-time code sent to your verified phone number as a second factor.", + "add": "Add", + "emailAdded": "Code via email added.", + "smsAdded": "Code via SMS added.", + "submit": "Continue", + "labels": { + "code": "Code" + }, + "required": { + "code": "This field is required" + } + }, + "errors": { + "couldNotRequestChallenge": "Could not request OTP challenge", + "couldNotVerifyCode": "Could not verify OTP code", + "couldNotGetSession": "Your session could not be loaded. Please sign in again.", + "invalidMethod": "This second factor is not supported.", + "couldNotAddEmail": "Code via email could not be added.", + "couldNotAddSms": "Code via SMS could not be added.", + "emailNotVerified": "Verify your email address before adding codes via email.", + "phoneNotVerified": "Verify your phone number before adding codes via SMS." + } + }, + "passkey": { + "verify": { + "title": "Authenticate with a passkey", + "description": "Your device will ask for your fingerprint, face, or screen lock", + "usePassword": "Use password", + "submit": "Continue", + "errors": { + "couldNotRequestChallenge": "Could not request passkey challenge", + "couldNotVerifyPasskey": "Could not verify passkey", + "noResponseReceived": "Passkey verification failed - no response received", + "noRedirectProvided": "Passkey verification completed but no redirect was provided", + "couldNotRetrievePasskey": "An error occurred while retrieving passkey", + "verificationCancelled": "Passkey verification was cancelled", + "verificationFailed": "An error occurred during passkey verification", + "couldNotFindSession": "Could not find session", + "couldNotUpdateSession": "Could not update session", + "userNotFound": "User not found in the system", + "couldNotDetermineRedirect": "Could not determine redirect URL after passkey verification" + } + }, + "set": { + "title": "Setup a passkey", + "description": "Your device will ask for your fingerprint, face, or screen lock", + "info": { + "description": "A passkey is an authentication method on a device like your fingerprint, Apple FaceID or similar. ", + "link": "Passkey Authentication" + }, + "skip": "Skip", + "submit": "Continue" + } + }, + "u2f": { + "verify": { + "title": "Verify 2-Factor", + "description": "Verify your account with your device." + }, + "set": { + "title": "Set up 2-Factor", + "description": "Set up a device as a second factor.", + "submit": "Continue" + } + }, + "register": { + "methods": { + "passkey": "Passkey", + "password": "Password" + }, + "disabled": { + "title": "Registration disabled", + "description": "The registration is disabled. Please contact your administrator." + }, + "missingdata": { + "title": "Missing data", + "description": "Provide email, first and last name to register." + }, + "title": "Register", + "description": "Create your Zitadel account.", + "noMethodAvailableWarning": "No authentication method available. Please contact your administrator.", + "selectMethod": "Select the method you would like to authenticate", + "agreeTo": "To register you must agree to the terms and conditions", + "termsOfService": "Terms of Service", + "privacyPolicy": "Privacy Policy", + "submit": "Continue", + "password": { + "title": "Set Password", + "description": "Set the password for your account", + "submit": "Continue", + "labels": { + "password": "Password", + "confirmPassword": "Confirm Password" + }, + "required": { + "password": "You have to provide a password!", + "confirmPassword": "This field is required" + } + }, + "labels": { + "firstname": "First name", + "lastname": "Last name", + "email": "E-mail" + }, + "required": { + "firstname": "This field is required", + "lastname": "This field is required", + "email": "This field is required" + }, + "errors": { + "couldNotCreateUser": "Could not create user", + "couldNotCreateSession": "Could not create session", + "userNotFound": "User not found in the system", + "couldNotLinkIDP": "Could not link IDP to user", + "couldNotRegisterUser": "Could not register user", + "sessionMismatch": "The registration was started in another browser. Please sign in with your identity provider again." + } + }, + "invite": { + "title": "Invite User", + "description": "Provide the email address and the name of the user you want to invite.", + "info": "The user will receive an email with further instructions.", + "notAllowed": "Your settings do not allow you to invite users.", + "submit": "Continue", + "success": { + "title": "User invited", + "description": "The email has successfully been sent.", + "verified": "The user has been invited and has already verified his email.", + "notVerifiedYet": "The user has been invited. They will receive an email with further instructions.", + "submit": "Invite another user" + } + }, + "signedin": { + "title": "Welcome {user}!", + "description": "You are signed in.", + "continue": "Continue", + "error": { + "title": "Error", + "description": "An error occurred while trying to sign in." + } + }, + "verify": { + "userIdMissing": "No userId provided!", + "successTitle": "User verified", + "successDescription": "The user has been verified successfully.", + "successContinue": "Continue", + "setupAuthenticator": "Setup authenticator", + "verify": { + "title": "Verify user", + "description": "Enter the Code provided in the verification email.", + "noCodeReceived": "Didn't receive a code?", + "resendCode": "Resend code", + "codeSent": "A new code has just been sent to your email address.", + "submit": "Continue", + "labels": { + "code": "Code" + }, + "required": { + "code": "This field is required" + } + }, + "errors": { + "couldNotResendEmail": "Could not resend email", + "couldNotVerifyUser": "Could not verify user", + "couldNotVerifyInvite": "Could not verify invite", + "couldNotVerifyEmail": "Could not verify email", + "couldNotVerify": "Could not verify", + "couldNotLoadUser": "Could not load user", + "couldNotLoadAuthenticators": "Could not load possible authenticators", + "couldNotCreateSession": "Could not create session", + "noHostFound": "No host found", + "userAlreadyVerified": "User is already verified!", + "couldNotResendInvite": "Could not resend invite", + "inviteSendFailed": "Failed to send invitation email", + "emailSendFailed": "Failed to send verification email", + "contextMissing": "An error occurred. Please try again." + } + }, + "authenticator": { + "title": "Choose authentication method", + "description": "Select the method you would like to authenticate", + "noMethodsAvailable": "No authentication methods available", + "allSetup": "You have already setup an authenticator!", + "linkWithIDP": "or link with an Identity Provider", + "methods": { + "totp": "Authenticator App", + "u2f": "Universal Second Factor", + "otpEmail": "Code via Email", + "otpSms": "Code via SMS", + "passkey": "Passkeys", + "password": "Password" + } + }, + "device": { + "usercode": { + "title": "Device code", + "description": "Enter the code displayed on your app or device.", + "submit": "Continue", + "labels": { + "code": "Code" + }, + "required": { + "code": "This field is required" + } + }, + "request": { + "title": "{appName} would like to connect", + "description": "{appName} will have access to:", + "disclaimer": "By clicking Allow, you allow {appName} and Zitadel to use your information in accordance with their respective terms of service and privacy policies. You can revoke this access at any time.", + "usercode": "Code displayed on your device:", + "submit": "Allow", + "deny": "Deny" + }, + "scope": { + "openid": "Verify your identity.", + "email": "View your email address.", + "profile": "View your full profile information.", + "offline_access": "Allow offline access to your account." + } + }, + "error": { + "noUserCode": "No user code provided!", + "noDeviceRequest": "No device request found.", + "unknownContext": "Could not get the context of the user. Make sure to enter the username first or provide a loginName as searchParam.", + "sessionExpired": "Your session has expired or requires re-authentication. Please sign in again.", + "failedLoading": "Failed to load data. Please try again.", + "tryagain": "Try Again", + "couldNotContinueSession": "Could not continue with session - missing user information", + "couldNotClearSession": "Could not end the session. Please try again." + } +} diff --git a/auth/ui/v2/apps/login/locales/es.json b/auth/ui/v2/apps/login/locales/es.json new file mode 100644 index 0000000..c56f2c7 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/es.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Atrás", + "title": "Iniciar sesión con Zitadel" + }, + "accounts": { + "title": "Cuentas", + "description": "Seleccione la cuenta que desea utilizar.", + "addAnother": "Agregar otra cuenta", + "noResults": "No se encontraron cuentas", + "verified": "verificado", + "expired": "expirado" + }, + "logout": { + "title": "Cerrar sesión", + "description": "Selecciona la cuenta que deseas eliminar", + "noResults": "No se encontraron cuentas", + "clear": "Eliminar sesión", + "verifiedAt": "Última actividad: {time}", + "success": { + "title": "Cierre de sesión exitoso", + "description": "Has cerrado sesión correctamente." + } + }, + "loginname": { + "title": "¡Bienvenido de nuevo!", + "description": "Introduce tus datos de acceso.", + "register": "Registrar nuevo usuario", + "submit": "Continuar", + "labels": { + "loginname": "Nombre de inicio de sesión", + "username": "Nombre de usuario", + "usernameOrPhoneNumber": "Nombre de usuario o número de teléfono", + "usernameOrEmail": "Nombre de usuario o correo electrónico" + }, + "required": { + "loginName": "Este campo es obligatorio" + }, + "errors": { + "internalError": "Se produjo un error interno", + "couldNotGetLoginSettings": "No se pudieron obtener los ajustes de inicio de sesión", + "couldNotSearchUsers": "No se pudieron buscar usuarios", + "couldNotGetDomain": "No se pudo obtener el dominio", + "couldNotGetHost": "No se pudo obtener el host", + "couldNotStartIDPFlow": "No se pudo iniciar el flujo de IDP", + "moreThanOneUserFound": "Se encontró más de un usuario. Proporcione un identificador único.", + "userNotFound": "Usuario no encontrado en el sistema", + "couldNotCreateSession": "No se pudo crear la sesión para el usuario", + "initialUserNotSupported": "Usuario inicial no admitido", + "localAuthenticationNotAllowed": "¡La autenticación local no está permitida! Contacte con su administrador para más información.", + "passkeysNotAllowed": "Las passkeys no están permitidas. Contacte con su administrador para más información.", + "couldNotFindIdentityProvider": "No se pudo encontrar el proveedor de identidad.", + "userNotActive": "El usuario no está activo. Contacte con su administrador para más información." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Ocurrió un error", + "multipleUsersFound": "Se encontraron varios usuarios", + "userNotFound": "Usuario no encontrado en el sistema" + } + }, + "password": { + "verify": { + "title": "Contraseña", + "description": "Introduce tu contraseña.", + "resetPassword": "Restablecer contraseña", + "submit": "Continuar", + "labels": { + "password": "Contraseña" + }, + "required": { + "password": "Este campo es obligatorio" + }, + "errors": { + "couldNotVerifyPassword": "No se pudo verificar la contraseña", + "couldNotResetPassword": "No se pudo restablecer la contraseña" + }, + "info": { + "passwordResetSent": "Se restableció la contraseña. Por favor, revise su correo electrónico" + } + }, + "set": { + "title": "Establecer Contraseña", + "description": "Establece la contraseña para tu cuenta", + "codeSent": "Se ha enviado un nuevo código a su dirección de correo electrónico.", + "noCodeReceived": "¿No recibiste un código?", + "resend": "Reenviar código", + "submit": "Continuar", + "labels": { + "code": "Código", + "newPassword": "Nueva contraseña", + "confirmPassword": "Confirmar contraseña" + }, + "required": { + "code": "Este campo es obligatorio", + "newPassword": "¡Debes proporcionar una contraseña!", + "confirmPassword": "Este campo es obligatorio" + }, + "errors": { + "couldNotSetPassword": "No se pudo establecer la contraseña", + "couldNotResetPassword": "No se pudo restablecer la contraseña", + "couldNotVerifyPassword": "No se pudo verificar la contraseña" + } + }, + "change": { + "title": "Cambiar Contraseña", + "description": "Establece la contraseña para tu cuenta", + "submit": "Continuar", + "labels": { + "currentPassword": "Contraseña actual", + "newPassword": "Nueva contraseña", + "confirmPassword": "Confirmar contraseña" + }, + "required": { + "currentPassword": "¡Debes proporcionar tu contraseña actual!", + "newPassword": "¡Debes proporcionar una nueva contraseña!", + "confirmPassword": "Este campo es obligatorio" + }, + "errors": { + "currentPasswordInvalid": "La contraseña actual es incorrecta.", + "couldNotChangePassword": "No se pudo cambiar la contraseña", + "couldNotVerifyPassword": "No se pudo verificar la contraseña", + "unknownError": "Error desconocido" + } + }, + "complexity": { + "length": "Debe tener al menos {minLength} caracteres de longitud.", + "hasSymbol": "Debe incluir un símbolo.", + "hasNumber": "Debe incluir un número.", + "hasUppercase": "Debe incluir una letra mayúscula.", + "hasLowercase": "Debe incluir una letra minúscula.", + "equals": "La confirmación de la contraseña coincide.", + "matches": "Coincide", + "doesNotMatch": "No coincide" + }, + "errors": { + "noHostFound": "No se encontró el host", + "couldNotSendResetLink": "No se pudo enviar el enlace de restablecimiento de contraseña", + "couldNotCreateSessionForUser": "No se pudo crear la sesión para el usuario", + "couldNotVerifyPassword": "No se pudo verificar la contraseña", + "failedToAuthenticate": "Error al autenticar. Tuvo {failedAttempts} de {maxPasswordAttempts} intentos de contraseña.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Error al autenticar.", + "accountLockedContactAdmin": " Comuníquese con su administrador para desbloquear su cuenta", + "userNotFound": "Usuario no encontrado en el sistema", + "initialUserNotSupported": "Usuario inicial no compatible", + "userInitialStateNotSupported": "El estado inicial del usuario no es compatible", + "codeOrVerificationRequired": "Debe proporcionar un código o tener una verificación de usuario válida", + "verificationRequired": "Se debe realizar la verificación de usuario", + "couldNotLoadSession": "No se pudo cargar la sesión", + "couldNotLoadAuthMethods": "No se pudieron cargar los métodos de autenticación", + "failedPrecondition": "Precondición fallida", + "sessionNotValid": "La sesión no es válida", + "passwordVerificationMissing": "Falta la verificación de la contraseña.", + "passwordVerificationTooOld": "La verificación de la contraseña es demasiado antigua. Por favor, verifique su contraseña de nuevo.", + "passwordResetNotAllowed": "El restablecimiento de contraseña no está permitido. Contacte con su administrador para más información.", + "localAuthenticationNotAllowed": "¡La autenticación local no está permitida! Contacte con su administrador para más información." + } + }, + "idp": { + "title": "Iniciar sesión con SSO", + "description": "Selecciona uno de los siguientes proveedores para iniciar sesión", + "orSignInWith": "o iniciar sesión con", + "signInWithApple": "Iniciar sesión con Apple", + "signInWithGoogle": "Iniciar sesión con Google", + "signInWithAzureAD": "Iniciar sesión con AzureAD", + "signInWithGithub": "Iniciar sesión con GitHub", + "signInWithGitlab": "Iniciar sesión con GitLab", + "signInWithZitadel": "Iniciar sesión con Zitadel", + "loginError": { + "title": "Error de inicio de sesión", + "description": "Ocurrió un error al intentar iniciar sesión." + }, + "linkingError": { + "title": "Error al vincular la cuenta", + "description": "Ocurrió un error al intentar vincular tu cuenta." + }, + "completeRegister": { + "title": "Completar registro", + "description": "Para completar el registro, debes establecer una contraseña." + }, + "accountNotFound": { + "title": "Cuenta no encontrada", + "description": "No pudimos encontrar una cuenta asociada con tus credenciales del proveedor de identidad.", + "info": "No se encontró ninguna cuenta existente. Por favor, inicia sesión con una cuenta existente o contacta a tu administrador para obtener asistencia.", + "backToLogin": "Volver al inicio de sesión" + }, + "registrationFailed": { + "title": "Registro no disponible", + "description": "No pudimos completar el proceso de registro.", + "info": "No se pudo determinar la organización para el registro. Por favor, contacta a tu administrador para obtener asistencia.", + "backToLogin": "Volver al inicio de sesión" + }, + "processing": { + "message": "Procesando autenticación...", + "noRedirect": "No se recibió redirección ni error del servidor", + "unexpectedError": "Ocurrió un error inesperado" + }, + "errors": { + "missingParameters": "Faltan parámetros requeridos", + "missingIdpInfo": "Falta información del IDP", + "idpNotFound": "Proveedor de identidad no encontrado", + "linkingNotAllowed": "La vinculación no está permitida para este proveedor de identidad", + "linkingFailed": "Error al vincular el proveedor de identidad con la cuenta", + "autoLinkingFailed": "Error al vincular automáticamente la cuenta", + "userCreationFailed": "Error al crear la cuenta de usuario", + "orgResolutionFailed": "No se pudo determinar la organización para el registro", + "sessionCreationFailed": "No se pudo crear la sesión o determinar la redirección", + "unknownError": "Ocurrió un error desconocido" + } + }, + "ldap": { + "title": "Iniciar sesión con LDAP", + "description": "Introduce tus credenciales LDAP.", + "submit": "Continuar", + "labels": { + "username": "Nombre de usuario", + "password": "Contraseña" + }, + "required": { + "username": "Este campo es obligatorio", + "password": "Este campo es obligatorio" + } + }, + "mfa": { + "verify": { + "title": "Verifica tu identidad", + "description": "Elige uno de los siguientes factores.", + "noResults": "No hay factores secundarios disponibles para configurar." + }, + "set": { + "title": "Configurar autenticación de 2 factores", + "description": "Elige uno de los siguientes factores secundarios.", + "skip": "Omitir" + } + }, + "otp": { + "verify": { + "title": "Verificar autenticación de 2 factores", + "totpDescription": "Introduce el código de tu aplicación de autenticación.", + "smsDescription": "Introduce el código que recibiste por SMS.", + "emailDescription": "Introduce el código que recibiste por correo electrónico.", + "noCodeReceived": "¿No recibiste un código?", + "resendCode": "Reenviar código", + "resendCodeIn": "Reenviar código ({seconds}s)", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo es obligatorio" + } + }, + "set": { + "title": "Configurar autenticación de 2 factores", + "totpDescription": "Escanea el código QR con tu aplicación de autenticación.", + "smsDescription": "Introduce tu número de teléfono para recibir un código por SMS.", + "emailDescription": "Introduce tu dirección de correo electrónico para recibir un código por correo electrónico.", + "totpRegisterDescription": "Escanea el código QR o navega manualmente a la URL.", + "emailAddDescription": "Usa un código de un solo uso enviado a tu dirección de correo electrónico verificada como segundo factor.", + "smsAddDescription": "Usa un código de un solo uso enviado a tu número de teléfono verificado como segundo factor.", + "add": "Añadir", + "emailAdded": "Código por correo electrónico añadido.", + "smsAdded": "Código por SMS añadido.", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo es obligatorio" + } + }, + "errors": { + "couldNotRequestChallenge": "No se pudo solicitar el desafío OTP", + "couldNotVerifyCode": "No se pudo verificar el código OTP", + "couldNotGetSession": "No se pudo cargar tu sesión. Vuelve a iniciar sesión.", + "invalidMethod": "Este segundo factor no es compatible.", + "couldNotAddEmail": "No se pudo añadir el código por correo electrónico.", + "couldNotAddSms": "No se pudo añadir el código por SMS.", + "emailNotVerified": "Verifica tu dirección de correo electrónico antes de añadir códigos por correo electrónico.", + "phoneNotVerified": "Verifica tu número de teléfono antes de añadir códigos por SMS." + } + }, + "passkey": { + "verify": { + "title": "Autenticar con una clave de acceso", + "description": "Tu dispositivo pedirá tu huella digital, rostro o bloqueo de pantalla", + "usePassword": "Usar contraseña", + "submit": "Continuar", + "errors": { + "couldNotRequestChallenge": "No se pudo solicitar el desafío de clave de acceso", + "couldNotVerifyPasskey": "No se pudo verificar la clave de acceso", + "noResponseReceived": "Verificación de clave de acceso fallida - no se recibió respuesta", + "noRedirectProvided": "Verificación de clave de acceso completada pero no se proporcionó redirección", + "couldNotRetrievePasskey": "Ocurrió un error al recuperar la clave de acceso", + "verificationCancelled": "La verificación de clave de acceso fue cancelada", + "verificationFailed": "Ocurrió un error durante la verificación de clave de acceso", + "couldNotFindSession": "No se pudo encontrar la sesión", + "couldNotUpdateSession": "No se pudo actualizar la sesión", + "userNotFound": "Usuario no encontrado en el sistema", + "couldNotDetermineRedirect": "No se pudo determinar la URL de redirección después de la verificación de clave de acceso" + } + }, + "set": { + "title": "Configurar una clave de acceso", + "description": "Tu dispositivo pedirá tu huella digital, rostro o bloqueo de pantalla", + "info": { + "description": "Una clave de acceso es un método de autenticación en un dispositivo como tu huella digital, Apple FaceID o similar.", + "link": "Autenticación sin contraseña" + }, + "skip": "Omitir", + "submit": "Continuar" + } + }, + "u2f": { + "verify": { + "title": "Verificar autenticación de 2 factores", + "description": "Verifica tu cuenta con tu dispositivo." + }, + "set": { + "title": "Configurar autenticación de 2 factores", + "description": "Configura un dispositivo como segundo factor.", + "submit": "Continuar" + } + }, + "register": { + "methods": { + "passkey": "Clave de acceso", + "password": "Contraseña" + }, + "disabled": { + "title": "Registro deshabilitado", + "description": "Registrarse está deshabilitado en este momento." + }, + "missingdata": { + "title": "Datos faltantes", + "description": "No se proporcionaron datos suficientes para el registro." + }, + "title": "Registrarse", + "description": "Crea tu cuenta Zitadel.", + "noMethodAvailableWarning": "No hay métodos de autenticación disponibles. Por favor, contacta a tu administrador.", + "selectMethod": "Selecciona el método con el que deseas autenticarte", + "agreeTo": "Para registrarte debes aceptar los términos y condiciones", + "termsOfService": "Términos de Servicio", + "privacyPolicy": "Política de Privacidad", + "submit": "Continuar", + "password": { + "title": "Establecer Contraseña", + "description": "Establece la contraseña para tu cuenta", + "submit": "Continuar", + "labels": { + "password": "Contraseña", + "confirmPassword": "Confirmar contraseña" + }, + "required": { + "password": "¡Debes proporcionar una contraseña!", + "confirmPassword": "Este campo es obligatorio" + } + }, + "labels": { + "firstname": "Nombre", + "lastname": "Apellidos", + "email": "Correo electrónico" + }, + "required": { + "firstname": "Este campo es obligatorio", + "lastname": "Este campo es obligatorio", + "email": "Este campo es obligatorio" + }, + "errors": { + "couldNotCreateUser": "No se pudo crear el usuario", + "couldNotCreateSession": "No se pudo crear la sesión", + "userNotFound": "Usuario no encontrado en el sistema", + "couldNotLinkIDP": "No se pudo vincular el IdP al usuario", + "couldNotRegisterUser": "No se pudo registrar el usuario", + "sessionMismatch": "El registro se inició en otro navegador. Vuelve a iniciar sesión con tu proveedor de identidad." + } + }, + "invite": { + "title": "Invitar usuario", + "description": "Introduce el correo electrónico del usuario que deseas invitar.", + "info": "El usuario recibirá un correo electrónico con un enlace para completar el registro.", + "notAllowed": "No tienes permiso para invitar usuarios.", + "submit": "Invitar usuario", + "success": { + "title": "¡Usuario invitado!", + "description": "El usuario ha sido invitado.", + "verified": "El usuario ha sido invitado y ya ha verificado su correo electrónico.", + "notVerifiedYet": "El usuario ha sido invitado. Recibirá un correo electrónico con más instrucciones.", + "submit": "Invitar a otro usuario" + } + }, + "signedin": { + "title": "¡Bienvenido {user}!", + "description": "Has iniciado sesión.", + "continue": "Continuar", + "error": { + "title": "Error", + "description": "Ocurrió un error al iniciar sesión." + } + }, + "verify": { + "userIdMissing": "¡No se proporcionó userId!", + "successTitle": "Usuario verificado", + "successDescription": "El usuario ha sido verificado con éxito.", + "successContinue": "Continuar", + "setupAuthenticator": "Configurar autenticador", + "verify": { + "title": "Verificar usuario", + "description": "Introduce el código proporcionado en el correo electrónico de verificación.", + "noCodeReceived": "¿No recibiste un código?", + "resendCode": "Reenviar código", + "codeSent": "Se ha enviado un código a tu dirección de correo electrónico.", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo es obligatorio" + } + }, + "errors": { + "couldNotResendEmail": "No se pudo reenviar el correo electrónico", + "couldNotVerifyUser": "No se pudo verificar al usuario", + "couldNotVerifyInvite": "No se pudo verificar la invitación", + "couldNotVerifyEmail": "No se pudo verificar el correo electrónico", + "couldNotVerify": "No se pudo verificar", + "couldNotLoadUser": "No se pudo cargar al usuario", + "couldNotLoadAuthenticators": "No se pudieron cargar los autenticadores posibles", + "couldNotCreateSession": "No se pudo crear la sesión", + "noHostFound": "No se encontró el host", + "userAlreadyVerified": "¡El usuario ya está verificado!", + "couldNotResendInvite": "No se pudo reenviar la invitación", + "inviteSendFailed": "No se pudo enviar el correo de invitación", + "emailSendFailed": "No se pudo enviar el correo electrónico de verificación", + "contextMissing": "Ocurrió un error. Por favor inténtelo de nuevo." + } + }, + "authenticator": { + "title": "Seleccionar método de autenticación", + "description": "Selecciona el método con el que deseas autenticarte", + "noMethodsAvailable": "No hay métodos de autenticación disponibles", + "allSetup": "¡Ya has configurado un autenticador!", + "linkWithIDP": "o vincúlalo con un proveedor de identidad", + "methods": { + "totp": "Aplicación de autenticación", + "u2f": "Segundo factor universal", + "otpEmail": "Código por correo electrónico", + "otpSms": "Código por SMS", + "passkey": "Clave de acceso", + "password": "Contraseña" + } + }, + "device": { + "usercode": { + "title": "Código del dispositivo", + "description": "Introduce el código.", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo es obligatorio" + } + }, + "request": { + "title": "{appName} desea conectarse:", + "description": "{appName} tendrá acceso a:", + "disclaimer": "Al hacer clic en Permitir, autorizas a {appName} y a Zitadel a usar tu información de acuerdo con sus respectivos términos de servicio y políticas de privacidad. Puedes revocar este acceso en cualquier momento.", + "submit": "Permitir", + "deny": "Denegar" + }, + "scope": { + "openid": "Verifica tu identidad.", + "email": "Accede a tu dirección de correo electrónico.", + "profile": "Accede a la información completa de tu perfil.", + "offline_access": "Permitir acceso sin conexión a tu cuenta." + } + }, + "error": { + "noUserCode": "¡No se proporcionó código de usuario!", + "noDeviceRequest": "No se encontró ninguna solicitud de dispositivo.", + "unknownContext": "No se pudo obtener el contexto del usuario. Asegúrate de ingresar primero el nombre de usuario o proporcionar un loginName como parámetro de búsqueda.", + "sessionExpired": "Tu sesión ha expirado o requiere una nueva autenticación. Por favor, inicia sesión de nuevo.", + "failedLoading": "No se pudieron cargar los datos. Por favor, inténtalo de nuevo.", + "tryagain": "Intentar de nuevo", + "couldNotContinueSession": "No se pudo continuar con la sesión - falta información del usuario", + "couldNotClearSession": "No se pudo cerrar la sesión. Inténtelo de nuevo." + } +} diff --git a/auth/ui/v2/apps/login/locales/fr.json b/auth/ui/v2/apps/login/locales/fr.json new file mode 100644 index 0000000..f617a7b --- /dev/null +++ b/auth/ui/v2/apps/login/locales/fr.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Retour", + "title": "Connexion avec Zitadel" + }, + "accounts": { + "title": "Comptes", + "description": "Choisissez le compte que vous souhaitez utiliser.", + "addAnother": "Ajouter un nouveau compte", + "noResults": "Pas de compte trouvé", + "verified": "vérifié", + "expired": "expiré" + }, + "logout": { + "title": "Déconnexion", + "description": "Cliquez sur un compte pour terminer la session", + "noResults": "Pas de compte trouvé", + "clear": "Fin de session", + "verifiedAt": "Dernière connexion: {time}", + "success": { + "title": "Déconnexion réussie", + "description": "Vous vous êtes déconnecté avec succès." + } + }, + "loginname": { + "title": "Bienvenue!", + "description": "Entrez vos données de connexion.", + "register": "Enregistrer un nouveau compte", + "submit": "Continuer", + "labels": { + "loginname": "Identifiant", + "username": "Nom d'utilisateur", + "usernameOrPhoneNumber": "Nom d'utilisateur ou numéro de téléphone", + "usernameOrEmail": "Nom d'utilisateur ou e-mail" + }, + "required": { + "loginName": "Ce champ est requis" + }, + "errors": { + "internalError": "Une erreur interne s'est produite", + "couldNotGetLoginSettings": "Impossible d'obtenir les paramètres de connexion", + "couldNotSearchUsers": "Impossible de rechercher des utilisateurs", + "couldNotGetDomain": "Impossible d'obtenir le domaine", + "couldNotGetHost": "Impossible d'obtenir l'hôte", + "couldNotStartIDPFlow": "Impossible de démarrer le flux IDP", + "moreThanOneUserFound": "Plus d'un utilisateur trouvé. Fournissez un identifiant unique.", + "userNotFound": "Utilisateur non trouvé dans le système", + "couldNotCreateSession": "Impossible de créer une session pour l'utilisateur", + "initialUserNotSupported": "Utilisateur initial non pris en charge", + "localAuthenticationNotAllowed": "L'authentification locale n'est pas autorisée ! Contactez votre administrateur pour plus d'informations.", + "passkeysNotAllowed": "Les clés d'accès ne sont pas autorisées ! Contactez votre administrateur pour plus d'informations.", + "couldNotFindIdentityProvider": "Impossible de trouver le fournisseur d'identité.", + "userNotActive": "L'utilisateur n'est pas actif. Contactez votre administrateur pour plus d'informations." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Une erreur s'est produite", + "multipleUsersFound": "Plusieurs utilisateurs trouvés", + "userNotFound": "Utilisateur non trouvé dans le système" + } + }, + "password": { + "verify": { + "title": "Mot de passe", + "description": "Entrez votre mot de passe.", + "resetPassword": "Réinitialiser mot de passe", + "submit": "Continuer", + "labels": { + "password": "Mot de passe" + }, + "required": { + "password": "Ce champ est requis" + }, + "errors": { + "couldNotVerifyPassword": "Impossible de vérifier le mot de passe", + "couldNotResetPassword": "Impossible de réinitialiser le mot de passe" + }, + "info": { + "passwordResetSent": "Le mot de passe a été réinitialisé. Veuillez vérifier vos e-mails." + } + }, + "set": { + "title": "Définir le mot de passe", + "description": "Définissez le mot de passe de votre compte", + "codeSent": "Un nouveau code a été envoyé à votre adresse e-mail.", + "noCodeReceived": "Vous n'avez pas reçu de code ?", + "resend": "Renvoyer le code", + "submit": "Continuer", + "labels": { + "code": "Code", + "newPassword": "Nouveau mot de passe", + "confirmPassword": "Confirmez le mot de passe" + }, + "required": { + "code": "Ce champ est requis", + "newPassword": "Vous devez fournir un mot de passe !", + "confirmPassword": "Ce champ est requis" + }, + "errors": { + "couldNotSetPassword": "Impossible de définir le mot de passe", + "couldNotResetPassword": "Impossible de réinitialiser le mot de passe", + "couldNotVerifyPassword": "Impossible de vérifier le mot de passe" + } + }, + "change": { + "title": "Changer le mot de passe", + "description": "Définissez le mot de passe de votre compte", + "submit": "Continuer", + "labels": { + "currentPassword": "Mot de passe actuel", + "newPassword": "Nouveau mot de passe", + "confirmPassword": "Confirmez le mot de passe" + }, + "required": { + "currentPassword": "Vous devez fournir votre mot de passe actuel !", + "newPassword": "Vous devez fournir un nouveau mot de passe !", + "confirmPassword": "Ce champ est requis" + }, + "errors": { + "currentPasswordInvalid": "Le mot de passe actuel est incorrect.", + "couldNotChangePassword": "Impossible de changer le mot de passe", + "couldNotVerifyPassword": "Impossible de vérifier le mot de passe", + "unknownError": "Erreur inconnue" + } + }, + "complexity": { + "length": "Doit contenir au moins {minLength} caractères.", + "hasSymbol": "Doit inclure un symbole.", + "hasNumber": "Doit inclure un chiffre.", + "hasUppercase": "Doit inclure une lettre majuscule.", + "hasLowercase": "Doit inclure une lettre minuscule.", + "equals": "La confirmation du mot de passe correspond.", + "matches": "Correspond", + "doesNotMatch": "Ne correspond pas" + }, + "errors": { + "noHostFound": "Aucun hôte trouvé", + "couldNotSendResetLink": "Impossible d'envoyer le lien de réinitialisation du mot de passe", + "couldNotCreateSessionForUser": "Impossible de créer une session pour l'utilisateur", + "couldNotVerifyPassword": "Impossible de vérifier le mot de passe", + "failedToAuthenticate": "Échec de l'authentification. Vous avez utilisé {failedAttempts} sur {maxPasswordAttempts} tentatives.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Échec de l'authentification.", + "accountLockedContactAdmin": " Contactez votre administrateur pour déverrouiller votre compte", + "userNotFound": "Utilisateur non trouvé dans le système", + "initialUserNotSupported": "Utilisateur initial non pris en charge", + "userInitialStateNotSupported": "État initial de l'utilisateur non pris en charge", + "codeOrVerificationRequired": "Vous devez fournir un code ou avoir une vérification utilisateur valide", + "verificationRequired": "Une vérification utilisateur doit être effectuée", + "couldNotLoadSession": "Impossible de charger la session", + "couldNotLoadAuthMethods": "Impossible de charger les méthodes d'authentification", + "failedPrecondition": "Pré-condition non remplie", + "sessionNotValid": "La session n'est pas valide", + "passwordVerificationMissing": "La vérification du mot de passe est manquante.", + "passwordVerificationTooOld": "La vérification du mot de passe est trop ancienne. Veuillez vérifier à nouveau votre mot de passe.", + "passwordResetNotAllowed": "La réinitialisation du mot de passe n'est pas autorisée. Contactez votre administrateur pour plus d'informations.", + "localAuthenticationNotAllowed": "L'authentification locale n'est pas autorisée ! Contactez votre administrateur pour plus d'informations." + } + }, + "idp": { + "title": "Se connecter avec SSO", + "description": "Sélectionnez un des fournisseurs suivants pour vous connecter", + "orSignInWith": "ou connectez-vous avec", + "signInWithApple": "Se connecter avec Apple", + "signInWithGoogle": "Se connecter avec Google", + "signInWithAzureAD": "Se connecter avec AzureAD", + "signInWithGithub": "Se connecter avec GitHub", + "signInWithGitlab": "Se connecter avec GitLab", + "signInWithZitadel": "Se connecter avec Zitadel", + "loginError": { + "title": "Échec de la connexion", + "description": "Une erreur est survenue lors de la tentative de connexion." + }, + "linkingError": { + "title": "Échec de la liaison du compte", + "description": "Une erreur est survenue lors de la tentative de lier votre compte." + }, + "completeRegister": { + "title": "Complétez vos informations", + "description": "Vous devez compléter votre inscription en fournissant votre adresse e-mail et votre nom." + }, + "accountNotFound": { + "title": "Compte introuvable", + "description": "Nous n'avons pas trouvé de compte associé aux identifiants de votre fournisseur d'identité.", + "info": "Aucun compte existant n'a été trouvé. Veuillez vous connecter avec un compte existant ou contacter votre administrateur pour obtenir de l'aide.", + "backToLogin": "Retour à la connexion" + }, + "registrationFailed": { + "title": "Inscription non disponible", + "description": "Nous n'avons pas pu terminer le processus d'inscription.", + "info": "Impossible de déterminer l'organisation pour l'inscription. Veuillez contacter votre administrateur pour obtenir de l'aide.", + "backToLogin": "Retour à la connexion" + }, + "processing": { + "message": "Traitement de l'authentification...", + "noRedirect": "Aucune redirection ou erreur renvoyée par le serveur", + "unexpectedError": "Une erreur inattendue s'est produite" + }, + "errors": { + "missingParameters": "Paramètres requis manquants", + "missingIdpInfo": "Informations du fournisseur d'identité manquantes", + "idpNotFound": "Fournisseur d'identité introuvable", + "linkingNotAllowed": "La liaison n'est pas autorisée pour ce fournisseur d'identité", + "linkingFailed": "Échec de la liaison du fournisseur d'identité au compte", + "autoLinkingFailed": "Échec de la liaison automatique du compte", + "userCreationFailed": "Échec de la création du compte utilisateur", + "orgResolutionFailed": "Impossible de déterminer l'organisation pour l'inscription", + "sessionCreationFailed": "Impossible de créer la session ou de déterminer la redirection", + "unknownError": "Une erreur inconnue s'est produite" + } + }, + "ldap": { + "title": "Connexion LDAP", + "description": "Entrez vos identifiants LDAP.", + "submit": "Continuer", + "labels": { + "username": "Nom d'utilisateur", + "password": "Mot de passe" + }, + "required": { + "username": "Ce champ est requis", + "password": "Ce champ est requis" + } + }, + "mfa": { + "verify": { + "title": "Vérifiez votre identité", + "description": "Choisissez l'un des facteurs suivants.", + "noResults": "Aucun second facteur disponible à configurer." + }, + "set": { + "title": "Configurer l'authentification à deux facteurs", + "description": "Choisissez l'un des seconds facteurs suivants.", + "skip": "Ignorer" + } + }, + "otp": { + "verify": { + "title": "Vérification à deux facteurs", + "totpDescription": "Entrez le code de votre application d'authentification.", + "smsDescription": "Entrez le code reçu par SMS.", + "emailDescription": "Entrez le code reçu par e-mail.", + "noCodeReceived": "Vous n'avez pas reçu de code ?", + "resendCode": "Renvoyer le code", + "resendCodeIn": "Renvoyer le code ({seconds}s)", + "submit": "Continuer", + "labels": { + "code": "Code" + }, + "required": { + "code": "Ce champ est requis" + } + }, + "set": { + "title": "Configurer l'authentification à deux facteurs", + "totpDescription": "Scannez le QR code avec votre application d'authentification.", + "smsDescription": "Entrez votre numéro de téléphone pour recevoir un code par SMS.", + "emailDescription": "Entrez votre adresse e-mail pour recevoir un code par e-mail.", + "totpRegisterDescription": "Scannez le QR code ou saisissez l'URL manuellement.", + "emailAddDescription": "Utilisez un code à usage unique envoyé à votre adresse e-mail vérifiée comme second facteur.", + "smsAddDescription": "Utilisez un code à usage unique envoyé à votre numéro de téléphone vérifié comme second facteur.", + "add": "Ajouter", + "emailAdded": "Code par e-mail ajouté.", + "smsAdded": "Code par SMS ajouté.", + "submit": "Continuer", + "labels": { + "code": "Code" + }, + "required": { + "code": "Ce champ est requis" + } + }, + "errors": { + "couldNotRequestChallenge": "Impossible de demander le challenge OTP", + "couldNotVerifyCode": "Impossible de vérifier le code OTP", + "couldNotGetSession": "Votre session n'a pas pu être chargée. Veuillez vous reconnecter.", + "invalidMethod": "Ce second facteur n'est pas pris en charge.", + "couldNotAddEmail": "Le code par e-mail n'a pas pu être ajouté.", + "couldNotAddSms": "Le code par SMS n'a pas pu être ajouté.", + "emailNotVerified": "Vérifiez votre adresse e-mail avant d'ajouter des codes par e-mail.", + "phoneNotVerified": "Vérifiez votre numéro de téléphone avant d'ajouter des codes par SMS." + } + }, + "passkey": { + "verify": { + "title": "S'authentifier avec une clé d'accès", + "description": "Votre appareil vous demandera votre empreinte digitale, votre visage ou votre verrouillage d'écran", + "usePassword": "Utiliser un mot de passe", + "submit": "Continuer", + "errors": { + "couldNotRequestChallenge": "Impossible de demander le défi de la clé d'accès", + "couldNotVerifyPasskey": "Impossible de vérifier la clé d'accès", + "noResponseReceived": "Échec de la vérification de la clé d'accès - aucune réponse reçue", + "noRedirectProvided": "La vérification de la clé d'accès est terminée mais aucune redirection n'a été fournie", + "couldNotRetrievePasskey": "Une erreur s'est produite lors de la récupération de la clé d'accès", + "verificationCancelled": "La vérification de la clé d'accès a été annulée", + "verificationFailed": "Une erreur s'est produite lors de la vérification de la clé d'accès", + "couldNotFindSession": "Session introuvable", + "couldNotUpdateSession": "Impossible de mettre à jour la session", + "userNotFound": "Utilisateur introuvable dans le système", + "couldNotDetermineRedirect": "Impossible de déterminer l'URL de redirection après la vérification de la clé d'accès" + } + }, + "set": { + "title": "Configurer une clé d'accès", + "description": "Votre appareil vous demandera votre empreinte digitale, votre visage ou votre verrouillage d'écran", + "info": { + "description": "Une clé d'accès est une méthode d'authentification sur un appareil, comme votre empreinte digitale, Apple FaceID ou équivalent.", + "link": "Authentification par clé d'accès" + }, + "skip": "Ignorer", + "submit": "Continuer" + } + }, + "u2f": { + "verify": { + "title": "Vérification à deux facteurs", + "description": "Vérifiez votre compte avec votre appareil." + }, + "set": { + "title": "Configurer la double authentification", + "description": "Configurez un appareil comme second facteur.", + "submit": "Continuer" + } + }, + "register": { + "methods": { + "passkey": "Clé d'accès", + "password": "Mot de passe" + }, + "disabled": { + "title": "Inscription désactivée", + "description": "L'inscription est désactivée. Veuillez contacter votre administrateur." + }, + "missingdata": { + "title": "Données manquantes", + "description": "Fournissez un e-mail, un prénom et un nom pour vous inscrire." + }, + "title": "S'inscrire", + "description": "Créez votre compte Zitadel.", + "noMethodAvailableWarning": "Aucune méthode d'authentification disponible. Veuillez contacter votre administrateur.", + "selectMethod": "Sélectionnez la méthode que vous souhaitez utiliser pour vous authentifier", + "agreeTo": "Pour vous inscrire, vous devez accepter les conditions d'utilisation", + "termsOfService": "Conditions d'utilisation", + "privacyPolicy": "Politique de confidentialité", + "submit": "Continuer", + "password": { + "title": "Définir un mot de passe", + "description": "Définissez le mot de passe de votre compte", + "submit": "Continuer", + "labels": { + "password": "Mot de passe", + "confirmPassword": "Confirmez le mot de passe" + }, + "required": { + "password": "Vous devez fournir un mot de passe !", + "confirmPassword": "Ce champ est requis" + } + }, + "labels": { + "firstname": "Prénom", + "lastname": "Nom", + "email": "E-mail" + }, + "required": { + "firstname": "Ce champ est requis", + "lastname": "Ce champ est requis", + "email": "Ce champ est requis" + }, + "errors": { + "couldNotCreateUser": "Impossible de créer l'utilisateur", + "couldNotCreateSession": "Impossible de créer la session", + "userNotFound": "Utilisateur non trouvé dans le système", + "couldNotLinkIDP": "Impossible de lier le fournisseur d'identité à l'utilisateur", + "couldNotRegisterUser": "Impossible d'inscrire l'utilisateur", + "sessionMismatch": "L'inscription a été commencée dans un autre navigateur. Veuillez vous reconnecter avec votre fournisseur d'identité." + } + }, + "invite": { + "title": "Inviter un utilisateur", + "description": "Fournissez l'adresse e-mail et le nom de l'utilisateur que vous souhaitez inviter.", + "info": "L'utilisateur recevra un e-mail avec de plus amples instructions.", + "notAllowed": "Vos paramètres ne vous permettent pas d'inviter des utilisateurs.", + "submit": "Continuer", + "success": { + "title": "Utilisateur invité", + "description": "L'e-mail a été envoyé avec succès.", + "verified": "L'utilisateur a été invité et a déjà vérifié son e-mail.", + "notVerifiedYet": "L'utilisateur a été invité. Il recevra un e-mail avec de plus amples instructions.", + "submit": "Inviter un autre utilisateur" + } + }, + "signedin": { + "title": "Bienvenue {user} !", + "description": "Vous êtes connecté.", + "continue": "Continuer", + "error": { + "title": "Erreur", + "description": "Une erreur est survenue lors de la connexion." + } + }, + "verify": { + "userIdMissing": "Aucun identifiant utilisateur fourni !", + "successTitle": "Utilisateur vérifié", + "successDescription": "L'utilisateur a été vérifié avec succès.", + "successContinue": "Continuer", + "setupAuthenticator": "Configurer l'authentificateur", + "verify": { + "title": "Vérifier l'utilisateur", + "description": "Entrez le code fourni dans l'e-mail de vérification.", + "noCodeReceived": "Vous n'avez pas reçu de code ?", + "resendCode": "Renvoyer le code", + "codeSent": "Un code vient d'être envoyé à votre adresse e-mail.", + "submit": "Continuer", + "labels": { + "code": "Code" + }, + "required": { + "code": "Ce champ est requis" + } + }, + "errors": { + "couldNotResendEmail": "Impossible de renvoyer l'e-mail", + "couldNotVerifyUser": "Impossible de vérifier l'utilisateur", + "couldNotVerifyInvite": "Impossible de vérifier l'invitation", + "couldNotVerifyEmail": "Impossible de vérifier l'e-mail", + "couldNotVerify": "Impossible de vérifier", + "couldNotLoadUser": "Impossible de charger l'utilisateur", + "couldNotLoadAuthenticators": "Impossible de charger les authentificateurs disponibles", + "couldNotCreateSession": "Impossible de créer la session", + "noHostFound": "Aucun hôte trouvé", + "userAlreadyVerified": "L'utilisateur est déjà vérifié !", + "couldNotResendInvite": "Impossible de renvoyer l'invitation", + "inviteSendFailed": "Échec de l'envoi de l'e-mail d'invitation", + "emailSendFailed": "Échec de l'envoi de l'e-mail de vérification", + "contextMissing": "Une erreur s'est produite. Veuillez réessayer." + } + }, + "authenticator": { + "title": "Choisir la méthode d'authentification", + "description": "Sélectionnez la méthode que vous souhaitez utiliser pour vous authentifier", + "noMethodsAvailable": "Aucune méthode d'authentification disponible", + "allSetup": "Vous avez déjà configuré un authentificateur !", + "linkWithIDP": "ou lier avec un fournisseur d'identité", + "methods": { + "totp": "Application d'authentification", + "u2f": "Second facteur universel", + "otpEmail": "Code par e-mail", + "otpSms": "Code par SMS", + "passkey": "Clés d'accès", + "password": "Mot de passe" + } + }, + "device": { + "usercode": { + "title": "Code de l'appareil", + "description": "Entrez le code affiché sur votre application ou appareil.", + "submit": "Continuer", + "labels": { + "code": "Code" + }, + "required": { + "code": "Ce champ est requis" + } + }, + "request": { + "title": "{appName} souhaite se connecter", + "description": "{appName} aura accès à :", + "disclaimer": "En cliquant sur Autoriser, vous permettez à {appName} et à Zitadel d'utiliser vos informations conformément à leurs conditions d'utilisation et politiques de confidentialité respectives. Vous pouvez révoquer cet accès à tout moment.", + "submit": "Autoriser", + "deny": "Refuser" + }, + "scope": { + "openid": "Vérifiez votre identité.", + "email": "Afficher votre adresse e-mail.", + "profile": "Afficher les informations complètes de votre profil.", + "offline_access": "Autoriser l'accès hors ligne à votre compte." + } + }, + "error": { + "noUserCode": "Aucun code utilisateur fourni !", + "noDeviceRequest": "Aucune demande d'appareil trouvée.", + "unknownContext": "Impossible d'obtenir le contexte de l'utilisateur. Assurez-vous d'abord de saisir le nom d'utilisateur ou de fournir un loginName comme paramètre de recherche.", + "sessionExpired": "Votre session a expiré ou nécessite une nouvelle authentification. Veuillez vous reconnecter.", + "failedLoading": "Échec du chargement des données. Veuillez réessayer.", + "tryagain": "Réessayer", + "couldNotContinueSession": "Impossible de continuer la session - informations utilisateur manquantes", + "couldNotClearSession": "La session n'a pas pu être terminée. Veuillez réessayer." + } +} diff --git a/auth/ui/v2/apps/login/locales/hu.json b/auth/ui/v2/apps/login/locales/hu.json new file mode 100644 index 0000000..3ac4d4c --- /dev/null +++ b/auth/ui/v2/apps/login/locales/hu.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Vissza", + "title": "Bejelentkezés a Zitadel-lel" + }, + "accounts": { + "title": "Fiókok", + "description": "Válaszd ki a használni kívánt fiókot.", + "addAnother": "Másik fiók hozzáadása", + "noResults": "Nem található fiók", + "verified": "ellenőrizve", + "expired": "lejárt" + }, + "logout": { + "title": "Kijelentkezés", + "description": "Kattints egy fiókra a munkamenet befejezéséhez", + "noResults": "Nem található fiók", + "clear": "Munkamenet befejezése", + "verifiedAt": "Utoljára aktív: {time}", + "success": { + "title": "Sikeres kijelentkezés", + "description": "Sikeresen kijelentkeztél." + } + }, + "loginname": { + "title": "Üdvözlünk újra!", + "description": "Add meg a bejelentkezési adataidat.", + "register": "Új felhasználó regisztrálása", + "submit": "Tovább", + "labels": { + "loginname": "Bejelentkezési név", + "username": "Felhasználónév", + "usernameOrPhoneNumber": "Felhasználónév vagy telefonszám", + "usernameOrEmail": "Felhasználónév vagy e-mail cím" + }, + "required": { + "loginName": "Ez a mező kötelező" + }, + "errors": { + "internalError": "Belső hiba történt", + "couldNotGetLoginSettings": "Nem sikerült lekérni a bejelentkezési beállításokat", + "couldNotSearchUsers": "Nem sikerült keresni a felhasználók között", + "couldNotGetDomain": "Nem sikerült lekérni a domaint", + "couldNotGetHost": "Nem sikerült lekérni a kiszolgálót (hostot)", + "couldNotStartIDPFlow": "Nem sikerült elindítani az IDP folyamatát", + "moreThanOneUserFound": "Több felhasználót találtunk. Adj meg egy egyedi azonosítót.", + "userNotFound": "A felhasználó nem található a rendszerben", + "couldNotCreateSession": "Nem sikerült munkamenetet létrehozni a felhasználóhoz", + "initialUserNotSupported": "A kezdeti felhasználó nem támogatott", + "localAuthenticationNotAllowed": "A helyi hitelesítés nem engedélyezett! További információért fordulj a rendszergazdához.", + "passkeysNotAllowed": "A jelkulcsok nem engedélyezettek! További információért fordulj a rendszergazdához.", + "couldNotFindIdentityProvider": "Nem található azonosítószolgáltató.", + "userNotActive": "A felhasználó nem aktív. További információért fordulj a rendszergazdához." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Hiba történt", + "multipleUsersFound": "Több felhasználó is található", + "userNotFound": "A felhasználó nem található a rendszerben" + } + }, + "password": { + "verify": { + "title": "Jelszó", + "description": "Add meg a jelszavadat.", + "resetPassword": "Jelszó visszaállítása", + "submit": "Tovább", + "labels": { + "password": "Jelszó" + }, + "required": { + "password": "Ez a mező kötelező" + }, + "errors": { + "couldNotVerifyPassword": "Nem sikerült ellenőrizni a jelszót", + "couldNotResetPassword": "Nem sikerült visszaállítani a jelszót" + }, + "info": { + "passwordResetSent": "A jelszó-visszaállító linket elküldtük. Ellenőrizd az e-mail fiókodat." + } + }, + "set": { + "title": "Jelszó beállítása", + "description": "Állítsd be a fiókod jelszavát", + "codeSent": "Az új kódot elküldtük az e-mail címedre.", + "noCodeReceived": "Nem kaptál kódot?", + "resend": "Kód újraküldése", + "submit": "Tovább", + "labels": { + "code": "Kód", + "newPassword": "Új jelszó", + "confirmPassword": "Jelszó megerősítése" + }, + "required": { + "code": "Ez a mező kötelező", + "newPassword": "Adj meg egy jelszót!", + "confirmPassword": "Ez a mező kötelező" + }, + "errors": { + "couldNotSetPassword": "Nem sikerült beállítani a jelszót", + "couldNotResetPassword": "Nem sikerült visszaállítani a jelszót", + "couldNotVerifyPassword": "Nem sikerült ellenőrizni a jelszót" + } + }, + "change": { + "title": "Jelszó módosítása", + "description": "Állítsd be a fiókod jelszavát", + "submit": "Tovább", + "labels": { + "currentPassword": "Jelenlegi jelszó", + "newPassword": "Új jelszó", + "confirmPassword": "Jelszó megerősítése" + }, + "required": { + "currentPassword": "Add meg a jelenlegi jelszavadat!", + "newPassword": "Add meg az új jelszavadat!", + "confirmPassword": "Ez a mező kötelező" + }, + "errors": { + "currentPasswordInvalid": "A jelenlegi jelszó helytelen.", + "couldNotChangePassword": "Nem sikerült módosítani a jelszót", + "couldNotVerifyPassword": "Nem sikerült ellenőrizni a jelszót", + "unknownError": "Ismeretlen hiba" + } + }, + "complexity": { + "length": "Legalább {minLength} karakter hosszúnak kell lennie.", + "hasSymbol": "Tartalmaznia kell egy szimbólumot.", + "hasNumber": "Tartalmaznia kell egy számot.", + "hasUppercase": "Tartalmaznia kell egy nagybetűt.", + "hasLowercase": "Tartalmaznia kell egy kisbetűt.", + "equals": "A jelszavak megegyeznek.", + "matches": "Egyezik", + "doesNotMatch": "Nem egyezik" + }, + "errors": { + "noHostFound": "Nem található kiszolgáló (host)", + "couldNotSendResetLink": "Nem sikerült elküldeni a jelszó visszaállító linket", + "couldNotCreateSessionForUser": "Nem sikerült munkamenetet létrehozni a felhasználóhoz", + "couldNotVerifyPassword": "Nem sikerült ellenőrizni a jelszót", + "failedToAuthenticate": "Sikertelen hitelesítés. Eddig {failedAttempts} sikertelen jelszópróbálkozása volt a megengedett {maxPasswordAttempts} próbálkozásból. {lockoutMessage}", + "failedToAuthenticateNoLimit": "A hitelesítés sikertelen.", + "accountLockedContactAdmin": " A fiókod feloldásához fordulj a rendszergazdához", + "userNotFound": "A felhasználó nem található a rendszerben", + "initialUserNotSupported": "A kezdeti felhasználó nem támogatott", + "userInitialStateNotSupported": "A felhasználó kezdeti állapota nem támogatott", + "codeOrVerificationRequired": "Meg kell adnod egy ellenőrző kódot, vagy érvényes felhasználó-ellenőrzéssel kell rendelkezned", + "verificationRequired": "El kell végezni a felhasználói ellenőrzést", + "couldNotLoadSession": "Nem sikerült betölteni a munkamenetet", + "couldNotLoadAuthMethods": "Nem sikerült betölteni a hitelesítési módszereket", + "failedPrecondition": "Az előfeltétel nem teljesült", + "sessionNotValid": "A munkamenet nem érvényes", + "passwordVerificationMissing": "A jelszó hitelesítés hiányzik.", + "passwordVerificationTooOld": "A jelszó hitelesítés túl régi. Kérjük, erősítsd meg újra a jelszavadat.", + "passwordResetNotAllowed": "A jelszó-visszaállítás nem engedélyezett. További információért fordulj a rendszergazdához.", + "localAuthenticationNotAllowed": "A helyi hitelesítés nem engedélyezett! További információért fordulj a rendszergazdához." + } + }, + "idp": { + "title": "Bejelentkezés SSO-val", + "description": "Válaszd ki az egyik szolgáltatót a bejelentkezéshez", + "orSignInWith": "vagy jelentkezz be ezzel", + "signInWithApple": "Bejelentkezés Apple-lel", + "signInWithGoogle": "Bejelentkezés Google-lel", + "signInWithAzureAD": "Bejelentkezés AzureAD-vel", + "signInWithGithub": "Bejelentkezés GitHubbal", + "signInWithGitlab": "Bejelentkezés GitLabbal", + "signInWithZitadel": "Bejelentkezés Zitadel-lel", + "loginError": { + "title": "Sikertelen bejelentkezés", + "description": "Hiba történt a bejelentkezés során." + }, + "linkingError": { + "title": "Sikertelen fiókösszekapcsolás", + "description": "Hiba történt a fiókod összekapcsolása során." + }, + "completeRegister": { + "title": "Add meg az adataidat", + "description": "A regisztráció befejezéséhez add meg az e-mail címedet és a nevedet." + }, + "accountNotFound": { + "title": "A fiók nem található", + "description": "Nem találtunk fiókot, amely az azonosítószolgáltatód hitelesítő adataihoz kapcsolódna.", + "info": "Nem található összekapcsolt fiók. Jelentkezz be egy már létező fiókkal, vagy fordulj segítségért a rendszergazdához.", + "backToLogin": "Vissza a bejelentkezéshez" + }, + "registrationFailed": { + "title": "A regisztráció nem elérhető", + "description": "Nem sikerült befejezni a regisztrációs folyamatot.", + "info": "Nem sikerült meghatározni a szervezetet a regisztrációhoz. Fordulj segítségért a rendszergazdához.", + "backToLogin": "Vissza a bejelentkezéshez" + }, + "processing": { + "message": "Hitelesítés folyamatban...", + "noRedirect": "A szerver nem adott vissza sem átirányítást, sem hibaüzenetet", + "unexpectedError": "Váratlan hiba történt" + }, + "errors": { + "missingParameters": "Hiányzó kötelező paraméterek", + "missingIdpInfo": "Hiányoznak az azonosítószolgáltató (IDP) adatai", + "idpNotFound": "Az azonosítószolgáltató nem található", + "linkingNotAllowed": "Az összekapcsolás nem engedélyezett ennél az azonosítószolgáltatónál", + "linkingFailed": "Nem sikerült összekapcsolni az azonosítószolgáltatót a fiókkal", + "autoLinkingFailed": "Nem sikerült automatikusan összekapcsolni a fiókot", + "userCreationFailed": "Nem sikerült létrehozni a felhasználói fiókot", + "orgResolutionFailed": "Nem sikerült meghatározni a szervezetet a regisztrációhoz", + "sessionCreationFailed": "Nem sikerült létrehozni a munkamenetet vagy meghatározni az átirányítási címet", + "unknownError": "Ismeretlen hiba történt" + } + }, + "ldap": { + "title": "LDAP bejelentkezés", + "description": "Add meg az LDAP hitelesítő adataidat.", + "submit": "Tovább", + "labels": { + "username": "Felhasználónév", + "password": "Jelszó" + }, + "required": { + "username": "Ez a mező kötelező", + "password": "Ez a mező kötelező" + } + }, + "mfa": { + "verify": { + "title": "Igazold a személyazonosságodat", + "description": "Válaszd ki az alábbi hitelesítési módok egyikét.", + "noResults": "Nincs beállítható hitelesítési mód." + }, + "set": { + "title": "Kétlépcsős azonosítás beállítása", + "description": "Válaszd ki az alábbi hitelesítési módok egyikét.", + "skip": "Kihagyás" + } + }, + "otp": { + "verify": { + "title": "Kétlépcsős azonosítás igazolása", + "totpDescription": "Add meg a hitelesítő alkalmazásodban megjelenő kódot.", + "smsDescription": "Add meg az SMS-ben kapott kódot.", + "emailDescription": "Add meg az e-mailben kapott kódot.", + "noCodeReceived": "Nem kaptál kódot?", + "resendCode": "Kód újraküldése", + "resendCodeIn": "Kód újraküldése ({seconds} mp)", + "submit": "Tovább", + "labels": { + "code": "Kód" + }, + "required": { + "code": "Ez a mező kötelező" + } + }, + "set": { + "title": "Kétlépcsős azonosítás beállítása", + "totpDescription": "Olvasd be a QR-kódot a hitelesítő alkalmazásoddal.", + "smsDescription": "Add meg a telefonszámodat, hogy SMS-ben elküldhessük az ellenőrző kódot.", + "emailDescription": "Add meg az e-mail címedet, hogy e-mailben elküldhessük az ellenőrző kódot.", + "totpRegisterDescription": "Olvasd be a QR-kódot, vagy navigálj az URL-re manuálisan.", + "emailAddDescription": "Használj az ellenőrzött e-mail-címedre küldött egyszer használatos kódot második faktorként.", + "smsAddDescription": "Használj az ellenőrzött telefonszámodra küldött egyszer használatos kódot második faktorként.", + "add": "Hozzáadás", + "emailAdded": "E-mailes kód hozzáadva.", + "smsAdded": "SMS-es kód hozzáadva.", + "submit": "Tovább", + "labels": { + "code": "Kód" + }, + "required": { + "code": "Ez a mező kötelező" + } + }, + "errors": { + "couldNotRequestChallenge": "Nem sikerült OTP-kihívást kérni", + "couldNotVerifyCode": "Nem sikerült ellenőrizni az OTP-kódot", + "couldNotGetSession": "A munkamenet nem tölthető be. Jelentkezz be újra.", + "invalidMethod": "Ez a második faktor nem támogatott.", + "couldNotAddEmail": "Az e-mailes kódot nem sikerült hozzáadni.", + "couldNotAddSms": "Az SMS-es kódot nem sikerült hozzáadni.", + "emailNotVerified": "Ellenőrizd az e-mail-címedet, mielőtt e-mailes kódokat adsz hozzá.", + "phoneNotVerified": "Ellenőrizd a telefonszámodat, mielőtt SMS-es kódokat adsz hozzá." + } + }, + "passkey": { + "verify": { + "title": "Hitelesítés jelkulccsal (Passkey)", + "description": "A készüléked az ujjlenyomatodat, arcodat vagy a képernyőzárat fogja kérni", + "usePassword": "Jelszó használata", + "submit": "Tovább", + "errors": { + "couldNotRequestChallenge": "Nem sikerült elindítani a jelkulcsos azonosítást", + "couldNotVerifyPasskey": "Nem sikerült ellenőrizni a jelkulcsot", + "noResponseReceived": "A jelkulcs ellenőrzése sikertelen - nem érkezett válasz", + "noRedirectProvided": "A jelkulcs ellenőrzése befejeződött, de nem érkezett átirányítás", + "couldNotRetrievePasskey": "Hiba történt a jelkulcs lekérése közben", + "verificationCancelled": "A jelkulcs ellenőrzése megszakadt", + "verificationFailed": "Hiba történt a jelkulcs ellenőrzése közben", + "couldNotFindSession": "Nem található munkamenet", + "couldNotUpdateSession": "Nem sikerült frissíteni a munkamenetet", + "userNotFound": "A felhasználó nem található a rendszerben", + "couldNotDetermineRedirect": "Nem sikerült meghatározni az átirányítási címet a jelkulcs ellenőrzése után" + } + }, + "set": { + "title": "Jelkulcs beállítása", + "description": "A készüléked az ujjlenyomatodat, arcodat vagy a képernyőzárat fogja kérni", + "info": { + "description": "A jelkulcs egy olyan hitelesítési módszer, amely az eszközödön használható, például ujjlenyomattal, Apple Face ID-val vagy más hasonló megoldással.", + "link": "Jelkulcsos hitelesítés" + }, + "skip": "Kihagyás", + "submit": "Tovább" + } + }, + "u2f": { + "verify": { + "title": "Kétlépcsős azonosítás igazolása", + "description": "Igazold a fiókodat a készülékeddel." + }, + "set": { + "title": "Kétlépcsős azonosítás beállítása", + "description": "Állíts be egy készüléket második hitelesítési módként.", + "submit": "Tovább" + } + }, + "register": { + "methods": { + "passkey": "Jelkulcs", + "password": "Jelszó" + }, + "disabled": { + "title": "A regisztráció letiltva", + "description": "A regisztráció le van tiltva. Fordulj a rendszergazdához." + }, + "missingdata": { + "title": "Hiányzó adatok", + "description": "A regisztrációhoz add meg az e-mail címedet, keresztneved és vezetékneved." + }, + "title": "Regisztráció", + "description": "Hozd létre a Zitadel fiókodat.", + "noMethodAvailableWarning": "Nincs elérhető hitelesítési módszer. Fordulj a rendszergazdához.", + "selectMethod": "Válaszd ki, milyen módszerrel szeretnél hitelesíteni", + "agreeTo": "A regisztrációhoz el kell fogadnod a felhasználási feltételeket", + "termsOfService": "Felhasználási feltételek", + "privacyPolicy": "Adatvédelmi irányelvek", + "submit": "Tovább", + "password": { + "title": "Jelszó beállítása", + "description": "Állítsd be a fiókod jelszavát", + "submit": "Tovább", + "labels": { + "password": "Jelszó", + "confirmPassword": "Jelszó megerősítése" + }, + "required": { + "password": "Adj meg egy jelszót!", + "confirmPassword": "Ez a mező kötelező" + } + }, + "labels": { + "firstname": "Keresztnév", + "lastname": "Vezetéknév", + "email": "E-mail cím" + }, + "required": { + "firstname": "Ez a mező kötelező", + "lastname": "Ez a mező kötelező", + "email": "Ez a mező kötelező" + }, + "errors": { + "couldNotCreateUser": "Nem sikerült létrehozni a felhasználót", + "couldNotCreateSession": "Nem sikerült létrehozni a munkamenetet", + "userNotFound": "A felhasználó nem található a rendszerben", + "couldNotLinkIDP": "Nem sikerült összekapcsolni az azonosítószolgáltatót a felhasználóval", + "couldNotRegisterUser": "Nem sikerült regisztrálni a felhasználót", + "sessionMismatch": "A regisztráció egy másik böngészőben indult. Jelentkezz be újra az azonosítószolgáltatódnál." + } + }, + "invite": { + "title": "Felhasználó meghívása", + "description": "Add meg a meghívni kívánt felhasználó e-mail címét és nevét.", + "info": "A felhasználó e-mailben kapja meg a további teendőket.", + "notAllowed": "A beállításaid nem teszik lehetővé felhasználók meghívását.", + "submit": "Tovább", + "success": { + "title": "Felhasználó meghívva", + "description": "Az e-mail sikeresen elküldve.", + "verified": "A felhasználót meghívtuk, és már ellenőrizte az e-mail címét.", + "notVerifiedYet": "A felhasználót meghívtuk. E-mailben kapja meg a további teendőket.", + "submit": "Másik felhasználó meghívása" + } + }, + "signedin": { + "title": "Üdvözlünk, {user}!", + "description": "Sikeresen bejelentkeztél.", + "continue": "Tovább", + "error": { + "title": "Hiba", + "description": "Hiba történt a bejelentkezés során." + } + }, + "verify": { + "userIdMissing": "Nincs megadva felhasználói azonosító!", + "successTitle": "Felhasználó ellenőrizve", + "successDescription": "A felhasználó ellenőrzése sikeresen megtörtént.", + "successContinue": "Tovább", + "setupAuthenticator": "Hitelesítő beállítása", + "verify": { + "title": "Felhasználó ellenőrzése", + "description": "Add meg az ellenőrző e-mailben kapott kódot.", + "noCodeReceived": "Nem kaptál kódot?", + "resendCode": "Kód újraküldése", + "codeSent": "Új kódot küldtünk az e-mail címedre.", + "submit": "Tovább", + "labels": { + "code": "Kód" + }, + "required": { + "code": "Ez a mező kötelező" + } + }, + "errors": { + "couldNotResendEmail": "Nem sikerült újraküldeni az e-mailt", + "couldNotVerifyUser": "Nem sikerült ellenőrizni a felhasználót", + "couldNotVerifyInvite": "Nem sikerült ellenőrizni a meghívást", + "couldNotVerifyEmail": "Nem sikerült ellenőrizni az e-mail címet", + "couldNotVerify": "Nem sikerült ellenőrizni", + "couldNotLoadUser": "Nem sikerült betölteni a felhasználót", + "couldNotLoadAuthenticators": "Nem sikerült betölteni a lehetséges hitelesítőket", + "couldNotCreateSession": "Nem sikerült létrehozni a munkamenetet", + "noHostFound": "Nem található kiszolgáló (host)", + "userAlreadyVerified": "A felhasználót már ellenőriztük!", + "couldNotResendInvite": "Nem sikerült újraküldeni a meghívást", + "inviteSendFailed": "Nem sikerült elküldeni a meghívó e-mailt", + "emailSendFailed": "Nem sikerült elküldeni az ellenőrző e-mailt", + "contextMissing": "Hiba történt. Kérjük, próbáld újra." + } + }, + "authenticator": { + "title": "Válassz hitelesítési módszert", + "description": "Válaszd ki, milyen módszerrel szeretnél hitelesíteni", + "noMethodsAvailable": "Nincs elérhető hitelesítési módszer", + "allSetup": "Már beállítottál egy hitelesítőt!", + "linkWithIDP": "vagy kapcsold össze egy azonosítószolgáltatóval", + "methods": { + "totp": "Hitelesítő alkalmazás", + "u2f": "Univerzális második faktor", + "otpEmail": "Kód e-mailben", + "otpSms": "Kód SMS-ben", + "passkey": "Jelkulcs", + "password": "Jelszó" + } + }, + "device": { + "usercode": { + "title": "Eszközkód", + "description": "Add meg az alkalmazásodban vagy eszközödön megjelenő kódot.", + "submit": "Tovább", + "labels": { + "code": "Kód" + }, + "required": { + "code": "Ez a mező kötelező" + } + }, + "request": { + "title": "A(z) {appName} kapcsolódni szeretne", + "description": "A(z) {appName} hozzáférést kap a következőkhöz:", + "disclaimer": "Az Engedélyezés gombra kattintva engedélyezed, hogy a(z) {appName} és a Zitadel a saját felhasználási feltételeik és adatvédelmi irányelveik szerint használja az adataidat. Ezt a hozzáférést bármikor visszavonhatod.", + "submit": "Engedélyezés", + "deny": "Elutasítás" + }, + "scope": { + "openid": "A személyazonosságod igazolása.", + "email": "Az e-mail címed megtekintése.", + "profile": "A teljes profilinformációd megtekintése.", + "offline_access": "Offline hozzáférés engedélyezése a fiókodhoz." + } + }, + "error": { + "noUserCode": "Nincs megadva felhasználói kód!", + "noDeviceRequest": "Nem található eszközkérés.", + "unknownContext": "Nem sikerült meghatározni a felhasználó kontextusát. Győződj meg róla, hogy előbb megadtad a felhasználónevet, vagy add meg a bejelentkezési nevet keresési paraméterként.", + "sessionExpired": "A munkameneted lejárt, vagy újbóli hitelesítést igényel. Kérjük, jelentkezz be újra.", + "failedLoading": "Nem sikerült betölteni az adatokat. Kérjük, próbáld újra.", + "tryagain": "Próbáld újra", + "couldNotContinueSession": "Nem sikerült folytatni a munkamenetet - hiányzó felhasználói információk", + "couldNotClearSession": "A munkamenetet nem sikerült befejezni. Kérjük, próbálja újra." + } +} diff --git a/auth/ui/v2/apps/login/locales/it.json b/auth/ui/v2/apps/login/locales/it.json new file mode 100644 index 0000000..a252e58 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/it.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Indietro", + "title": "Accedi con Zitadel" + }, + "accounts": { + "title": "Account", + "description": "Seleziona l'account che vuoi utilizzare.", + "addAnother": "Aggiungi un altro account", + "noResults": "Nessun account trovato", + "verified": "verificato", + "expired": "scaduto" + }, + "logout": { + "title": "Esci", + "description": "Seleziona l'account che desideri uscire", + "noResults": "Nessun account trovato", + "clear": "Elimina sessione", + "verifiedAt": "Ultima attività: {time}", + "success": { + "title": "Uscita riuscita", + "description": "Hai effettuato l'uscita con successo." + } + }, + "loginname": { + "title": "Bentornato!", + "description": "Inserisci i tuoi dati di accesso.", + "register": "Registrati come nuovo utente", + "submit": "Continua", + "labels": { + "loginname": "Nome di accesso", + "username": "Nome utente", + "usernameOrPhoneNumber": "Nome utente o numero di telefono", + "usernameOrEmail": "Nome utente o e-mail" + }, + "required": { + "loginName": "Questo campo è obbligatorio" + }, + "errors": { + "internalError": "Si è verificato un errore interno", + "couldNotGetLoginSettings": "Impossibile ottenere le impostazioni di accesso", + "couldNotSearchUsers": "Impossibile cercare gli utenti", + "couldNotGetDomain": "Impossibile ottenere il dominio", + "couldNotGetHost": "Impossibile ottenere l'host", + "couldNotStartIDPFlow": "Impossibile avviare il flusso IDP", + "moreThanOneUserFound": "È stato trovato più di un utente. Fornisci un identificatore univoco.", + "userNotFound": "Utente non trovato nel sistema", + "couldNotCreateSession": "Impossibile creare la sessione per l'utente", + "initialUserNotSupported": "Utente iniziale non supportato", + "localAuthenticationNotAllowed": "L'autenticazione locale non è consentita! Contatta il tuo amministratore per ulteriori informazioni.", + "passkeysNotAllowed": "Passkey non consentite! Contatta l'amministratore per maggiori informazioni.", + "couldNotFindIdentityProvider": "Impossibile trovare il provider di identità.", + "userNotActive": "L'utente non è attivo. Contatta l'amministratore per maggiori informazioni." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Si è verificato un errore", + "multipleUsersFound": "Trovati più utenti", + "userNotFound": "Utente non trovato nel sistema" + } + }, + "password": { + "verify": { + "title": "Password", + "description": "Inserisci la tua password.", + "resetPassword": "Reimposta Password", + "submit": "Continua", + "labels": { + "password": "Password" + }, + "required": { + "password": "Questo campo è obbligatorio" + }, + "errors": { + "couldNotVerifyPassword": "Impossibile verificare la password", + "couldNotResetPassword": "Impossibile reimpostare la password" + }, + "info": { + "passwordResetSent": "La password è stata reimpostata. Controlla la tua e-mail" + } + }, + "set": { + "title": "Imposta Password", + "description": "Imposta la password per il tuo account", + "codeSent": "Un nuovo codice è stato inviato al tuo indirizzo email.", + "noCodeReceived": "Non hai ricevuto un codice?", + "resend": "Invia di nuovo", + "submit": "Continua", + "labels": { + "code": "Codice", + "newPassword": "Nuova password", + "confirmPassword": "Conferma password" + }, + "required": { + "code": "Questo campo è obbligatorio", + "newPassword": "Devi fornire una password!", + "confirmPassword": "Questo campo è obbligatorio" + }, + "errors": { + "couldNotSetPassword": "Impossibile impostare la password", + "couldNotResetPassword": "Impossibile reimpostare la password", + "couldNotVerifyPassword": "Impossibile verificare la password" + } + }, + "change": { + "title": "Cambia Password", + "description": "Imposta la password per il tuo account", + "submit": "Continua", + "labels": { + "currentPassword": "Password attuale", + "newPassword": "Nuova password", + "confirmPassword": "Conferma password" + }, + "required": { + "currentPassword": "Devi fornire la tua password attuale!", + "newPassword": "Devi fornire una nuova password!", + "confirmPassword": "Questo campo è obbligatorio" + }, + "errors": { + "currentPasswordInvalid": "La password attuale non è corretta.", + "couldNotChangePassword": "Impossibile modificare la password", + "couldNotVerifyPassword": "Impossibile verificare la password", + "unknownError": "Errore sconosciuto" + } + }, + "complexity": { + "length": "Deve contenere almeno {minLength} caratteri.", + "hasSymbol": "Deve includere un simbolo.", + "hasNumber": "Deve includere un numero.", + "hasUppercase": "Deve includere una lettera maiuscola.", + "hasLowercase": "Deve includere una lettera minuscola.", + "equals": "La conferma della password corrisponde.", + "matches": "Corrisponde", + "doesNotMatch": "Non corrisponde" + }, + "errors": { + "noHostFound": "Nessun host trovato", + "couldNotSendResetLink": "Impossibile inviare il link per il ripristino della password", + "couldNotCreateSessionForUser": "Impossibile creare una sessione per l'utente", + "couldNotVerifyPassword": "Impossibile verificare la password", + "failedToAuthenticate": "Autenticazione non riuscita. Hai effettuato {failedAttempts} di {maxPasswordAttempts} tentativi di password.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Autenticazione non riuscita.", + "accountLockedContactAdmin": " Contatta l'amministratore per sbloccare il tuo account", + "userNotFound": "Utente non trovato nel sistema", + "initialUserNotSupported": "Utente iniziale non supportato", + "userInitialStateNotSupported": "Lo stato iniziale dell'utente non è supportato", + "codeOrVerificationRequired": "Devi fornire un codice o avere una verifica utente valida", + "verificationRequired": "È necessario effettuare la verifica utente", + "couldNotLoadSession": "Impossibile caricare la sessione", + "couldNotLoadAuthMethods": "Impossibile caricare i metodi di autenticazione", + "failedPrecondition": "Precondizione non soddisfatta", + "sessionNotValid": "La sessione non è valida", + "passwordVerificationMissing": "Manca la verifica della password.", + "passwordVerificationTooOld": "La verifica della password è troppo vecchia. Si prega di verificare nuovamente la password.", + "passwordResetNotAllowed": "Il ripristino della password non è consentito. Contatta il tuo amministratore per ulteriori informazioni.", + "localAuthenticationNotAllowed": "L'autenticazione locale non è consentita! Contatta il tuo amministratore per ulteriori informazioni." + } + }, + "idp": { + "title": "Accedi con SSO", + "description": "Seleziona uno dei seguenti provider per accedere", + "orSignInWith": "o accedi con", + "signInWithApple": "Accedi con Apple", + "signInWithGoogle": "Accedi con Google", + "signInWithAzureAD": "Accedi con AzureAD", + "signInWithGithub": "Accedi con GitHub", + "signInWithGitlab": "Accedi con GitLab", + "signInWithZitadel": "Accedi con Zitadel", + "loginError": { + "title": "Accesso fallito", + "description": "Si è verificato un errore durante il tentativo di accesso." + }, + "linkingError": { + "title": "Collegamento account fallito", + "description": "Si è verificato un errore durante il tentativo di collegare il tuo account." + }, + "completeRegister": { + "title": "Completa la registrazione", + "description": "Completa la registrazione del tuo account." + }, + "accountNotFound": { + "title": "Account non trovato", + "description": "Non siamo riusciti a trovare un account associato alle tue credenziali del provider di identità.", + "info": "Nessun account esistente è stato trovato. Accedi con un account esistente o contatta il tuo amministratore per assistenza.", + "backToLogin": "Torna al login" + }, + "registrationFailed": { + "title": "Registrazione non disponibile", + "description": "Non siamo riusciti a completare il processo di registrazione.", + "info": "Impossibile determinare l'organizzazione per la registrazione. Contatta il tuo amministratore per assistenza.", + "backToLogin": "Torna al login" + }, + "processing": { + "message": "Elaborazione autenticazione in corso...", + "noRedirect": "Nessun reindirizzamento o errore ricevuto dal server", + "unexpectedError": "Si è verificato un errore imprevisto" + }, + "errors": { + "missingParameters": "Parametri richiesti mancanti", + "missingIdpInfo": "Informazioni IDP mancanti", + "idpNotFound": "Provider di identità non trovato", + "linkingNotAllowed": "Il collegamento non è consentito per questo provider di identità", + "linkingFailed": "Collegamento del provider di identità all'account non riuscito", + "autoLinkingFailed": "Collegamento automatico dell'account non riuscito", + "userCreationFailed": "Creazione dell'account utente non riuscita", + "orgResolutionFailed": "Impossibile determinare l'organizzazione per la registrazione", + "sessionCreationFailed": "Impossibile creare la sessione o determinare il reindirizzamento", + "unknownError": "Si è verificato un errore sconosciuto" + } + }, + "ldap": { + "title": "Accedi con LDAP", + "description": "Inserisci le tue credenziali LDAP.", + "submit": "Continua", + "labels": { + "username": "Nome utente", + "password": "Password" + }, + "required": { + "username": "Questo campo è obbligatorio", + "password": "Questo campo è obbligatorio" + } + }, + "mfa": { + "verify": { + "title": "Verifica la tua identità", + "description": "Scegli uno dei seguenti fattori.", + "noResults": "Nessun secondo fattore disponibile per la configurazione." + }, + "set": { + "title": "Configura l'autenticazione a 2 fattori", + "description": "Scegli uno dei seguenti secondi fattori.", + "skip": "Salta" + } + }, + "otp": { + "verify": { + "title": "Verifica l'autenticazione a 2 fattori", + "totpDescription": "Inserisci il codice dalla tua app di autenticazione.", + "smsDescription": "Inserisci il codice ricevuto via SMS.", + "emailDescription": "Inserisci il codice ricevuto via email.", + "noCodeReceived": "Non hai ricevuto un codice?", + "resendCode": "Invia di nuovo il codice", + "resendCodeIn": "Invia di nuovo il codice ({seconds}s)", + "submit": "Continua", + "labels": { + "code": "Codice" + }, + "required": { + "code": "Questo campo è obbligatorio" + } + }, + "set": { + "title": "Configura l'autenticazione a 2 fattori", + "totpDescription": "Scansiona il codice QR con la tua app di autenticazione.", + "smsDescription": "Inserisci il tuo numero di telefono per ricevere un codice via SMS.", + "emailDescription": "Inserisci il tuo indirizzo email per ricevere un codice via email.", + "totpRegisterDescription": "Scansiona il codice QR o naviga manualmente all'URL.", + "emailAddDescription": "Usa un codice monouso inviato al tuo indirizzo email verificato come secondo fattore.", + "smsAddDescription": "Usa un codice monouso inviato al tuo numero di telefono verificato come secondo fattore.", + "add": "Aggiungi", + "emailAdded": "Codice via email aggiunto.", + "smsAdded": "Codice via SMS aggiunto.", + "submit": "Continua", + "labels": { + "code": "Codice" + }, + "required": { + "code": "Questo campo è obbligatorio" + } + }, + "errors": { + "couldNotRequestChallenge": "Impossibile richiedere la challenge OTP", + "couldNotVerifyCode": "Impossibile verificare il codice OTP", + "couldNotGetSession": "Impossibile caricare la sessione. Accedi di nuovo.", + "invalidMethod": "Questo secondo fattore non è supportato.", + "couldNotAddEmail": "Impossibile aggiungere il codice via email.", + "couldNotAddSms": "Impossibile aggiungere il codice via SMS.", + "emailNotVerified": "Verifica il tuo indirizzo email prima di aggiungere codici via email.", + "phoneNotVerified": "Verifica il tuo numero di telefono prima di aggiungere codici via SMS." + } + }, + "passkey": { + "verify": { + "title": "Autenticati con una passkey", + "description": "Il tuo dispositivo chiederà la tua impronta digitale, il volto o il blocco schermo", + "usePassword": "Usa password", + "submit": "Continua", + "errors": { + "couldNotRequestChallenge": "Impossibile richiedere la sfida passkey", + "couldNotVerifyPasskey": "Impossibile verificare la passkey", + "noResponseReceived": "Verifica passkey fallita - nessuna risposta ricevuta", + "noRedirectProvided": "Verifica passkey completata ma nessun reindirizzamento fornito", + "couldNotRetrievePasskey": "Si è verificato un errore durante il recupero della passkey", + "verificationCancelled": "La verifica della passkey è stata annullata", + "verificationFailed": "Si è verificato un errore durante la verifica della passkey", + "couldNotFindSession": "Impossibile trovare la sessione", + "couldNotUpdateSession": "Impossibile aggiornare la sessione", + "userNotFound": "Utente non trovato nel sistema", + "couldNotDetermineRedirect": "Impossibile determinare l'URL di reindirizzamento dopo la verifica passkey" + } + }, + "set": { + "title": "Configura una passkey", + "description": "Il tuo dispositivo chiederà la tua impronta digitale, il volto o il blocco schermo", + "info": { + "description": "Una passkey è un metodo di autenticazione su un dispositivo come la tua impronta digitale, Apple FaceID o simili.", + "link": "Autenticazione con Passkey" + }, + "skip": "Salta", + "submit": "Continua" + } + }, + "u2f": { + "verify": { + "title": "Verifica l'autenticazione a 2 fattori", + "description": "Verifica il tuo account con il tuo dispositivo." + }, + "set": { + "title": "Configura l'autenticazione a 2 fattori", + "description": "Configura un dispositivo come secondo fattore.", + "submit": "Continua" + } + }, + "register": { + "methods": { + "passkey": "Passkey", + "password": "Password" + }, + "disabled": { + "title": "Registration disabled", + "description": "Registrazione disabilitata. Contatta l'amministratore di sistema per assistenza." + }, + "missingdata": { + "title": "Registrazione", + "description": "Inserisci i tuoi dati per registrarti." + }, + "title": "Registrati", + "description": "Crea il tuo account Zitadel.", + "noMethodAvailableWarning": "Nessun metodo di autenticazione disponibile. Contatta l'amministratore di sistema per assistenza.", + "selectMethod": "Seleziona il metodo con cui desideri autenticarti", + "agreeTo": "Per registrarti devi accettare i termini e le condizioni", + "termsOfService": "Termini di Servizio", + "privacyPolicy": "Informativa sulla Privacy", + "submit": "Continua", + "password": { + "title": "Imposta Password", + "description": "Imposta la password per il tuo account", + "submit": "Continua", + "labels": { + "password": "Password", + "confirmPassword": "Conferma password" + }, + "required": { + "password": "Devi fornire una password!", + "confirmPassword": "Questo campo è obbligatorio" + } + }, + "labels": { + "firstname": "Nome", + "lastname": "Cognome", + "email": "E-mail" + }, + "required": { + "firstname": "Questo campo è obbligatorio", + "lastname": "Questo campo è obbligatorio", + "email": "Questo campo è obbligatorio" + }, + "errors": { + "couldNotCreateUser": "Impossibile creare l'utente", + "couldNotCreateSession": "Impossibile creare la sessione", + "userNotFound": "Utente non trovato nel sistema", + "couldNotLinkIDP": "Impossibile collegare l'IDP all'utente", + "couldNotRegisterUser": "Impossibile registrare l'utente", + "sessionMismatch": "La registrazione è stata avviata in un altro browser. Accedi di nuovo con il tuo provider di identità." + } + }, + "invite": { + "title": "Invita Utente", + "description": "Inserisci l'indirizzo email dell'utente che desideri invitare.", + "info": "L'utente riceverà un'email con ulteriori istruzioni.", + "notAllowed": "Non hai i permessi per invitare un utente.", + "submit": "Invita Utente", + "success": { + "title": "Invito inviato", + "description": "L'utente è stato invitato con successo.", + "verified": "L'utente è stato invitato e ha già verificato la sua email.", + "notVerifiedYet": "L'utente è stato invitato. Riceverà un'email con ulteriori istruzioni.", + "submit": "Invita un altro utente" + } + }, + "signedin": { + "title": "Benvenuto {user}!", + "description": "Sei connesso.", + "continue": "Continua", + "error": { + "title": "Errore", + "description": "Si è verificato un errore durante il tentativo di accesso." + } + }, + "verify": { + "userIdMissing": "Nessun userId fornito!", + "successTitle": "Utente verificato", + "successDescription": "L'utente è stato verificato con successo.", + "successContinue": "Continua", + "setupAuthenticator": "Configura autenticatore", + "verify": { + "title": "Verifica utente", + "description": "Inserisci il codice fornito nell'email di verifica.", + "noCodeReceived": "Non hai ricevuto un codice?", + "resendCode": "Invia di nuovo il codice", + "codeSent": "Un codice è stato appena inviato al tuo indirizzo email.", + "submit": "Continua", + "labels": { + "code": "Codice" + }, + "required": { + "code": "Questo campo è obbligatorio" + } + }, + "errors": { + "couldNotResendEmail": "Impossibile reinviare l'email", + "couldNotVerifyUser": "Impossibile verificare l'utente", + "couldNotVerifyInvite": "Impossibile verificare l'invito", + "couldNotVerifyEmail": "Impossibile verificare l'email", + "couldNotVerify": "Impossibile verificare", + "couldNotLoadUser": "Impossibile caricare l'utente", + "couldNotLoadAuthenticators": "Impossibile caricare gli autenticatori possibili", + "couldNotCreateSession": "Impossibile creare la sessione", + "noHostFound": "Nessun host trovato", + "userAlreadyVerified": "L'utente è già verificato!", + "couldNotResendInvite": "Impossibile reinviare l'invito", + "inviteSendFailed": "Impossibile inviare l'email di invito", + "emailSendFailed": "Impossibile inviare l'email di verifica", + "contextMissing": "Si è verificato un errore. Riprova." + } + }, + "authenticator": { + "title": "Seleziona metodo di autenticazione", + "description": "Seleziona il metodo con cui desideri autenticarti", + "noMethodsAvailable": "Nessun metodo di autenticazione disponibile", + "allSetup": "Hai già configurato un autenticatore!", + "linkWithIDP": "o collega con un Identity Provider", + "methods": { + "totp": "App di autenticazione", + "u2f": "Secondo fattore universale", + "otpEmail": "Codice via email", + "otpSms": "Codice via SMS", + "passkey": "Passkey", + "password": "Password" + } + }, + "device": { + "usercode": { + "title": "Codice dispositivo", + "description": "Inserisci il codice.", + "submit": "Continua", + "labels": { + "code": "Codice" + }, + "required": { + "code": "Questo campo è obbligatorio" + } + }, + "request": { + "title": "{appName} desidera connettersi:", + "description": "{appName} avrà accesso a:", + "disclaimer": "Cliccando su Consenti, autorizzi {appName} e Zitadel a utilizzare le tue informazioni in conformità con i rispettivi termini di servizio e politiche sulla privacy. Puoi revocare questo accesso in qualsiasi momento.", + "submit": "Consenti", + "deny": "Nega" + }, + "scope": { + "openid": "Verifica la tua identità.", + "email": "Accedi al tuo indirizzo email.", + "profile": "Accedi alle informazioni complete del tuo profilo.", + "offline_access": "Consenti l'accesso offline al tuo account." + } + }, + "error": { + "noUserCode": "Nessun codice utente fornito!", + "noDeviceRequest": "Nessuna richiesta di dispositivo trovata.", + "unknownContext": "Impossibile ottenere il contesto dell'utente. Assicurati di inserire prima il nome utente o di fornire un loginName come parametro di ricerca.", + "sessionExpired": "La tua sessione è scaduta o richiede una nuova autenticazione. Effettua nuovamente l'accesso.", + "failedLoading": "Impossibile caricare i dati. Riprova.", + "tryagain": "Riprova", + "couldNotContinueSession": "Impossibile continuare con la sessione - informazioni utente mancanti", + "couldNotClearSession": "Impossibile terminare la sessione. Riprova." + } +} diff --git a/auth/ui/v2/apps/login/locales/ja.json b/auth/ui/v2/apps/login/locales/ja.json new file mode 100644 index 0000000..8ee372b --- /dev/null +++ b/auth/ui/v2/apps/login/locales/ja.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "戻る", + "title": "Zitadelでログイン" + }, + "accounts": { + "title": "アカウント", + "description": "使用するアカウントを選択してください。", + "addAnother": "別のアカウントを追加", + "noResults": "アカウントが見つかりません", + "verified": "認証済み", + "expired": "期限切れ" + }, + "logout": { + "title": "ログアウト", + "description": "セッションを終了するアカウントをクリックしてください", + "noResults": "アカウントが見つかりません", + "clear": "セッション終了", + "verifiedAt": "最後のアクティブ: {time}", + "success": { + "title": "ログアウト完了", + "description": "正常にログアウトしました。" + } + }, + "loginname": { + "title": "お帰りなさい!", + "description": "ログイン情報を入力してください。", + "register": "新規ユーザー登録", + "submit": "続行", + "labels": { + "loginname": "ログイン名", + "username": "ユーザー名", + "usernameOrPhoneNumber": "ユーザー名または電話番号", + "usernameOrEmail": "ユーザー名またはメールアドレス" + }, + "required": { + "loginName": "必須項目です" + }, + "errors": { + "internalError": "内部エラーが発生しました", + "couldNotGetLoginSettings": "ログイン設定を取得できませんでした", + "couldNotSearchUsers": "ユーザーを検索できませんでした", + "couldNotGetDomain": "ドメインを取得できませんでした", + "couldNotGetHost": "ホストを取得できませんでした", + "couldNotStartIDPFlow": "IDPフローを開始できませんでした", + "moreThanOneUserFound": "複数のユーザーが見つかりました。一意の識別子を指定してください。", + "userNotFound": "ユーザーがシステムに見つかりません", + "couldNotCreateSession": "ユーザーのセッションを作成できませんでした", + "initialUserNotSupported": "初期ユーザーはサポートされていません", + "localAuthenticationNotAllowed": "ローカル認証は許可されていません! 詳細については管理者に問い合わせてください。", + "passkeysNotAllowed": "パスキーは許可されていません!詳細については管理者にお問い合わせください。", + "couldNotFindIdentityProvider": "IDプロバイダーが見つかりませんでした。", + "userNotActive": "ユーザーはアクティブではありません。詳細については管理者にお問い合わせください。" + } + }, + "password": { + "verify": { + "title": "パスワード", + "description": "パスワードを入力してください。", + "resetPassword": "パスワードをリセット", + "submit": "続行", + "labels": { + "password": "パスワード" + }, + "required": { + "password": "必須項目です" + }, + "errors": { + "couldNotVerifyPassword": "パスワードを確認できませんでした", + "couldNotResetPassword": "パスワードをリセットできませんでした" + }, + "info": { + "passwordResetSent": "パスワードがリセットされました。メールを確認してください" + } + }, + "set": { + "title": "パスワード設定", + "description": "アカウントのパスワードを設定してください", + "codeSent": "新しいコードがメールアドレスに送信されました。", + "noCodeReceived": "コードが届きませんか?", + "resend": "コードを再送信", + "submit": "続行", + "labels": { + "code": "コード", + "newPassword": "新しいパスワード", + "confirmPassword": "パスワード確認" + }, + "required": { + "code": "必須項目です", + "newPassword": "パスワードを入力してください!", + "confirmPassword": "必須項目です" + }, + "errors": { + "couldNotSetPassword": "パスワードを設定できませんでした", + "couldNotResetPassword": "パスワードをリセットできませんでした", + "couldNotVerifyPassword": "パスワードを確認できませんでした" + } + }, + "change": { + "title": "パスワード変更", + "description": "アカウントのパスワードを設定してください", + "submit": "続行", + "labels": { + "currentPassword": "現在のパスワード", + "newPassword": "新しいパスワード", + "confirmPassword": "パスワード確認" + }, + "required": { + "currentPassword": "現在のパスワードを入力してください!", + "newPassword": "新しいパスワードを入力してください!", + "confirmPassword": "必須項目です" + }, + "errors": { + "currentPasswordInvalid": "現在のパスワードが正しくありません。", + "couldNotChangePassword": "パスワードを変更できませんでした", + "couldNotVerifyPassword": "パスワードを確認できませんでした", + "unknownError": "不明なエラー" + } + }, + "errors": { + "passwordVerificationMissing": "パスワード確認がありません。", + "passwordVerificationTooOld": "パスワード確認が古すぎます。もう一度パスワードを確認してください。", + "noHostFound": "ホストが見つかりません", + "couldNotSendResetLink": "パスワードリセットリンクを送信できませんでした", + "couldNotCreateSessionForUser": "ユーザーのセッションを作成できませんでした", + "couldNotVerifyPassword": "パスワードを確認できませんでした", + "failedToAuthenticate": "認証に失敗しました。パスワード試行回数 {maxPasswordAttempts} 回中 {failedAttempts} 回失敗しました。{lockoutMessage}", + "failedToAuthenticateNoLimit": "認証に失敗しました。", + "accountLockedContactAdmin": " アカウントのロックを解除するには管理者に連絡してください", + "userNotFound": "ユーザーがシステムに見つかりません", + "initialUserNotSupported": "初期ユーザーはサポートされていません", + "userInitialStateNotSupported": "ユーザーの初期状態はサポートされていません", + "codeOrVerificationRequired": "コードを提供するか、有効なユーザー確認チェックを行う必要があります", + "verificationRequired": "ユーザー確認チェックを行う必要があります", + "couldNotLoadSession": "セッションを読み込めませんでした", + "couldNotLoadAuthMethods": "認証方法を読み込めませんでした", + "failedPrecondition": "前提条件に失敗しました", + "sessionNotValid": "セッションが無効です", + "passwordResetNotAllowed": "パスワードのリセットは許可されていません。詳細については管理者に問い合わせてください。", + "localAuthenticationNotAllowed": "ローカル認証は許可されていません! 詳細については管理者に問い合わせてください。" + }, + "complexity": { + "length": "{minLength} 文字以上である必要があります。", + "hasSymbol": "記号を含める必要があります。", + "hasNumber": "数字を含める必要があります。", + "hasUppercase": "大文字を含める必要があります。", + "hasLowercase": "小文字を含める必要があります。", + "equals": "パスワード確認が一致しました。", + "matches": "一致します", + "doesNotMatch": "一致しません" + } + }, + "idp": { + "title": "SSOでサインイン", + "description": "以下のプロバイダーを選択してサインインしてください", + "orSignInWith": "または次でサインイン", + "signInWithApple": "Appleでサインイン", + "signInWithGoogle": "Googleでサインイン", + "signInWithAzureAD": "AzureADでサインイン", + "signInWithGithub": "GitHubでサインイン", + "signInWithGitlab": "GitLabでサインイン", + "signInWithZitadel": "Zitadelでサインイン", + "loginError": { + "title": "ログイン失敗", + "description": "ログインの際にエラーが発生しました。" + }, + "linkingError": { + "title": "アカウント連携失敗", + "description": "アカウント連携の際にエラーが発生しました。" + }, + "completeRegister": { + "title": "データを完成させる", + "description": "メールアドレスと名前を入力して登録を完了してください。" + }, + "accountNotFound": { + "title": "アカウントが見つかりません", + "description": "アイデンティティプロバイダの認証情報に関連付けられたアカウントが見つかりませんでした。", + "info": "既存のアカウントが見つかりませんでした。既存のアカウントでサインインするか、管理者にお問い合わせください。", + "backToLogin": "ログインに戻る" + }, + "registrationFailed": { + "title": "登録が利用できません", + "description": "登録プロセスを完了できませんでした。", + "info": "登録する組織を特定できませんでした。管理者にお問い合わせください。", + "backToLogin": "ログインに戻る" + }, + "processing": { + "message": "認証を処理しています...", + "noRedirect": "サーバーからリダイレクトまたはエラーが返されませんでした", + "unexpectedError": "予期しないエラーが発生しました" + }, + "errors": { + "missingParameters": "必要なパラメータが不足しています", + "missingIdpInfo": "IDP情報が不足しています", + "idpNotFound": "アイデンティティプロバイダが見つかりません", + "linkingNotAllowed": "このアイデンティティプロバイダとの連携は許可されていません", + "linkingFailed": "アイデンティティプロバイダのアカウントへの連携に失敗しました", + "autoLinkingFailed": "アカウントの自動連携に失敗しました", + "userCreationFailed": "ユーザーアカウントの作成に失敗しました", + "orgResolutionFailed": "登録する組織を特定できませんでした", + "sessionCreationFailed": "セッションの作成またはリダイレクトの決定に失敗しました", + "unknownError": "不明なエラーが発生しました" + } + }, + "ldap": { + "title": "LDAPログイン", + "description": "LDAP認証情報を入力してください。", + "submit": "続行", + "labels": { + "username": "ユーザー名", + "password": "パスワード" + }, + "required": { + "username": "必須項目です", + "password": "必須項目です" + } + }, + "mfa": { + "verify": { + "title": "本人確認", + "description": "以下の要素の中から一つを選択してください。", + "noResults": "設定可能な二要素認証がありません。" + }, + "set": { + "title": "二要素認証の設定", + "description": "以下の二要素認証の中から一つを選択してください。", + "skip": "スキップ" + } + }, + "otp": { + "verify": { + "title": "二要素認証", + "totpDescription": "認証アプリからコードを入力してください。", + "smsDescription": "SMSで受信したコードを入力してください。", + "emailDescription": "メールで受信したコードを入力してください。", + "noCodeReceived": "コードが届きませんか?", + "resendCode": "コードを再送信", + "resendCodeIn": "コードを再送信 ({seconds}秒)", + "submit": "続行", + "labels": { + "code": "コード" + }, + "required": { + "code": "必須項目です" + } + }, + "set": { + "title": "二要素認証の設定", + "totpDescription": "認証アプリでQRコードをスキャンしてください。", + "smsDescription": "SMSでコードを受信する電話番号を入力してください。", + "emailDescription": "メールでコードを受信するメールアドレスを入力してください。", + "totpRegisterDescription": "QRコードをスキャンするか、URLに手動でアクセスしてください。", + "emailAddDescription": "確認済みのメールアドレスに送信されるワンタイムコードを第2要素として使用します。", + "smsAddDescription": "確認済みの電話番号に送信されるワンタイムコードを第2要素として使用します。", + "add": "追加", + "emailAdded": "メールによるコードを追加しました。", + "smsAdded": "SMSによるコードを追加しました。", + "submit": "続行", + "labels": { + "code": "コード" + }, + "required": { + "code": "必須項目です" + } + }, + "errors": { + "couldNotRequestChallenge": "OTPチャレンジをリクエストできませんでした", + "couldNotVerifyCode": "OTPコードを確認できませんでした", + "couldNotGetSession": "セッションを読み込めませんでした。もう一度サインインしてください。", + "invalidMethod": "この第2要素はサポートされていません。", + "couldNotAddEmail": "メールによるコードを追加できませんでした。", + "couldNotAddSms": "SMSによるコードを追加できませんでした。", + "emailNotVerified": "メールによるコードを追加する前に、メールアドレスを確認してください。", + "phoneNotVerified": "SMSによるコードを追加する前に、電話番号を確認してください。" + } + }, + "passkey": { + "verify": { + "title": "パスキーで認証", + "description": "デバイスが指紋、顔、または画面ロックの入力を求めます", + "usePassword": "パスワードを使用", + "submit": "続行", + "errors": { + "couldNotRequestChallenge": "パスキーチャレンジを要求できませんでした", + "couldNotVerifyPasskey": "パスキーを確認できませんでした", + "noResponseReceived": "パスキー確認に失敗しました - 応答がありません", + "noRedirectProvided": "パスキー確認は完了しましたが、リダイレクトが提供されませんでした", + "couldNotRetrievePasskey": "パスキーの取得中にエラーが発生しました", + "verificationCancelled": "パスキー確認がキャンセルされました", + "verificationFailed": "パスキー確認中にエラーが発生しました", + "couldNotFindSession": "セッションが見つかりませんでした", + "couldNotUpdateSession": "セッションを更新できませんでした", + "userNotFound": "ユーザーがシステムに見つかりません", + "couldNotDetermineRedirect": "パスキー確認後のリダイレクトURLを決定できませんでした" + } + }, + "set": { + "title": "パスキーの設定", + "description": "デバイスが指紋、顔、または画面ロックの入力を求めます", + "info": { + "description": "パスキーは、指紋やApple FaceIDなどのデバイス上の認証方法です。", + "link": "パスキー認証" + }, + "skip": "スキップ", + "submit": "続行" + } + }, + "u2f": { + "verify": { + "title": "二要素認証", + "description": "デバイスでアカウントを確認してください。" + }, + "set": { + "title": "二要素認証の設定", + "description": "デバイスを二要素認証として設定します。", + "submit": "続行" + } + }, + "register": { + "methods": { + "passkey": "パスキー", + "password": "パスワード" + }, + "disabled": { + "title": "登録が無効", + "description": "登録が無効になっています。管理者にお問い合わせください。" + }, + "missingdata": { + "title": "データが不足", + "description": "登録するにはメールアドレス、姓、名を入力してください。" + }, + "title": "登録", + "description": "Zitadelアカウントを作成します。", + "noMethodAvailableWarning": "使用可能な認証方法がありません。管理者にお問い合わせください。", + "selectMethod": "認証に使用する方法を選択してください", + "agreeTo": "登録するには利用規約に同意する必要があります", + "termsOfService": "利用規約", + "privacyPolicy": "プライバシーポリシー", + "submit": "続行", + "password": { + "title": "パスワード設定", + "description": "アカウントのパスワードを設定してください", + "submit": "続行", + "labels": { + "password": "パスワード", + "confirmPassword": "パスワード確認" + }, + "required": { + "password": "パスワードを入力してください!", + "confirmPassword": "必須項目です" + } + }, + "labels": { + "firstname": "名", + "lastname": "姓", + "email": "メールアドレス" + }, + "required": { + "firstname": "必須項目です", + "lastname": "必須項目です", + "email": "必須項目です" + }, + "errors": { + "couldNotCreateUser": "ユーザーを作成できませんでした", + "couldNotCreateSession": "セッションを作成できませんでした", + "userNotFound": "ユーザーがシステムに見つかりません", + "couldNotLinkIDP": "IDPをユーザーにリンクできませんでした", + "couldNotRegisterUser": "ユーザーを登録できませんでした", + "sessionMismatch": "登録は別のブラウザで開始されました。IDプロバイダーでもう一度サインインしてください。" + } + }, + "invite": { + "title": "ユーザー招待", + "description": "招待するユーザーのメールアドレスと名前を入力してください。", + "info": "ユーザーには詳細な手順が記載されたメールが送信されます。", + "notAllowed": "設定によりユーザーを招待できません。", + "submit": "続行", + "success": { + "title": "ユーザーを招待しました", + "description": "メールが正常に送信されました。", + "verified": "ユーザーが招待され、既にメールアドレスが確認済みです。", + "notVerifiedYet": "ユーザーが招待されました。詳細な手順が記載されたメールを受信します。", + "submit": "別のユーザーを招待" + } + }, + "signedin": { + "title": "ようこそ {user}さん!", + "description": "サインインしました。", + "continue": "続行", + "error": { + "title": "エラー", + "description": "サインインの際にエラーが発生しました。" + } + }, + "verify": { + "userIdMissing": "ユーザーIDが指定されていません!", + "successTitle": "ユーザー確認完了", + "successDescription": "ユーザーの確認が正常に完了しました。", + "successContinue": "続行", + "setupAuthenticator": "認証の設定", + "verify": { + "title": "ユーザー確認", + "description": "確認メールに記載されたコードを入力してください。", + "noCodeReceived": "コードが届きませんか?", + "resendCode": "コードを再送信", + "codeSent": "確認コードをメールアドレスに送信しました。", + "submit": "続行", + "labels": { + "code": "コード" + }, + "required": { + "code": "必須項目です" + } + }, + "errors": { + "couldNotResendEmail": "メールを再送信できませんでした", + "couldNotVerifyUser": "ユーザーを確認できませんでした", + "couldNotVerifyInvite": "招待を確認できませんでした", + "couldNotVerifyEmail": "メールアドレスを確認できませんでした", + "couldNotVerify": "確認できませんでした", + "couldNotLoadUser": "ユーザーを読み込めませんでした", + "couldNotLoadAuthenticators": "認証方法を読み込めませんでした", + "couldNotCreateSession": "セッションを作成できませんでした", + "noHostFound": "ホストが見つかりません", + "userAlreadyVerified": "ユーザーは既に確認済みです!", + "couldNotResendInvite": "招待を再送信できませんでした", + "inviteSendFailed": "招待メールの送信に失敗しました", + "emailSendFailed": "確認メールの送信に失敗しました", + "contextMissing": "エラーが発生しました。もう一度お試しください。" + } + }, + "authenticator": { + "title": "認証方法を選択", + "description": "認証に使用する方法を選択してください", + "noMethodsAvailable": "使用可能な認証方法がありません", + "allSetup": "認証の設定は既に完了しています!", + "linkWithIDP": "またはIDプロバイダーと連携", + "methods": { + "totp": "認証アプリ", + "u2f": "ユニバーサルセカンドファクター", + "otpEmail": "メールでコードを受け取る", + "otpSms": "SMSでコードを受け取る", + "passkey": "パスキー", + "password": "パスワード" + } + }, + "device": { + "usercode": { + "title": "デバイスコード", + "description": "アプリまたはデバイスに表示されるコードを入力してください。", + "submit": "続行", + "labels": { + "code": "コード" + }, + "required": { + "code": "必須項目です" + } + }, + "request": { + "title": "{appName}が接続を要求しています", + "description": "{appName}は以下にアクセスします:", + "disclaimer": "「許可」をクリックすることで、{appName}とZitadelがそれぞれの利用規約およびプライバシーポリシーに従ってあなたの情報を使用することを許可します。このアクセスはいつでも取り消すことができます。", + "submit": "許可", + "deny": "拒否" + }, + "scope": { + "openid": "本人確認を行います。", + "email": "メールアドレスを表示します。", + "profile": "すべてのプロフィール情報を表示します。", + "offline_access": "アカウントへのオフラインアクセスを許可します。" + } + }, + "error": { + "noUserCode": "ユーザーコードが指定されていません!", + "noDeviceRequest": "デバイスリクエストが見つかりません。", + "unknownContext": "ユーザーのコンテキストを取得できませんでした。最初にユーザー名を入力するか、検索パラメータとしてloginNameを指定してください。", + "sessionExpired": "セッションが期限切れか、再認証が必要です。再度ログインしてください。", + "failedLoading": "データの読み込みに失敗しました。再試行してください。", + "tryagain": "再試行", + "couldNotContinueSession": "セッションを継続できませんでした - ユーザー情報が不足しています", + "couldNotClearSession": "セッションを終了できませんでした。もう一度お試しください。" + }, + "zitadel": { + "errors": { + "errorOccured": "エラーが発生しました", + "multipleUsersFound": "複数のユーザーが見つかりました", + "userNotFound": "ユーザーがシステムに見つかりません" + } + } +} diff --git a/auth/ui/v2/apps/login/locales/nl.json b/auth/ui/v2/apps/login/locales/nl.json new file mode 100644 index 0000000..17f019a --- /dev/null +++ b/auth/ui/v2/apps/login/locales/nl.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Terug", + "title": "Inloggen met Zitadel" + }, + "accounts": { + "title": "Accounts", + "description": "Selecteer het account dat je wilt gebruiken.", + "addAnother": "Nog een account toevoegen", + "noResults": "Geen accounts gevonden", + "verified": "geverifieerd", + "expired": "verlopen" + }, + "logout": { + "title": "Uitloggen", + "description": "Klik op een account om de sessie te beëindigen", + "noResults": "Geen accounts gevonden", + "clear": "Sessie beëindigen", + "verifiedAt": "Laatst actief: {time}", + "success": { + "title": "Succesvol uitgelogd", + "description": "Je bent succesvol uitgelogd." + } + }, + "loginname": { + "title": "Welkom terug!", + "description": "Voer jouw inloggegevens in.", + "register": "Nieuwe gebruiker registreren", + "submit": "Verder", + "labels": { + "loginname": "Loginnaam", + "username": "Gebruikersnaam", + "usernameOrPhoneNumber": "Telefoonnummer of gebruikersnaam", + "usernameOrEmail": "E-mail of gebruikersnaam" + }, + "required": { + "loginName": "Dit veld is verplicht" + }, + "errors": { + "internalError": "Er is een interne fout opgetreden", + "couldNotGetLoginSettings": "Kon aanmeldinstellingen niet ophalen", + "couldNotSearchUsers": "Kon gebruikers niet zoeken", + "couldNotGetDomain": "Kon domein niet ophalen", + "couldNotGetHost": "Kon host niet ophalen", + "couldNotStartIDPFlow": "Kon IDP-stroom niet starten", + "moreThanOneUserFound": "Meer dan één gebruiker gevonden. Geef een unieke identificatie op.", + "userNotFound": "Gebruiker niet in het systeem gevonden", + "couldNotCreateSession": "Kon sessie voor gebruiker niet aanmaken", + "initialUserNotSupported": "Initiële gebruiker wordt niet ondersteund", + "localAuthenticationNotAllowed": "Lokale authenticatie is niet toegestaan! Neem contact op met uw beheerder voor meer informatie.", + "passkeysNotAllowed": "Passkeys niet toegestaan! Neem contact op met jouw beheerder voor meer informatie.", + "couldNotFindIdentityProvider": "Kon identiteitsprovider niet vinden.", + "userNotActive": "Gebruiker is niet actief. Neem contact op met jouw beheerder voor meer informatie." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Er is een fout opgetreden", + "multipleUsersFound": "Meerdere gebruikers gevonden", + "userNotFound": "Gebruiker niet in het systeem gevonden" + } + }, + "password": { + "verify": { + "title": "Wachtwoord", + "description": "Voer jouw wachtwoord in.", + "resetPassword": "Wachtwoord resetten", + "submit": "Verder", + "labels": { + "password": "Wachtwoord" + }, + "required": { + "password": "Dit veld is verplicht" + }, + "errors": { + "couldNotVerifyPassword": "Kon wachtwoord niet verifiëren", + "couldNotResetPassword": "Kon wachtwoord niet resetten" + }, + "info": { + "passwordResetSent": "Het wachtwoord is opnieuw ingesteld. Controleer jouw e-mail" + } + }, + "set": { + "title": "Stel Wachtwoord in", + "description": "Stel het wachtwoord voor jouw account in", + "codeSent": "Er is een nieuwe code naar uw e-mailadres verzonden.", + "noCodeReceived": "Geen code ontvangen?", + "resend": "Code opnieuw versturen", + "submit": "Verder", + "labels": { + "code": "Code", + "newPassword": "Nieuw Wachtwoord", + "confirmPassword": "Bevestig Wachtwoord" + }, + "required": { + "code": "Dit veld is verplicht", + "newPassword": "U moet een wachtwoord opgeven!", + "confirmPassword": "Dit veld is verplicht" + }, + "errors": { + "couldNotSetPassword": "Kon wachtwoord niet instellen", + "couldNotResetPassword": "Kon wachtwoord niet resetten", + "couldNotVerifyPassword": "Kon wachtwoord niet verifiëren" + } + }, + "change": { + "title": "Verander Wachtwoord", + "description": "Stel het wachtwoord voor jouw account in", + "submit": "Verder", + "labels": { + "currentPassword": "Huidig wachtwoord", + "newPassword": "Nieuw wachtwoord", + "confirmPassword": "Bevestig wachtwoord" + }, + "required": { + "currentPassword": "Je moet je huidige wachtwoord opgeven!", + "newPassword": "Je moet een nieuw wachtwoord opgeven!", + "confirmPassword": "Dit veld is verplicht" + }, + "errors": { + "currentPasswordInvalid": "Het huidige wachtwoord is onjuist.", + "couldNotChangePassword": "Kon wachtwoord niet wijzigen", + "couldNotVerifyPassword": "Kon wachtwoord niet verifiëren", + "unknownError": "Onbekende fout" + } + }, + "complexity": { + "length": "Moet minstens {minLength} tekens lang zijn.", + "hasSymbol": "Moet een symbool bevatten.", + "hasNumber": "Moet een nummer bevatten.", + "hasUppercase": "Moet een hoofdletter bevatten.", + "hasLowercase": "Moet een kleine letter bevatten.", + "equals": "Wachtwoordbevestiging komt overeen.", + "matches": "Komt overeen", + "doesNotMatch": "Komt niet overeen" + }, + "errors": { + "noHostFound": "Geen host gevonden", + "couldNotSendResetLink": "Kon link voor wachtwoordherstel niet verzenden", + "couldNotCreateSessionForUser": "Kon sessie voor gebruiker niet aanmaken", + "couldNotVerifyPassword": "Kon wachtwoord niet verifiëren", + "failedToAuthenticate": "Authenticatie mislukt. U had {failedAttempts} van {maxPasswordAttempts} wachtwoordpogingen.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Authenticatie mislukt.", + "accountLockedContactAdmin": " Neem contact op met jouw beheerder om jouw account te ontgrendelen", + "userNotFound": "Gebruiker niet in het systeem gevonden", + "initialUserNotSupported": "Initiële gebruiker wordt niet ondersteund", + "userInitialStateNotSupported": "Initiële gebruikersstatus wordt niet ondersteund", + "codeOrVerificationRequired": "U moet een code opgeven of een geldige gebruikersverificatie hebben", + "verificationRequired": "Gebruikersverificatie moet worden uitgevoerd", + "couldNotLoadSession": "Kon sessie niet laden", + "couldNotLoadAuthMethods": "Kon verificatiemethoden niet laden", + "failedPrecondition": "Voorwaarde mislukt", + "sessionNotValid": "Sessie is niet geldig", + "passwordVerificationMissing": "Wachtwoordverificatie ontbreekt.", + "passwordVerificationTooOld": "Wachtwoordverificatie is te oud. Verifieer je wachtwoord opnieuw.", + "passwordResetNotAllowed": "Wachtwoord resetten is niet toegestaan. Neem contact op met uw beheerder voor meer informatie.", + "localAuthenticationNotAllowed": "Lokale authenticatie is niet toegestaan! Neem contact op met uw beheerder voor meer informatie." + } + }, + "idp": { + "title": "Aanmelden met SSO", + "description": "Selecteer een van de volgende providers om u aan te melden", + "orSignInWith": "of meld u aan met", + "signInWithApple": "Aanmelden met Apple", + "signInWithGoogle": "Aanmelden met Google", + "signInWithAzureAD": "Aanmelden met AzureAD", + "signInWithGithub": "Aanmelden met GitHub", + "signInWithGitlab": "Aanmelden met GitLab", + "signInWithZitadel": "Aanmelden met Zitadel", + "loginError": { + "title": "Inloggen mislukt", + "description": "Er is een fout opgetreden tijdens het inloggen." + }, + "linkingError": { + "title": "Koppelen van account mislukt", + "description": "Er is een fout opgetreden tijdens het koppelen van jouw account." + }, + "completeRegister": { + "title": "Vul jouw gegevens aan", + "description": "U moet jouw registratie voltooien door jouw e-mailadres en naam op te geven." + }, + "accountNotFound": { + "title": "Account niet gevonden", + "description": "We hebben geen account gevonden dat aan jouw identiteitsprovidergegevens is gekoppeld.", + "info": "Er is geen bestaand account gevonden. Meld u aan met een bestaand account of neem contact op met jouw beheerder voor hulp.", + "backToLogin": "Terug naar inloggen" + }, + "registrationFailed": { + "title": "Registratie niet beschikbaar", + "description": "We konden het registratieproces niet voltooien.", + "info": "Kan de organisatie voor registratie niet bepalen. Neem contact op met jouw beheerder voor hulp.", + "backToLogin": "Terug naar inloggen" + }, + "processing": { + "message": "Authenticatie wordt verwerkt...", + "noRedirect": "Geen omleiding of fout van server ontvangen", + "unexpectedError": "Er is een onverwachte fout opgetreden" + }, + "errors": { + "missingParameters": "Vereiste parameters ontbreken", + "missingIdpInfo": "IDP-informatie ontbreekt", + "idpNotFound": "Identiteitsprovider niet gevonden", + "linkingNotAllowed": "Koppelen is niet toegestaan voor deze identiteitsprovider", + "linkingFailed": "Koppelen van identiteitsprovider aan account mislukt", + "autoLinkingFailed": "Automatisch koppelen van account mislukt", + "userCreationFailed": "Aanmaken van gebruikersaccount mislukt", + "orgResolutionFailed": "Kon organisatie voor registratie niet bepalen", + "sessionCreationFailed": "Kon sessie niet aanmaken of omleiding bepalen", + "unknownError": "Er is een onbekende fout opgetreden" + } + }, + "ldap": { + "title": "LDAP-inlog", + "description": "Voer jouw LDAP-inloggegevens in.", + "submit": "Verder", + "labels": { + "username": "Gebruikersnaam", + "password": "Wachtwoord" + }, + "required": { + "username": "Dit veld is verplicht", + "password": "Dit veld is verplicht" + } + }, + "mfa": { + "verify": { + "title": "Verifieer jouw identiteit", + "description": "Kies een van de volgende factoren.", + "noResults": "Er zijn geen tweede factoren beschikbaar om in te stellen." + }, + "set": { + "title": "Stel 2-factor in", + "description": "Kies een van de volgende tweede factoren.", + "skip": "Overslaan" + } + }, + "otp": { + "verify": { + "title": "Verifieer 2-Factor", + "totpDescription": "Voer de code uit jouw authenticator-app in.", + "smsDescription": "Voer de code in die u via sms heeft ontvangen.", + "emailDescription": "Voer de code in die u via e-mail heeft ontvangen.", + "noCodeReceived": "Geen code ontvangen?", + "resendCode": "Code opnieuw versturen", + "resendCodeIn": "Code opnieuw versturen ({seconds}s)", + "submit": "Verder", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dit veld is verplicht" + } + }, + "set": { + "title": "Stel 2-factor in", + "totpDescription": "Scan de QR-code met jouw authenticator-app.", + "smsDescription": "Voer jouw telefoonnummer in om een code via sms te ontvangen.", + "emailDescription": "Voer jouw e-mailadres in om een code via e-mail te ontvangen.", + "totpRegisterDescription": "Scan de QR-code of navigeer handmatig naar de URL.", + "emailAddDescription": "Gebruik een eenmalige code die naar je geverifieerde e-mailadres wordt gestuurd als tweede factor.", + "smsAddDescription": "Gebruik een eenmalige code die naar je geverifieerde telefoonnummer wordt gestuurd als tweede factor.", + "add": "Toevoegen", + "emailAdded": "Code via e-mail toegevoegd.", + "smsAdded": "Code via sms toegevoegd.", + "submit": "Verder", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dit veld is verplicht" + } + }, + "errors": { + "couldNotRequestChallenge": "Kon OTP-uitdaging niet aanvragen", + "couldNotVerifyCode": "Kon OTP-code niet verifiëren", + "couldNotGetSession": "Je sessie kon niet worden geladen. Meld je opnieuw aan.", + "invalidMethod": "Deze tweede factor wordt niet ondersteund.", + "couldNotAddEmail": "Code via e-mail kon niet worden toegevoegd.", + "couldNotAddSms": "Code via sms kon niet worden toegevoegd.", + "emailNotVerified": "Verifieer je e-mailadres voordat je codes via e-mail toevoegt.", + "phoneNotVerified": "Verifieer je telefoonnummer voordat je codes via sms toevoegt." + } + }, + "passkey": { + "verify": { + "title": "Authenticeer met een passkey", + "description": "Jouw apparaat vraagt om jouw vingerafdruk, gezicht of schermvergrendeling", + "usePassword": "Gebruik wachtwoord", + "submit": "Doorgaan", + "errors": { + "couldNotRequestChallenge": "Kon passkey-uitdaging niet aanvragen", + "couldNotVerifyPasskey": "Kon passkey niet verifiëren", + "noResponseReceived": "Passkey-verificatie mislukt - geen reactie ontvangen", + "noRedirectProvided": "Passkey-verificatie voltooid maar er werd geen omleiding geleverd", + "couldNotRetrievePasskey": "Er trad een fout op bij het ophalen van de passkey", + "verificationCancelled": "Passkey-verificatie is geannuleerd", + "verificationFailed": "Er trad een fout op tijdens de passkey-verificatie", + "couldNotFindSession": "Kon sessie niet vinden", + "couldNotUpdateSession": "Kon sessie niet bijwerken", + "userNotFound": "Gebruiker niet in het systeem gevonden", + "couldNotDetermineRedirect": "Kon omleidings-URL na passkey-verificatie niet bepalen" + } + }, + "set": { + "title": "Stel een passkey in", + "description": "Uw apparaat vraagt om jouw vingerafdruk, gezicht of schermvergrendeling", + "info": { + "description": "Een passkey is een authenticatiemethode op een apparaat zoals jouw vingerafdruk, Apple FaceID of iets dergelijks. ", + "link": "Passkey authenticatie" + }, + "skip": "Overslaan", + "submit": "Doorgaan" + } + }, + "u2f": { + "verify": { + "title": "Verifieer 2-Factor", + "description": "Verifieer jouw account met jouw apparaat." + }, + "set": { + "title": "Stel 2-factor in", + "description": "Stel een apparaat in als tweede factor.", + "submit": "Doorgaan" + } + }, + "register": { + "methods": { + "passkey": "Passkey", + "password": "Wachtwoord" + }, + "disabled": { + "title": "Registratie uitgeschakeld", + "description": "Registratie is uitgeschakeld. Neem contact op met jouw beheerder." + }, + "missingdata": { + "title": "Ontbrekende gegevens", + "description": "Geef e-mail, voornaam en achternaam op om te registreren." + }, + "title": "Registreren", + "description": "Maak jouw Zitadel-account aan.", + "noMethodAvailableWarning": "Geen authenticatiemethode beschikbaar. Neem contact op met jouw beheerder.", + "selectMethod": "Selecteer de methode waarmee u wilt verifiëren", + "agreeTo": "Om te registreren moet u akkoord gaan met de voorwaarden", + "termsOfService": "Servicevoorwaarden", + "privacyPolicy": "Privacybeleid", + "submit": "Doorgaan", + "password": { + "title": "Stel Wachtwoord in", + "description": "Stel het wachtwoord voor jouw account in", + "submit": "Doorgaan", + "labels": { + "password": "Wachtwoord", + "confirmPassword": "Bevestig Wachtwoord" + }, + "required": { + "password": "U moet een wachtwoord opgeven!", + "confirmPassword": "Dit veld is verplicht" + } + }, + "labels": { + "firstname": "Voornaam", + "lastname": "Achternaam", + "email": "E-Mail" + }, + "required": { + "firstname": "Dit veld is verplicht", + "lastname": "Dit veld is verplicht", + "email": "Dit veld is verplicht" + }, + "errors": { + "couldNotCreateUser": "Kon gebruiker niet aanmaken", + "couldNotCreateSession": "Kon sessie niet aanmaken", + "userNotFound": "Gebruiker niet in het systeem gevonden", + "couldNotLinkIDP": "Kon IDP niet aan gebruiker koppelen", + "couldNotRegisterUser": "Kon gebruiker niet registreren", + "sessionMismatch": "De registratie is in een andere browser gestart. Meld je opnieuw aan bij je identiteitsprovider." + } + }, + "invite": { + "title": "Gebruiker uitnodigen", + "description": "Geef het e-mailadres en de naam op van de gebruiker die u wilt uitnodigen.", + "info": "De gebruiker ontvangt een e-mail met verdere instructies.", + "notAllowed": "Uw instellingen staan het uitnodigen van gebruikers niet toe.", + "submit": "Doorgaan", + "success": { + "title": "Gebruiker uitgenodigd", + "description": "De e-mail is succesvol verzonden.", + "verified": "De gebruiker is uitgenodigd en heeft zijn e-mail al geverifieerd.", + "notVerifiedYet": "De gebruiker is uitgenodigd. Zij ontvangen een e-mail met verdere instructies.", + "submit": "Nog een gebruiker uitnodigen" + } + }, + "signedin": { + "title": "Welkom {user}!", + "description": "U bent aangemeld.", + "continue": "Verder", + "error": { + "title": "Fout", + "description": "Er is een fout opgetreden tijdens het aanmelden." + } + }, + "verify": { + "userIdMissing": "Geen gebruikers-ID opgegeven!", + "successTitle": "Gebruiker geverifieerd", + "successDescription": "De gebruiker is succesvol geverifieerd.", + "successContinue": "Doorgaan", + "setupAuthenticator": "Authenticator instellen", + "verify": { + "title": "Gebruiker verifiëren", + "description": "Voer de code in uit de verificatie-e-mail.", + "noCodeReceived": "Geen code ontvangen?", + "resendCode": "Code opnieuw versturen", + "codeSent": "Er is zojuist een code naar jouw e-mailadres gestuurd.", + "submit": "Doorgaan", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dit veld is verplicht" + } + }, + "errors": { + "couldNotResendEmail": "Kon e-mail niet opnieuw versturen", + "couldNotVerifyUser": "Kon gebruiker niet verifiëren", + "couldNotVerifyInvite": "Kon uitnodiging niet verifiëren", + "couldNotVerifyEmail": "Kon e-mail niet verifiëren", + "couldNotVerify": "Kon niet verifiëren", + "couldNotLoadUser": "Kon gebruiker niet laden", + "couldNotLoadAuthenticators": "Kon mogelijke authenticators niet laden", + "couldNotCreateSession": "Kon sessie niet aanmaken", + "noHostFound": "Geen host gevonden", + "userAlreadyVerified": "Gebruiker is al geverifieerd!", + "couldNotResendInvite": "Kon uitnodiging niet opnieuw versturen", + "inviteSendFailed": "Versturen van uitnodigingsmail mislukt", + "emailSendFailed": "Versturen van verificatie-e-mail mislukt", + "contextMissing": "Er is een fout opgetreden. Probeer het opnieuw." + } + }, + "authenticator": { + "title": "Kies authenticatiemethode", + "description": "Selecteer de methode waarmee u wilt verifiëren", + "noMethodsAvailable": "Geen authenticatiemethoden beschikbaar", + "allSetup": "U heeft al een authenticator ingesteld!", + "linkWithIDP": "of link met een identiteitsprovider", + "methods": { + "totp": "Authenticator-app", + "u2f": "Universele tweede factor", + "otpEmail": "Code via e-mail", + "otpSms": "Code via sms", + "passkey": "Passkeys", + "password": "Wachtwoord" + } + }, + "device": { + "usercode": { + "title": "Apparaatcode", + "description": "Voer de code in die op jouw app of apparaat wordt weergegeven.", + "submit": "Doorgaan", + "labels": { + "code": "Code" + }, + "required": { + "code": "Dit veld is verplicht" + } + }, + "request": { + "title": "{appName} wil verbinding maken", + "description": "{appName} krijgt toegang tot:", + "disclaimer": "Door op Toestaan te klikken geeft u {appName} en Zitadel toestemming om jouw informatie te gebruiken overeenkomstig hun respectieve servicevoorwaarden en privacybeleid. U kunt deze toegang op elk moment intrekken.", + "submit": "Toestaan", + "deny": "Weigeren" + }, + "scope": { + "openid": "Verifieer jouw identiteit.", + "email": "Bekijk jouw e-mailadres.", + "profile": "Bekijk jouw volledige profielinformatie.", + "offline_access": "Sta offline toegang tot jouw account toe." + } + }, + "error": { + "noUserCode": "Geen gebruikerscode opgegeven!", + "noDeviceRequest": "Geen apparaatverzoek gevonden.", + "unknownContext": "Kon de context van de gebruiker niet ophalen. Zorg ervoor dat u eerst de gebruikersnaam invoert of een loginName als zoekparameter opgeeft.", + "sessionExpired": "Uw sessie is verlopen of vereist opnieuw authenticatie. Log opnieuw in.", + "failedLoading": "Gegevens laden mislukt. Probeer het opnieuw.", + "tryagain": "Opnieuw proberen", + "couldNotContinueSession": "Kon de sessie niet voortzetten - ontbrekende gebruikersinformatie", + "couldNotClearSession": "De sessie kon niet worden beëindigd. Probeer het opnieuw." + } +} diff --git a/auth/ui/v2/apps/login/locales/pl.json b/auth/ui/v2/apps/login/locales/pl.json new file mode 100644 index 0000000..aaab196 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/pl.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Powrót", + "title": "Zaloguj się za pomocą Zitadel" + }, + "accounts": { + "title": "Konta", + "description": "Wybierz konto, którego chcesz użyć.", + "addAnother": "Dodaj kolejne konto", + "noResults": "Nie znaleziono kont", + "verified": "zweryfikowany", + "expired": "wygasł" + }, + "logout": { + "title": "Wyloguj się", + "description": "Wybierz konto, które chcesz usunąć", + "noResults": "Nie znaleziono kont", + "clear": "Usuń sesję", + "verifiedAt": "Ostatnia aktywność: {time}", + "success": { + "title": "Wylogowanie udane", + "description": "Pomyślnie się wylogowałeś." + } + }, + "loginname": { + "title": "Witamy ponownie!", + "description": "Wprowadź dane logowania.", + "register": "Zarejestruj nowego użytkownika", + "submit": "Kontynuuj", + "labels": { + "loginname": "Login", + "username": "Nazwa użytkownika", + "usernameOrPhoneNumber": "Nazwa użytkownika lub numer telefonu", + "usernameOrEmail": "Nazwa użytkownika lub e-mail" + }, + "required": { + "loginName": "To pole jest wymagane" + }, + "errors": { + "internalError": "Wystąpił błąd wewnętrzny", + "couldNotGetLoginSettings": "Nie udało się pobrać ustawień logowania", + "couldNotSearchUsers": "Nie udało się wyszukać użytkowników", + "couldNotGetDomain": "Nie udało się pobrać domeny", + "couldNotGetHost": "Nie udało się pobrać hosta", + "couldNotStartIDPFlow": "Nie udało się rozpocząć procesu IDP", + "moreThanOneUserFound": "Znaleziono więcej niż jednego użytkownika. Podaj unikalny identyfikator.", + "userNotFound": "Użytkownik nie został znaleziony w systemie", + "couldNotCreateSession": "Nie udało się utworzyć sesji dla użytkownika", + "initialUserNotSupported": "Użytkownik inicjalny nie jest obsługiwany", + "localAuthenticationNotAllowed": "Uwierzytelnianie lokalne nie jest dozwolone! Skontaktuj się z administratorem, aby uzyskać więcej informacji.", + "passkeysNotAllowed": "Klucze dostępu są niedozwolone! Skontaktuj się z administratorem, aby uzyskać więcej informacji.", + "couldNotFindIdentityProvider": "Nie udało się znaleźć dostawcy tożsamości.", + "userNotActive": "Użytkownik jest nieaktywny. Skontaktuj się z administratorem, aby uzyskać więcej informacji." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Wystąpił błąd", + "multipleUsersFound": "Znaleziono wielu użytkowników", + "userNotFound": "Użytkownik nie został znaleziony w systemie" + } + }, + "password": { + "verify": { + "title": "Hasło", + "description": "Wprowadź swoje hasło.", + "resetPassword": "Zresetuj hasło", + "submit": "Kontynuuj", + "labels": { + "password": "Hasło" + }, + "required": { + "password": "To pole jest wymagane" + }, + "errors": { + "couldNotVerifyPassword": "Nie można zweryfikować hasła", + "couldNotResetPassword": "Nie można zresetować hasła" + }, + "info": { + "passwordResetSent": "Hasło zostało zresetowane. Sprawdź swoją pocztę e-mail" + } + }, + "set": { + "title": "Ustaw hasło", + "description": "Ustaw hasło dla swojego konta", + "codeSent": "Nowy kod został wysłany na Twój adres e-mail.", + "noCodeReceived": "Nie otrzymałeś kodu?", + "resend": "Wyślij kod ponownie", + "submit": "Kontynuuj", + "labels": { + "code": "Kod", + "newPassword": "Nowe hasło", + "confirmPassword": "Potwierdź nowe hasło" + }, + "required": { + "code": "To pole jest wymagane", + "newPassword": "Musisz podać hasło!", + "confirmPassword": "To pole jest wymagane" + }, + "errors": { + "couldNotSetPassword": "Nie można ustawić hasła", + "couldNotResetPassword": "Nie można zresetować hasła", + "couldNotVerifyPassword": "Nie można zweryfikować hasła" + } + }, + "change": { + "title": "Zmień hasło", + "description": "Ustaw nowe hasło dla swojego konta", + "submit": "Kontynuuj", + "labels": { + "currentPassword": "Aktualne hasło", + "newPassword": "Nowe hasło", + "confirmPassword": "Potwierdź nowe hasło" + }, + "required": { + "currentPassword": "Musisz podać aktualne hasło!", + "newPassword": "Musisz podać nowe hasło!", + "confirmPassword": "To pole jest wymagane" + }, + "errors": { + "currentPasswordInvalid": "Aktualne hasło jest nieprawidłowe.", + "couldNotChangePassword": "Nie można zmienić hasła", + "couldNotVerifyPassword": "Nie można zweryfikować hasła", + "unknownError": "Nieznany błąd" + } + }, + "complexity": { + "length": "Musi zawierać co najmniej {minLength} znaków.", + "hasSymbol": "Musi zawierać symbol.", + "hasNumber": "Musi zawierać numer.", + "hasUppercase": "Musi zawierać dużą literę.", + "hasLowercase": "Musi zawierać małą literę.", + "equals": "Potwierdzenie hasła pasuje.", + "matches": "Pasuje", + "doesNotMatch": "Nie pasuje" + }, + "errors": { + "noHostFound": "Nie znaleziono hosta", + "couldNotSendResetLink": "Nie można wysłać linku do resetowania hasła", + "couldNotCreateSessionForUser": "Nie można utworzyć sesji dla użytkownika", + "couldNotVerifyPassword": "Nie można zweryfikować hasła", + "failedToAuthenticate": "Uwierzytelnianie nie powiodło się. Wykorzystałeś {failedAttempts} z {maxPasswordAttempts} prób wprowadzenia hasła.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Uwierzytelnianie nie powiodło się.", + "accountLockedContactAdmin": " Skontaktuj się z administratorem, aby odblokować konto", + "userNotFound": "Użytkownik nie został znaleziony w systemie", + "initialUserNotSupported": "Użytkownik początkowy nie jest obsługiwany", + "userInitialStateNotSupported": "Początkowy stan użytkownika nie jest obsługiwany", + "codeOrVerificationRequired": "Musisz podać kod lub mieć ważną weryfikację użytkownika", + "verificationRequired": "Wymagana jest weryfikacja użytkownika", + "couldNotLoadSession": "Nie można załadować sesji", + "couldNotLoadAuthMethods": "Nie można załadować metod uwierzytelniania", + "failedPrecondition": "Nie spełniono warunków wstępnych", + "sessionNotValid": "Sesja jest nieważna", + "passwordVerificationMissing": "Brak weryfikacji hasła.", + "passwordVerificationTooOld": "Weryfikacja hasła jest przestarzała. Proszę zweryfikować hasło ponownie.", + "passwordResetNotAllowed": "Resetowanie hasła jest niedozwolone. Skontaktuj się z administratorem, aby uzyskać więcej informacji.", + "localAuthenticationNotAllowed": "Uwierzytelnianie lokalne nie jest dozwolone! Skontaktuj się z administratorem, aby uzyskać więcej informacji." + } + }, + "idp": { + "title": "Zaloguj się za pomocą SSO", + "description": "Wybierz jednego z poniższych dostawców, aby się zalogować", + "orSignInWith": "lub zaloguj się przez", + "signInWithApple": "Zaloguj się przez Apple", + "signInWithGoogle": "Zaloguj się przez Google", + "signInWithAzureAD": "Zaloguj się przez AzureAD", + "signInWithGithub": "Zaloguj się przez GitHub", + "signInWithGitlab": "Zaloguj się przez GitLab", + "signInWithZitadel": "Zaloguj się przez Zitadel", + "loginError": { + "title": "Logowanie nieudane", + "description": "Wystąpił błąd podczas próby logowania." + }, + "linkingError": { + "title": "Powiązanie konta nie powiodło się", + "description": "Wystąpił błąd podczas próby powiązania konta." + }, + "completeRegister": { + "title": "Ukończ rejestrację", + "description": "Ukończ rejestrację swojego konta." + }, + "accountNotFound": { + "title": "Nie znaleziono konta", + "description": "Nie mogliśmy znaleźć konta powiązanego z danymi logowania Twojego dostawcy tożsamości.", + "info": "Nie znaleziono istniejącego konta. Zaloguj się przy użyciu istniejącego konta lub skontaktuj się z administratorem w celu uzyskania pomocy.", + "backToLogin": "Powrót do logowania" + }, + "registrationFailed": { + "title": "Rejestracja niedostępna", + "description": "Nie mogliśmy ukończyć procesu rejestracji.", + "info": "Nie można określić organizacji do rejestracji. Skontaktuj się z administratorem w celu uzyskania pomocy.", + "backToLogin": "Powrót do logowania" + }, + "processing": { + "message": "Przetwarzanie uwierzytelniania...", + "noRedirect": "Nie otrzymano przekierowania ani błędu z serwera", + "unexpectedError": "Wystąpił nieoczekiwany błąd" + }, + "errors": { + "missingParameters": "Brakuje wymaganych parametrów", + "missingIdpInfo": "Brak informacji IDP", + "idpNotFound": "Dostawca tożsamości nie znaleziony", + "linkingNotAllowed": "Łączenie nie jest dozwolone dla tego dostawcy tożsamości", + "linkingFailed": "Nie udało się połączyć dostawcy tożsamości z kontem", + "autoLinkingFailed": "Nie udało się automatycznie połączyć konta", + "userCreationFailed": "Nie udało się utworzyć konta użytkownika", + "orgResolutionFailed": "Nie można określić organizacji do rejestracji", + "sessionCreationFailed": "Nie można utworzyć sesji lub określić przekierowania", + "unknownError": "Wystąpił nieznany błąd" + } + }, + "ldap": { + "title": "Zaloguj się przez LDAP", + "description": "Wprowadź swoje dane logowania LDAP.", + "submit": "Kontynuuj", + "labels": { + "username": "Nazwa użytkownika", + "password": "Hasło" + }, + "required": { + "username": "To pole jest wymagane", + "password": "To pole jest wymagane" + } + }, + "mfa": { + "verify": { + "title": "Zweryfikuj swoją tożsamość", + "description": "Wybierz jeden z poniższych sposobów weryfikacji.", + "noResults": "Nie znaleziono dostępnych metod uwierzytelniania dwuskładnikowego." + }, + "set": { + "title": "Skonfiguruj uwierzytelnianie dwuskładnikowe", + "description": "Wybierz jedną z poniższych metod drugiego czynnika.", + "skip": "Pomiń" + } + }, + "otp": { + "verify": { + "title": "Zweryfikuj uwierzytelnianie dwuskładnikowe", + "totpDescription": "Wprowadź kod z aplikacji uwierzytelniającej.", + "smsDescription": "Wprowadź kod otrzymany SMS-em.", + "emailDescription": "Wprowadź kod otrzymany e-mailem.", + "noCodeReceived": "Nie otrzymałeś kodu?", + "resendCode": "Wyślij kod ponownie", + "resendCodeIn": "Wyślij kod ponownie ({seconds}s)", + "submit": "Kontynuuj", + "labels": { + "code": "Kod" + }, + "required": { + "code": "To pole jest wymagane" + } + }, + "set": { + "title": "Skonfiguruj uwierzytelnianie dwuskładnikowe", + "totpDescription": "Zeskanuj kod QR za pomocą aplikacji uwierzytelniającej.", + "smsDescription": "Wprowadź swój numer telefonu, aby otrzymać kod SMS-em.", + "emailDescription": "Wprowadź swój adres e-mail, aby otrzymać kod e-mailem.", + "totpRegisterDescription": "Zeskanuj kod QR lub otwórz adres URL ręcznie.", + "emailAddDescription": "Używaj jednorazowego kodu wysyłanego na zweryfikowany adres e-mail jako drugiego składnika.", + "smsAddDescription": "Używaj jednorazowego kodu wysyłanego na zweryfikowany numer telefonu jako drugiego składnika.", + "add": "Dodaj", + "emailAdded": "Dodano kod przez e-mail.", + "smsAdded": "Dodano kod przez SMS.", + "submit": "Kontynuuj", + "labels": { + "code": "Kod" + }, + "required": { + "code": "To pole jest wymagane" + } + }, + "errors": { + "couldNotRequestChallenge": "Nie można zażądać wyzwania OTP", + "couldNotVerifyCode": "Nie można zweryfikować kodu OTP", + "couldNotGetSession": "Nie udało się wczytać sesji. Zaloguj się ponownie.", + "invalidMethod": "Ten drugi składnik nie jest obsługiwany.", + "couldNotAddEmail": "Nie udało się dodać kodu przez e-mail.", + "couldNotAddSms": "Nie udało się dodać kodu przez SMS.", + "emailNotVerified": "Zweryfikuj adres e-mail przed dodaniem kodów przez e-mail.", + "phoneNotVerified": "Zweryfikuj numer telefonu przed dodaniem kodów przez SMS." + } + }, + "passkey": { + "verify": { + "title": "Uwierzytelnij się za pomocą klucza dostępu", + "description": "Twoje urządzenie poprosi o użycie odcisku palca, rozpoznawania twarzy lub blokady ekranu.", + "usePassword": "Użyj hasła", + "submit": "Kontynuuj", + "errors": { + "couldNotRequestChallenge": "Nie można zażądać wyzwania klucza dostępu", + "couldNotVerifyPasskey": "Nie można zweryfikować klucza dostępu", + "noResponseReceived": "Weryfikacja klucza dostępu nie powiodła się - nie otrzymano odpowiedzi", + "noRedirectProvided": "Weryfikacja klucza dostępu zakończona, ale nie podano przekierowania", + "couldNotRetrievePasskey": "Wystąpił błąd podczas pobierania klucza dostępu", + "verificationCancelled": "Weryfikacja klucza dostępu została anulowana", + "verificationFailed": "Wystąpił błąd podczas weryfikacji klucza dostępu", + "couldNotFindSession": "Nie można znaleźć sesji", + "couldNotUpdateSession": "Nie można zaktualizować sesji", + "userNotFound": "Użytkownik nie znaleziony w systemie", + "couldNotDetermineRedirect": "Nie można określić adresu URL przekierowania po weryfikacji klucza dostępu" + } + }, + "set": { + "title": "Skonfiguruj klucz dostępu", + "description": "Twoje urządzenie poprosi o użycie odcisku palca, rozpoznawania twarzy lub blokady ekranu.", + "info": { + "description": "Klucz dostępu to metoda uwierzytelniania na urządzeniu, wykorzystująca np. odcisk palca, Apple FaceID lub podobne rozwiązania.", + "link": "Uwierzytelnianie kluczem dostępu" + }, + "skip": "Pomiń", + "submit": "Kontynuuj" + } + }, + "u2f": { + "verify": { + "title": "Zweryfikuj uwierzytelnianie dwuskładnikowe", + "description": "Zweryfikuj swoje konto za pomocą urządzenia." + }, + "set": { + "title": "Skonfiguruj uwierzytelnianie dwuskładnikowe", + "description": "Skonfiguruj urządzenie jako dodatkowy czynnik uwierzytelniania.", + "submit": "Kontynuuj" + } + }, + "register": { + "methods": { + "passkey": "Klucz dostępu", + "password": "Hasło" + }, + "disabled": { + "title": "Rejestracja wyłączona", + "description": "Rejestracja jest wyłączona. Skontaktuj się z administratorem." + }, + "missingdata": { + "title": "Brak danych", + "description": "Podaj e-mail, imię i nazwisko, aby się zarejestrować." + }, + "title": "Rejestracja", + "description": "Utwórz konto Zitadel.", + "noMethodAvailableWarning": "Brak dostępnych metod uwierzytelniania. Skontaktuj się z administratorem.", + "selectMethod": "Wybierz metodę uwierzytelniania, której chcesz użyć", + "agreeTo": "Aby się zarejestrować, musisz zaakceptować warunki korzystania", + "termsOfService": "Regulamin", + "privacyPolicy": "Polityka prywatności", + "submit": "Kontynuuj", + "password": { + "title": "Ustaw hasło", + "description": "Ustaw hasło dla swojego konta", + "submit": "Kontynuuj", + "labels": { + "password": "Hasło", + "confirmPassword": "Potwierdź hasło" + }, + "required": { + "password": "Musisz podać hasło!", + "confirmPassword": "To pole jest wymagane" + } + }, + "labels": { + "firstname": "Imię", + "lastname": "Nazwisko", + "email": "E-mail" + }, + "required": { + "firstname": "To pole jest wymagane", + "lastname": "To pole jest wymagane", + "email": "To pole jest wymagane" + }, + "errors": { + "couldNotCreateUser": "Nie udało się utworzyć użytkownika", + "couldNotCreateSession": "Nie udało się utworzyć sesji", + "userNotFound": "Nie znaleziono użytkownika w systemie", + "couldNotLinkIDP": "Nie udało się powiązać IDP z użytkownikiem", + "couldNotRegisterUser": "Nie udało się zarejestrować użytkownika", + "sessionMismatch": "Rejestracja została rozpoczęta w innej przeglądarce. Zaloguj się ponownie u swojego dostawcy tożsamości." + } + }, + "invite": { + "title": "Zaproś użytkownika", + "description": "Podaj adres e-mail oraz imię i nazwisko użytkownika, którego chcesz zaprosić.", + "info": "Użytkownik otrzyma e-mail z dalszymi instrukcjami.", + "notAllowed": "Twoje ustawienia nie pozwalają na zapraszanie użytkowników.", + "submit": "Kontynuuj", + "success": { + "title": "Użytkownik zaproszony", + "description": "E-mail został pomyślnie wysłany.", + "verified": "Użytkownik został zaproszony i już zweryfikował swój e-mail.", + "notVerifiedYet": "Użytkownik został zaproszony. Otrzyma e-mail z dalszymi instrukcjami.", + "submit": "Zaproś kolejnego użytkownika" + } + }, + "signedin": { + "title": "Witaj {user}!", + "description": "Jesteś zalogowany.", + "continue": "Kontynuuj", + "error": { + "title": "Błąd", + "description": "Nie można załadować danych. Sprawdź połączenie z internetem lub spróbuj ponownie później." + } + }, + "verify": { + "userIdMissing": "Nie podano identyfikatora użytkownika!", + "successTitle": "Weryfikacja zakończona", + "successDescription": "Użytkownik został pomyślnie zweryfikowany.", + "successContinue": "Kontynuuj", + "setupAuthenticator": "Skonfiguruj uwierzytelnianie", + "verify": { + "title": "Zweryfikuj użytkownika", + "description": "Wprowadź kod z wiadomości weryfikacyjnej.", + "noCodeReceived": "Nie otrzymałeś kodu?", + "resendCode": "Wyślij kod ponownie", + "codeSent": "Kod został właśnie wysłany na twój adres e-mail.", + "submit": "Kontynuuj", + "labels": { + "code": "Kod" + }, + "required": { + "code": "To pole jest wymagane" + } + }, + "errors": { + "couldNotResendEmail": "Nie udało się ponownie wysłać wiadomości e-mail", + "couldNotVerifyUser": "Nie udało się zweryfikować użytkownika", + "couldNotVerifyInvite": "Nie udało się zweryfikować zaproszenia", + "couldNotVerifyEmail": "Nie udało się zweryfikować adresu e-mail", + "couldNotVerify": "Nie udało się zweryfikować", + "couldNotLoadUser": "Nie udało się załadować użytkownika", + "couldNotLoadAuthenticators": "Nie udało się wczytać dostępnych metod uwierzytelniania", + "couldNotCreateSession": "Nie udało się utworzyć sesji", + "noHostFound": "Nie znaleziono hosta", + "userAlreadyVerified": "Użytkownik jest już zweryfikowany!", + "couldNotResendInvite": "Nie udało się ponownie wysłać zaproszenia", + "inviteSendFailed": "Nie udało się wysłać wiadomości e-mail z zaproszeniem", + "emailSendFailed": "Nie udało się wysłać wiadomości e-mail weryfikacyjnej", + "contextMissing": "Wystąpił błąd. Spróbuj ponownie." + } + }, + "authenticator": { + "title": "Wybierz metodę uwierzytelniania", + "description": "Wybierz metodę, której chcesz użyć do uwierzytelnienia.", + "noMethodsAvailable": "Brak dostępnych metod uwierzytelniania", + "allSetup": "Już skonfigurowałeś metodę uwierzytelniania!", + "linkWithIDP": "lub połącz z dostawcą tożsamości", + "methods": { + "totp": "Aplikacja uwierzytelniająca", + "u2f": "Uniwersalny drugi składnik", + "otpEmail": "Kod przez e-mail", + "otpSms": "Kod przez SMS", + "passkey": "Klucz dostępu", + "password": "Hasło" + } + }, + "device": { + "usercode": { + "title": "Kod urządzenia", + "description": "Wprowadź kod.", + "submit": "Kontynuuj", + "labels": { + "code": "Kod" + }, + "required": { + "code": "To pole jest wymagane" + } + }, + "request": { + "title": "{appName} chce się połączyć:", + "description": "{appName} będzie miało dostęp do:", + "disclaimer": "Klikając Zezwól, pozwalasz tej aplikacji i Zitadel na korzystanie z Twoich informacji zgodnie z ich odpowiednimi warunkami użytkowania i politykami prywatności. Możesz cofnąć ten dostęp w dowolnym momencie.", + "submit": "Zezwól", + "deny": "Odmów" + }, + "scope": { + "openid": "Zweryfikuj swoją tożsamość.", + "email": "Uzyskaj dostęp do swojego adresu e-mail.", + "profile": "Uzyskaj dostęp do pełnych informacji o swoim profilu.", + "offline_access": "Zezwól na dostęp offline do swojego konta." + } + }, + "error": { + "noUserCode": "Nie podano kodu użytkownika!", + "noDeviceRequest": "Nie znaleziono żądania urządzenia.", + "unknownContext": "Nie udało się pobrać kontekstu użytkownika. Upewnij się, że najpierw wprowadziłeś nazwę użytkownika lub podałeś login jako parametr wyszukiwania.", + "sessionExpired": "Twoja sesja wygasła lub wymaga ponownego uwierzytelnienia. Zaloguj się ponownie.", + "failedLoading": "Nie udało się załadować danych. Spróbuj ponownie.", + "tryagain": "Spróbuj ponownie", + "couldNotContinueSession": "Nie udało się kontynuować sesji - brak informacji o użytkowniku", + "couldNotClearSession": "Nie udało się zakończyć sesji. Spróbuj ponownie." + } +} diff --git a/auth/ui/v2/apps/login/locales/pt.json b/auth/ui/v2/apps/login/locales/pt.json new file mode 100644 index 0000000..900535b --- /dev/null +++ b/auth/ui/v2/apps/login/locales/pt.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Voltar", + "title": "Entrar com Zitadel" + }, + "accounts": { + "title": "Contas", + "description": "Selecione a conta que deseja utilizar.", + "addAnother": "Adicionar outra conta", + "noResults": "Nenhuma conta encontrada", + "verified": "verificado", + "expired": "expirado" + }, + "logout": { + "title": "Sair", + "description": "Clique em uma conta para encerrar a sessão", + "noResults": "Nenhuma conta encontrada", + "clear": "Encerrar Sessão", + "verifiedAt": "Último acesso: {time}", + "success": { + "title": "Sessão encerrada", + "description": "Você saiu com sucesso." + } + }, + "loginname": { + "title": "Bem-vindo de volta!", + "description": "Insira seus dados de acesso.", + "register": "Cadastrar novo usuário", + "submit": "Continuar", + "labels": { + "loginname": "Nome de usuário", + "username": "Usuário", + "usernameOrPhoneNumber": "Usuário ou número de telefone", + "usernameOrEmail": "Usuário ou e-mail" + }, + "required": { + "loginName": "Este campo é obrigatório" + }, + "errors": { + "internalError": "Ocorreu um erro interno", + "couldNotGetLoginSettings": "Não foi possível obter as configurações de login", + "couldNotSearchUsers": "Não foi possível pesquisar usuários", + "couldNotGetDomain": "Não foi possível obter o domínio", + "couldNotGetHost": "Não foi possível obter o host", + "couldNotStartIDPFlow": "Não foi possível iniciar o fluxo do provedor de identidade", + "moreThanOneUserFound": "Mais de um usuário encontrado. Forneça um identificador único.", + "userNotFound": "Usuário não encontrado no sistema", + "couldNotCreateSession": "Não foi possível criar sessão para o usuário", + "initialUserNotSupported": "Usuário inicial não suportado", + "localAuthenticationNotAllowed": "A autenticação local não é permitida! Entre em contato com o administrador para mais informações.", + "passkeysNotAllowed": "Chaves de acesso não são permitidas! Entre em contato com o administrador para mais informações.", + "couldNotFindIdentityProvider": "Não foi possível encontrar o provedor de identidade.", + "userNotActive": "O usuário não está ativo. Entre em contato com o administrador para mais informações." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Ocorreu um erro", + "multipleUsersFound": "Múltiplos usuários encontrados", + "userNotFound": "Usuário não encontrado no sistema" + } + }, + "password": { + "verify": { + "title": "Senha", + "description": "Insira sua senha.", + "resetPassword": "Redefinir Senha", + "submit": "Continuar", + "labels": { + "password": "Senha" + }, + "required": { + "password": "Este campo é obrigatório" + }, + "errors": { + "couldNotVerifyPassword": "Não foi possível verificar a senha", + "couldNotResetPassword": "Não foi possível redefinir a senha" + }, + "info": { + "passwordResetSent": "A senha foi redefinida. Por favor, verifique seu e-mail" + } + }, + "set": { + "title": "Definir Senha", + "description": "Defina a senha da sua conta", + "codeSent": "Um código foi enviado para o seu e-mail.", + "noCodeReceived": "Não recebeu o código?", + "resend": "Reenviar código", + "submit": "Continuar", + "labels": { + "code": "Código", + "newPassword": "Nova Senha", + "confirmPassword": "Confirmar Senha" + }, + "required": { + "code": "Este campo é obrigatório", + "newPassword": "Você precisa fornecer uma senha!", + "confirmPassword": "Este campo é obrigatório" + }, + "errors": { + "couldNotSetPassword": "Não foi possível definir a senha", + "couldNotResetPassword": "Não foi possível redefinir a senha", + "couldNotVerifyPassword": "Não foi possível verificar a senha" + } + }, + "change": { + "title": "Alterar Senha", + "description": "Defina a senha da sua conta", + "submit": "Continuar", + "labels": { + "currentPassword": "Senha Atual", + "newPassword": "Nova Senha", + "confirmPassword": "Confirmar Senha" + }, + "required": { + "currentPassword": "Você precisa fornecer sua senha atual!", + "newPassword": "Você precisa fornecer uma nova senha!", + "confirmPassword": "Este campo é obrigatório" + }, + "errors": { + "currentPasswordInvalid": "A senha atual está incorreta.", + "couldNotChangePassword": "Não foi possível alterar a senha", + "couldNotVerifyPassword": "Não foi possível verificar a senha", + "unknownError": "Erro desconhecido" + } + }, + "complexity": { + "length": "Deve ter pelo menos {minLength} caracteres.", + "hasSymbol": "Deve incluir um símbolo.", + "hasNumber": "Deve incluir um número.", + "hasUppercase": "Deve incluir uma letra maiúscula.", + "hasLowercase": "Deve incluir uma letra minúscula.", + "equals": "A confirmação de senha coincide.", + "matches": "Coincide", + "doesNotMatch": "Não coincide" + }, + "errors": { + "noHostFound": "Nenhum host encontrado", + "couldNotSendResetLink": "Não foi possível enviar o link de redefinição de senha", + "couldNotCreateSessionForUser": "Não foi possível criar sessão para o usuário", + "couldNotVerifyPassword": "Não foi possível verificar a senha", + "failedToAuthenticate": "Falha na autenticação. Você usou {failedAttempts} de {maxPasswordAttempts} tentativas de senha.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Falha na autenticação.", + "accountLockedContactAdmin": " Entre em contato com o administrador para desbloquear sua conta", + "userNotFound": "Usuário não encontrado no sistema", + "initialUserNotSupported": "Usuário inicial não suportado", + "userInitialStateNotSupported": "Estado inicial do usuário não é suportado", + "codeOrVerificationRequired": "Você precisa fornecer um código ou ter uma verificação de usuário válida", + "verificationRequired": "A verificação do usuário precisa ser realizada", + "couldNotLoadSession": "Não foi possível carregar a sessão", + "couldNotLoadAuthMethods": "Não foi possível carregar os métodos de autenticação", + "failedPrecondition": "Pré-condição falhou", + "sessionNotValid": "A sessão não é válida", + "passwordVerificationMissing": "A verificação de senha está ausente.", + "passwordVerificationTooOld": "A verificação de senha expirou. Por favor, verifique sua senha novamente.", + "passwordResetNotAllowed": "A redefinição de senha não é permitida. Entre em contato com o administrador para mais informações.", + "localAuthenticationNotAllowed": "A autenticação local não é permitida! Entre em contato com o administrador para mais informações." + } + }, + "idp": { + "title": "Entrar com SSO", + "description": "Selecione um dos provedores abaixo para entrar", + "orSignInWith": "ou entre com", + "signInWithApple": "Entrar com Apple", + "signInWithGoogle": "Entrar com Google", + "signInWithAzureAD": "Entrar com AzureAD", + "signInWithGithub": "Entrar com GitHub", + "signInWithGitlab": "Entrar com GitLab", + "signInWithZitadel": "Entrar com Zitadel", + "loginError": { + "title": "Falha no login", + "description": "Ocorreu um erro ao tentar fazer login." + }, + "linkingError": { + "title": "Falha na vinculação de conta", + "description": "Ocorreu um erro ao tentar vincular sua conta." + }, + "completeRegister": { + "title": "Complete seus dados", + "description": "Você precisa completar seu cadastro fornecendo seu endereço de e-mail e nome." + }, + "accountNotFound": { + "title": "Conta Não Encontrada", + "description": "Não encontramos uma conta associada às suas credenciais do provedor de identidade.", + "info": "Nenhuma conta existente foi encontrada. Por favor, entre com uma conta existente ou entre em contato com o administrador para assistência.", + "backToLogin": "Voltar ao Login" + }, + "registrationFailed": { + "title": "Cadastro Indisponível", + "description": "Não foi possível completar o processo de cadastro.", + "info": "Não foi possível determinar a organização para o cadastro. Por favor, entre em contato com o administrador para assistência.", + "backToLogin": "Voltar ao Login" + }, + "processing": { + "message": "Processando autenticação...", + "noRedirect": "Nenhum redirecionamento ou erro retornado pelo servidor", + "unexpectedError": "Ocorreu um erro inesperado" + }, + "errors": { + "missingParameters": "Parâmetros obrigatórios ausentes", + "missingIdpInfo": "Informações do provedor de identidade ausentes", + "idpNotFound": "Provedor de identidade não encontrado", + "linkingNotAllowed": "A vinculação não é permitida para este provedor de identidade", + "linkingFailed": "Falha ao vincular o provedor de identidade à conta", + "autoLinkingFailed": "Falha ao vincular automaticamente a conta", + "userCreationFailed": "Falha ao criar conta de usuário", + "orgResolutionFailed": "Não foi possível determinar a organização para o cadastro", + "sessionCreationFailed": "Não foi possível criar sessão ou determinar redirecionamento", + "unknownError": "Ocorreu um erro desconhecido" + } + }, + "ldap": { + "title": "Login LDAP", + "description": "Insira suas credenciais LDAP.", + "submit": "Continuar", + "labels": { + "username": "Usuário", + "password": "Senha" + }, + "required": { + "username": "Este campo é obrigatório", + "password": "Este campo é obrigatório" + } + }, + "mfa": { + "verify": { + "title": "Verifique sua identidade", + "description": "Escolha um dos fatores abaixo.", + "noResults": "Nenhum segundo fator disponível para configurar." + }, + "set": { + "title": "Configurar 2º Fator", + "description": "Escolha um dos seguintes segundos fatores.", + "skip": "Pular" + } + }, + "otp": { + "verify": { + "title": "Verificar 2º Fator", + "totpDescription": "Insira o código do seu aplicativo autenticador.", + "smsDescription": "Insira o código que você recebeu via SMS.", + "emailDescription": "Insira o código que você recebeu por e-mail.", + "noCodeReceived": "Não recebeu o código?", + "resendCode": "Reenviar código", + "resendCodeIn": "Reenviar código ({seconds}s)", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo é obrigatório" + } + }, + "set": { + "title": "Configurar 2º Fator", + "totpDescription": "Escaneie o QR Code com seu aplicativo autenticador.", + "smsDescription": "Insira seu número de telefone para receber um código via SMS.", + "emailDescription": "Insira seu endereço de e-mail para receber um código por e-mail.", + "totpRegisterDescription": "Escaneie o QR Code ou acesse a URL manualmente.", + "emailAddDescription": "Use um código de uso único enviado para o seu endereço de e-mail verificado como segundo fator.", + "smsAddDescription": "Use um código de uso único enviado para o seu número de telefone verificado como segundo fator.", + "add": "Adicionar", + "emailAdded": "Código por e-mail adicionado.", + "smsAdded": "Código por SMS adicionado.", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo é obrigatório" + } + }, + "errors": { + "couldNotRequestChallenge": "Não foi possível solicitar o desafio OTP", + "couldNotVerifyCode": "Não foi possível verificar o código OTP", + "couldNotGetSession": "Não foi possível carregar sua sessão. Entre novamente.", + "invalidMethod": "Este segundo fator não é suportado.", + "couldNotAddEmail": "Não foi possível adicionar o código por e-mail.", + "couldNotAddSms": "Não foi possível adicionar o código por SMS.", + "emailNotVerified": "Verifique seu endereço de e-mail antes de adicionar códigos por e-mail.", + "phoneNotVerified": "Verifique seu número de telefone antes de adicionar códigos por SMS." + } + }, + "passkey": { + "verify": { + "title": "Autenticar com chave de acesso", + "description": "Seu dispositivo solicitará sua impressão digital, rosto ou bloqueio de tela", + "usePassword": "Usar senha", + "submit": "Continuar", + "errors": { + "couldNotRequestChallenge": "Não foi possível solicitar desafio da chave de acesso", + "couldNotVerifyPasskey": "Não foi possível verificar a chave de acesso", + "noResponseReceived": "Falha na verificação da chave de acesso - nenhuma resposta recebida", + "noRedirectProvided": "Verificação da chave de acesso concluída, mas nenhum redirecionamento foi fornecido", + "couldNotRetrievePasskey": "Ocorreu um erro ao recuperar a chave de acesso", + "verificationCancelled": "A verificação da chave de acesso foi cancelada", + "verificationFailed": "Ocorreu um erro durante a verificação da chave de acesso", + "couldNotFindSession": "Não foi possível encontrar a sessão", + "couldNotUpdateSession": "Não foi possível atualizar a sessão", + "userNotFound": "Usuário não encontrado no sistema", + "couldNotDetermineRedirect": "Não foi possível determinar a URL de redirecionamento após verificação da chave de acesso" + } + }, + "set": { + "title": "Configurar chave de acesso", + "description": "Seu dispositivo solicitará sua impressão digital, rosto ou bloqueio de tela", + "info": { + "description": "Uma chave de acesso é um método de autenticação no seu dispositivo, como impressão digital, Apple FaceID ou similar. ", + "link": "Autenticação por Chave de Acesso" + }, + "skip": "Pular", + "submit": "Continuar" + } + }, + "u2f": { + "verify": { + "title": "Verificar 2º Fator", + "description": "Verifique sua conta com seu dispositivo." + }, + "set": { + "title": "Configurar 2º Fator", + "description": "Configure um dispositivo como segundo fator.", + "submit": "Continuar" + } + }, + "register": { + "methods": { + "passkey": "Chave de Acesso", + "password": "Senha" + }, + "disabled": { + "title": "Cadastro desativado", + "description": "O cadastro está desativado. Por favor, entre em contato com o administrador." + }, + "missingdata": { + "title": "Dados incompletos", + "description": "Forneça e-mail, nome e sobrenome para se cadastrar." + }, + "title": "Cadastrar", + "description": "Crie sua conta Zitadel.", + "noMethodAvailableWarning": "Nenhum método de autenticação disponível. Por favor, entre em contato com o administrador.", + "selectMethod": "Selecione o método de autenticação desejado", + "agreeTo": "Para se cadastrar, você deve concordar com os termos e condições", + "termsOfService": "Termos de Serviço", + "privacyPolicy": "Política de Privacidade", + "submit": "Continuar", + "password": { + "title": "Definir Senha", + "description": "Defina a senha da sua conta", + "submit": "Continuar", + "labels": { + "password": "Senha", + "confirmPassword": "Confirmar Senha" + }, + "required": { + "password": "Você precisa fornecer uma senha!", + "confirmPassword": "Este campo é obrigatório" + } + }, + "labels": { + "firstname": "Nome", + "lastname": "Sobrenome", + "email": "E-mail" + }, + "required": { + "firstname": "Este campo é obrigatório", + "lastname": "Este campo é obrigatório", + "email": "Este campo é obrigatório" + }, + "errors": { + "couldNotCreateUser": "Não foi possível criar o usuário", + "couldNotCreateSession": "Não foi possível criar a sessão", + "userNotFound": "Usuário não encontrado no sistema", + "couldNotLinkIDP": "Não foi possível vincular o provedor de identidade ao usuário", + "couldNotRegisterUser": "Não foi possível cadastrar o usuário", + "sessionMismatch": "O cadastro foi iniciado em outro navegador. Entre novamente com seu provedor de identidade." + } + }, + "invite": { + "title": "Convidar Usuário", + "description": "Forneça o endereço de e-mail e o nome do usuário que deseja convidar.", + "info": "O usuário receberá um e-mail com instruções.", + "notAllowed": "Suas configurações não permitem convidar usuários.", + "submit": "Continuar", + "success": { + "title": "Usuário convidado", + "description": "O e-mail foi enviado com sucesso.", + "verified": "O usuário foi convidado e já verificou seu e-mail.", + "notVerifiedYet": "O usuário foi convidado. Ele receberá um e-mail com instruções.", + "submit": "Convidar outro usuário" + } + }, + "signedin": { + "title": "Bem-vindo, {user}!", + "description": "Você está conectado.", + "continue": "Continuar", + "error": { + "title": "Erro", + "description": "Ocorreu um erro ao tentar entrar." + } + }, + "verify": { + "userIdMissing": "Nenhum ID de usuário fornecido!", + "successTitle": "Usuário verificado", + "successDescription": "O usuário foi verificado com sucesso.", + "successContinue": "Continuar", + "setupAuthenticator": "Configurar autenticador", + "verify": { + "title": "Verificar usuário", + "description": "Insira o código fornecido no e-mail de verificação.", + "noCodeReceived": "Não recebeu o código?", + "resendCode": "Reenviar código", + "codeSent": "Um código foi enviado para o seu endereço de e-mail.", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo é obrigatório" + } + }, + "errors": { + "couldNotResendEmail": "Não foi possível reenviar o e-mail", + "couldNotVerifyUser": "Não foi possível verificar o usuário", + "couldNotVerifyInvite": "Não foi possível verificar o convite", + "couldNotVerifyEmail": "Não foi possível verificar o e-mail", + "couldNotVerify": "Não foi possível verificar", + "couldNotLoadUser": "Não foi possível carregar o usuário", + "couldNotLoadAuthenticators": "Não foi possível carregar os autenticadores disponíveis", + "couldNotCreateSession": "Não foi possível criar a sessão", + "noHostFound": "Nenhum host encontrado", + "userAlreadyVerified": "O usuário já foi verificado!", + "couldNotResendInvite": "Não foi possível reenviar o convite", + "inviteSendFailed": "Falha ao enviar e-mail de convite", + "emailSendFailed": "Falha ao enviar e-mail de verificação", + "contextMissing": "Ocorreu um erro. Por favor, tente novamente." + } + }, + "authenticator": { + "title": "Escolha o método de autenticação", + "description": "Selecione o método de autenticação desejado", + "noMethodsAvailable": "Nenhum método de autenticação disponível", + "allSetup": "Você já configurou um autenticador!", + "linkWithIDP": "ou vincule com um Provedor de Identidade", + "methods": { + "totp": "Aplicativo autenticador", + "u2f": "Segundo fator universal", + "otpEmail": "Código via e-mail", + "otpSms": "Código via SMS", + "passkey": "Chave de Acesso", + "password": "Senha" + } + }, + "device": { + "usercode": { + "title": "Código do dispositivo", + "description": "Insira o código exibido no seu aplicativo ou dispositivo.", + "submit": "Continuar", + "labels": { + "code": "Código" + }, + "required": { + "code": "Este campo é obrigatório" + } + }, + "request": { + "title": "{appName} deseja se conectar", + "description": "{appName} terá acesso a:", + "disclaimer": "Ao clicar em Permitir, você autoriza {appName} e Zitadel a usar suas informações de acordo com seus respectivos termos de serviço e políticas de privacidade. Você pode revogar este acesso a qualquer momento.", + "submit": "Permitir", + "deny": "Negar" + }, + "scope": { + "openid": "Verificar sua identidade.", + "email": "Ver seu endereço de e-mail.", + "profile": "Ver suas informações completas de perfil.", + "offline_access": "Permitir acesso offline à sua conta." + } + }, + "error": { + "noUserCode": "Nenhum código de usuário fornecido!", + "noDeviceRequest": "Nenhuma solicitação de dispositivo encontrada.", + "unknownContext": "Não foi possível obter o contexto do usuário. Certifique-se de inserir o nome de usuário primeiro ou forneça um loginName como parâmetro de busca.", + "sessionExpired": "Sua sessão expirou ou requer uma nova autenticação. Por favor, faça login novamente.", + "failedLoading": "Falha ao carregar dados. Por favor, tente novamente.", + "tryagain": "Tentar Novamente", + "couldNotContinueSession": "Não foi possível continuar a sessão — informações do usuário ausentes", + "couldNotClearSession": "Não foi possível terminar a sessão. Tente novamente." + } +} diff --git a/auth/ui/v2/apps/login/locales/ru.json b/auth/ui/v2/apps/login/locales/ru.json new file mode 100644 index 0000000..ea2271e --- /dev/null +++ b/auth/ui/v2/apps/login/locales/ru.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Назад", + "title": "Войти с Zitadel" + }, + "accounts": { + "title": "Аккаунты", + "description": "Выберите аккаунт, который хотите использовать.", + "addAnother": "Добавить другой аккаунт", + "noResults": "Аккаунты не найдены", + "verified": "проверенный", + "expired": "истёк" + }, + "logout": { + "title": "Выход", + "description": "Выберите аккаунт, который хотите удалить", + "noResults": "Аккаунты не найдены", + "clear": "Удалить сессию", + "verifiedAt": "Последняя активность: {time}", + "success": { + "title": "Выход выполнен успешно", + "description": "Вы успешно вышли из системы." + } + }, + "loginname": { + "title": "С возвращением!", + "description": "Введите свои данные для входа.", + "register": "Зарегистрировать нового пользователя", + "submit": "Продолжить", + "labels": { + "loginname": "Логин", + "username": "Имя пользователя", + "usernameOrPhoneNumber": "Имя пользователя или номер телефона", + "usernameOrEmail": "Имя пользователя или электронная почта" + }, + "required": { + "loginName": "Это поле обязательно для заполнения" + }, + "errors": { + "internalError": "Произошла внутренняя ошибка", + "couldNotGetLoginSettings": "Не удалось получить настройки входа", + "couldNotSearchUsers": "Не удалось выполнить поиск пользователей", + "couldNotGetDomain": "Не удалось получить домен", + "couldNotGetHost": "Не удалось получить хост", + "couldNotStartIDPFlow": "Не удалось запустить поток IDP", + "moreThanOneUserFound": "Найдено более одного пользователя. Укажите уникальный идентификатор.", + "userNotFound": "Пользователь не найден в системе", + "couldNotCreateSession": "Не удалось создать сессию для пользователя", + "initialUserNotSupported": "Начальный пользователь не поддерживается", + "localAuthenticationNotAllowed": "Локальная аутентификация запрещена! Обратитесь к администратору за дополнительной информацией.", + "passkeysNotAllowed": "Ключи доступа не разрешены! Обратитесь к администратору за дополнительной информацией.", + "couldNotFindIdentityProvider": "Не удалось найти поставщика удостоверений.", + "userNotActive": "Пользователь неактивен. Обратитесь к администратору за дополнительной информацией." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Произошла ошибка", + "multipleUsersFound": "Найдено несколько пользователей", + "userNotFound": "Пользователь не найден в системе" + } + }, + "password": { + "verify": { + "title": "Пароль", + "description": "Введите ваш пароль.", + "resetPassword": "Сбросить пароль", + "submit": "Продолжить", + "labels": { + "password": "Пароль" + }, + "required": { + "password": "Это поле обязательно для заполнения" + }, + "errors": { + "couldNotVerifyPassword": "Не удалось проверить пароль", + "couldNotResetPassword": "Не удалось сбросить пароль" + }, + "info": { + "passwordResetSent": "Пароль был сброшен. Пожалуйста, проверьте свою электронную почту" + } + }, + "set": { + "title": "Установить пароль", + "description": "Установите пароль для вашего аккаунта", + "codeSent": "Новый код был отправлен на ваш адрес электронной почты.", + "noCodeReceived": "Не получили код?", + "resend": "Отправить код повторно", + "submit": "Продолжить", + "labels": { + "code": "Код", + "newPassword": "Новый пароль", + "confirmPassword": "Подтвердите пароль" + }, + "required": { + "code": "Это поле обязательно для заполнения", + "newPassword": "Вы должны указать пароль!", + "confirmPassword": "Это поле обязательно для заполнения" + }, + "errors": { + "couldNotSetPassword": "Не удалось установить пароль", + "couldNotResetPassword": "Не удалось сбросить пароль", + "couldNotVerifyPassword": "Не удалось проверить пароль" + } + }, + "change": { + "title": "Изменить пароль", + "description": "Установите пароль для вашего аккаунта", + "submit": "Продолжить", + "labels": { + "currentPassword": "Текущий пароль", + "newPassword": "Новый пароль", + "confirmPassword": "Подтвердите пароль" + }, + "required": { + "currentPassword": "Вы должны указать текущий пароль!", + "newPassword": "Вы должны указать новый пароль!", + "confirmPassword": "Это поле обязательно для заполнения" + }, + "errors": { + "currentPasswordInvalid": "Текущий пароль неверен.", + "couldNotChangePassword": "Не удалось изменить пароль", + "couldNotVerifyPassword": "Не удалось проверить пароль", + "unknownError": "Неизвестная ошибка" + } + }, + "complexity": { + "length": "Минимум {minLength} символов.", + "hasSymbol": "Должен содержать специальный символ.", + "hasNumber": "Должен содержать цифру.", + "hasUppercase": "Должен содержать заглавную букву.", + "hasLowercase": "Должен содержать строчную букву.", + "equals": "Пароли должны совпадать.", + "matches": "Совпадает", + "doesNotMatch": "Не совпадает" + }, + "errors": { + "noHostFound": "Хост не найден", + "couldNotSendResetLink": "Не удалось отправить ссылку для сброса пароля", + "couldNotCreateSessionForUser": "Не удалось создать сессию для пользователя", + "couldNotVerifyPassword": "Не удалось проверить пароль", + "failedToAuthenticate": "Не удалось пройти аутентификацию. У вас было {failedAttempts} из {maxPasswordAttempts} попыток ввода пароля.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Не удалось пройти аутентификацию.", + "accountLockedContactAdmin": " Свяжитесь с администратором, чтобы разблокировать вашу учетную запись", + "userNotFound": "Пользователь не найден в системе", + "initialUserNotSupported": "Первичный пользователь не поддерживается", + "userInitialStateNotSupported": "Начальное состояние пользователя не поддерживается", + "codeOrVerificationRequired": "Вы должны предоставить код или иметь действительную проверку пользователя", + "verificationRequired": "Необходимо выполнить проверку пользователя", + "couldNotLoadSession": "Не удалось загрузить сессию", + "couldNotLoadAuthMethods": "Не удалось загрузить методы аутентификации", + "failedPrecondition": "Нарушено предварительное условие", + "sessionNotValid": "Сессия недействительна", + "passwordVerificationMissing": "Отсутствует проверка пароля.", + "passwordVerificationTooOld": "Проверка пароля устарела. Пожалуйста, подтвердите пароль еще раз.", + "passwordResetNotAllowed": "Сброс пароля запрещен. Обратитесь к администратору за дополнительной информацией.", + "localAuthenticationNotAllowed": "Локальная аутентификация запрещена! Обратитесь к администратору за дополнительной информацией." + } + }, + "idp": { + "title": "Войти через SSO", + "description": "Выберите одного из провайдеров для входа", + "orSignInWith": "или войти через", + "signInWithApple": "Войти через Apple", + "signInWithGoogle": "Войти через Google", + "signInWithAzureAD": "Войти через AzureAD", + "signInWithGithub": "Войти через GitHub", + "signInWithGitlab": "Войти через GitLab", + "signInWithZitadel": "Войти через Zitadel", + "loginError": { + "title": "Ошибка входа", + "description": "Произошла ошибка при попытке входа." + }, + "linkingError": { + "title": "Ошибка привязки аккаунта", + "description": "Произошла ошибка при попытке привязать аккаунт." + }, + "completeRegister": { + "title": "Завершите регистрацию", + "description": "Завершите регистрацию вашего аккаунта." + }, + "accountNotFound": { + "title": "Аккаунт не найден", + "description": "Мы не смогли найти аккаунт, связанный с учетными данными вашего провайдера идентификации.", + "info": "Существующий аккаунт не найден. Пожалуйста, войдите с существующим аккаунтом или обратитесь к администратору за помощью.", + "backToLogin": "Вернуться к входу" + }, + "registrationFailed": { + "title": "Регистрация недоступна", + "description": "Мы не смогли завершить процесс регистрации.", + "info": "Не удалось определить организацию для регистрации. Пожалуйста, обратитесь к администратору за помощью.", + "backToLogin": "Вернуться к входу" + }, + "processing": { + "message": "Обработка аутентификации...", + "noRedirect": "Не получено перенаправления или ошибки от сервера", + "unexpectedError": "Произошла неожиданная ошибка" + }, + "errors": { + "missingParameters": "Отсутствуют обязательные параметры", + "missingIdpInfo": "Отсутствует информация IDP", + "idpNotFound": "Провайдер идентификации не найден", + "linkingNotAllowed": "Связывание не разрешено для этого провайдера идентификации", + "linkingFailed": "Не удалось связать провайдера идентификации с учетной записью", + "autoLinkingFailed": "Не удалось автоматически связать учетную запись", + "userCreationFailed": "Не удалось создать учетную запись пользователя", + "orgResolutionFailed": "Не удалось определить организацию для регистрации", + "sessionCreationFailed": "Не удалось создать сеанс или определить перенаправление", + "unknownError": "Произошла неизвестная ошибка" + } + }, + "ldap": { + "title": "Войти через LDAP", + "description": "Введите ваши учетные данные LDAP.", + "submit": "Продолжить", + "labels": { + "username": "Имя пользователя", + "password": "Пароль" + }, + "required": { + "username": "Это поле обязательно для заполнения", + "password": "Это поле обязательно для заполнения" + } + }, + "mfa": { + "verify": { + "title": "Подтвердите вашу личность", + "description": "Выберите один из следующих факторов.", + "noResults": "Нет доступных методов двухфакторной аутентификации" + }, + "set": { + "title": "Настройка двухфакторной аутентификации", + "description": "Выберите один из следующих методов.", + "skip": "Пропустить" + } + }, + "otp": { + "verify": { + "title": "Подтверждение 2FA", + "totpDescription": "Введите код из приложения-аутентификатора.", + "smsDescription": "Введите код, полученный по SMS.", + "emailDescription": "Введите код, полученный по email.", + "noCodeReceived": "Не получили код?", + "resendCode": "Отправить код повторно", + "resendCodeIn": "Отправить код повторно ({seconds} с)", + "submit": "Продолжить", + "labels": { + "code": "Код" + }, + "required": { + "code": "Это поле обязательно для заполнения" + } + }, + "set": { + "title": "Настройка двухфакторной аутентификации", + "totpDescription": "Отсканируйте QR-код в приложении-аутентификаторе.", + "smsDescription": "Введите номер телефона для получения кода по SMS.", + "emailDescription": "Введите email для получения кода.", + "totpRegisterDescription": "Отсканируйте QR-код или перейдите по ссылке вручную.", + "emailAddDescription": "Используйте одноразовый код, отправляемый на ваш подтверждённый адрес электронной почты, в качестве второго фактора.", + "smsAddDescription": "Используйте одноразовый код, отправляемый на ваш подтверждённый номер телефона, в качестве второго фактора.", + "add": "Добавить", + "emailAdded": "Код по электронной почте добавлен.", + "smsAdded": "Код по SMS добавлен.", + "submit": "Продолжить", + "labels": { + "code": "Код" + }, + "required": { + "code": "Это поле обязательно для заполнения" + } + }, + "errors": { + "couldNotRequestChallenge": "Не удалось запросить OTP-челлендж", + "couldNotVerifyCode": "Не удалось проверить OTP-код", + "couldNotGetSession": "Не удалось загрузить сессию. Войдите снова.", + "invalidMethod": "Этот второй фактор не поддерживается.", + "couldNotAddEmail": "Не удалось добавить код по электронной почте.", + "couldNotAddSms": "Не удалось добавить код по SMS.", + "emailNotVerified": "Подтвердите адрес электронной почты, прежде чем добавлять коды по электронной почте.", + "phoneNotVerified": "Подтвердите номер телефона, прежде чем добавлять коды по SMS." + } + }, + "passkey": { + "verify": { + "title": "Аутентификация с помощью пасскей", + "description": "Устройство запросит отпечаток пальца, лицо или экранный замок", + "usePassword": "Использовать пароль", + "submit": "Продолжить", + "errors": { + "couldNotRequestChallenge": "Не удалось запросить вызов пасскей", + "couldNotVerifyPasskey": "Не удалось проверить пасскей", + "noResponseReceived": "Проверка пасскей не удалась - ответ не получен", + "noRedirectProvided": "Проверка пасскей завершена, но перенаправление не предоставлено", + "couldNotRetrievePasskey": "Произошла ошибка при получении пасскей", + "verificationCancelled": "Проверка пасскей была отменена", + "verificationFailed": "Произошла ошибка при проверке пасскей", + "couldNotFindSession": "Не удалось найти сеанс", + "couldNotUpdateSession": "Не удалось обновить сеанс", + "userNotFound": "Пользователь не найден в системе", + "couldNotDetermineRedirect": "Не удалось определить URL перенаправления после проверки пасскей" + } + }, + "set": { + "title": "Настройка пасскей", + "description": "Устройство запросит отпечаток пальца, лицо или экранный замок", + "info": { + "description": "Пасскей — метод аутентификации через устройство (отпечаток пальца, Apple FaceID и аналоги).", + "link": "Аутентификация по Пасскею" + }, + "skip": "Пропустить", + "submit": "Продолжить" + } + }, + "u2f": { + "verify": { + "title": "Подтверждение 2FA", + "description": "Подтвердите аккаунт с помощью устройства." + }, + "set": { + "title": "Настройка двухфакторной аутентификации", + "description": "Настройте устройство как второй фактор.", + "submit": "Продолжить" + } + }, + "register": { + "methods": { + "passkey": "Пасскей", + "password": "Пароль" + }, + "disabled": { + "title": "Регистрация отключена", + "description": "Регистрация недоступна. Обратитесь к администратору." + }, + "missingdata": { + "title": "Недостаточно данных", + "description": "Укажите email, имя и фамилию для регистрации." + }, + "title": "Регистрация", + "description": "Создайте свой аккаунт Zitadel.", + "noMethodAvailableWarning": "Нет доступных методов аутентификации. Обратитесь к администратору.", + "selectMethod": "Выберите метод аутентификации", + "agreeTo": "Для регистрации необходимо принять условия:", + "termsOfService": "Условия использования", + "privacyPolicy": "Политика конфиденциальности", + "submit": "Продолжить", + "password": { + "title": "Установить пароль", + "description": "Установите пароль для вашего аккаунта", + "submit": "Продолжить", + "labels": { + "password": "Пароль", + "confirmPassword": "Подтвердите пароль" + }, + "required": { + "password": "Вы должны указать пароль!", + "confirmPassword": "Это поле обязательно для заполнения" + } + }, + "labels": { + "firstname": "Имя", + "lastname": "Фамилия", + "email": "Электронная почта" + }, + "required": { + "firstname": "Это поле обязательно для заполнения", + "lastname": "Это поле обязательно для заполнения", + "email": "Это поле обязательно для заполнения" + }, + "errors": { + "couldNotCreateUser": "Не удалось создать пользователя", + "couldNotCreateSession": "Не удалось создать сессию", + "userNotFound": "Пользователь не найден в системе", + "couldNotLinkIDP": "Не удалось привязать IDP к пользователю", + "couldNotRegisterUser": "Не удалось зарегистрировать пользователя", + "sessionMismatch": "Регистрация была начата в другом браузере. Войдите снова через вашего поставщика удостоверений." + } + }, + "invite": { + "title": "Пригласить пользователя", + "description": "Укажите email и имя пользователя для приглашения.", + "info": "Пользователь получит email с инструкциями.", + "notAllowed": "Ваши настройки не позволяют приглашать пользователей.", + "submit": "Продолжить", + "success": { + "title": "Пользователь приглашён", + "description": "Письмо успешно отправлено.", + "verified": "Пользователь приглашён и уже подтвердил email.", + "notVerifiedYet": "Пользователь приглашён. Он получит email с инструкциями.", + "submit": "Пригласить другого пользователя" + } + }, + "signedin": { + "title": "Добро пожаловать, {user}!", + "description": "Вы вошли в систему.", + "continue": "Продолжить", + "error": { + "title": "Ошибка", + "description": "Не удалось войти в систему. Проверьте свои данные и попробуйте снова." + } + }, + "verify": { + "userIdMissing": "Не указан userId!", + "successTitle": "Пользователь подтверждён", + "successDescription": "Пользователь успешно подтверждён.", + "successContinue": "Продолжить", + "setupAuthenticator": "Настроить аутентификатор", + "verify": { + "title": "Подтверждение пользователя", + "description": "Введите код из письма подтверждения.", + "noCodeReceived": "Не получили код?", + "resendCode": "Отправить код повторно", + "codeSent": "Код отправлен на ваш email.", + "submit": "Продолжить", + "labels": { + "code": "Код" + }, + "required": { + "code": "Это поле обязательно для заполнения" + } + }, + "errors": { + "couldNotResendEmail": "Не удалось повторно отправить электронное письмо", + "couldNotVerifyUser": "Не удалось подтвердить пользователя", + "couldNotVerifyInvite": "Не удалось подтвердить приглашение", + "couldNotVerifyEmail": "Не удалось подтвердить электронную почту", + "couldNotVerify": "Не удалось подтвердить", + "couldNotLoadUser": "Не удалось загрузить пользователя", + "couldNotLoadAuthenticators": "Не удалось загрузить доступные средства аутентификации", + "couldNotCreateSession": "Не удалось создать сеанс", + "noHostFound": "Хост не найден", + "userAlreadyVerified": "Пользователь уже подтверждён!", + "couldNotResendInvite": "Не удалось повторно отправить приглашение", + "inviteSendFailed": "Не удалось отправить письмо с приглашением", + "emailSendFailed": "Не удалось отправить письмо с подтверждением", + "contextMissing": "Произошла ошибка. Пожалуйста, попробуйте еще раз." + } + }, + "authenticator": { + "title": "Выбор метода аутентификации", + "description": "Выберите предпочитаемый метод аутентификации", + "noMethodsAvailable": "Нет доступных методов аутентификации", + "allSetup": "Аутентификатор уже настроен!", + "linkWithIDP": "или привязать через Identity Provider", + "methods": { + "totp": "Приложение-аутентификатор", + "u2f": "Универсальный второй фактор", + "otpEmail": "Код по email", + "otpSms": "Код по SMS", + "passkey": "Пасскей", + "password": "Пароль" + } + }, + "device": { + "usercode": { + "title": "Код устройства", + "description": "Введите код.", + "submit": "Продолжить", + "labels": { + "code": "Код" + }, + "required": { + "code": "Это поле обязательно для заполнения" + } + }, + "request": { + "title": "{appName} хочет подключиться:", + "description": "{appName} получит доступ к:", + "disclaimer": "Нажимая «Разрешить», вы разрешаете этому приложению и Zitadel использовать вашу информацию в соответствии с их условиями использования и политиками конфиденциальности. Вы можете отозвать этот доступ в любое время.", + "submit": "Разрешить", + "deny": "Запретить" + }, + "scope": { + "openid": "Проверка вашей личности.", + "email": "Доступ к вашему адресу электронной почты.", + "profile": "Доступ к полной информации вашего профиля.", + "offline_access": "Разрешить офлайн-доступ к вашему аккаунту." + } + }, + "error": { + "noUserCode": "Не указан код пользователя!", + "noDeviceRequest": "Не найдена ни одна заявка на устройство.", + "unknownContext": "Не удалось получить контекст пользователя. Укажите имя пользователя или loginName в параметрах поиска.", + "sessionExpired": "Ваша сессия истекла или требует повторной аутентификации. Войдите снова.", + "failedLoading": "Ошибка загрузки данных. Попробуйте ещё раз.", + "tryagain": "Попробовать снова", + "couldNotContinueSession": "Не удалось продолжить сеанс - отсутствует информация о пользователе", + "couldNotClearSession": "Не удалось завершить сеанс. Пожалуйста, попробуйте ещё раз." + } +} diff --git a/auth/ui/v2/apps/login/locales/tr.json b/auth/ui/v2/apps/login/locales/tr.json new file mode 100644 index 0000000..48dbce7 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/tr.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Geri", + "title": "Zitadel ile Giriş" + }, + "accounts": { + "title": "Hesaplar", + "description": "Kullanmak istediğiniz hesabı seçin.", + "addAnother": "Başka hesap ekle", + "noResults": "Hesap bulunamadı", + "verified": "doğrulandı", + "expired": "süresi doldu" + }, + "logout": { + "title": "Çıkış", + "description": "Oturumu sonlandırmak için bir hesaba tıklayın", + "noResults": "Hesap bulunamadı", + "clear": "Oturumu Sonlandır", + "verifiedAt": "Son aktif: {time}", + "success": { + "title": "Çıkış başarılı", + "description": "Başarıyla çıkış yaptınız." + } + }, + "loginname": { + "title": "Tekrar hoş geldiniz!", + "description": "Giriş bilgilerinizi girin.", + "register": "Yeni kullanıcı kaydet", + "submit": "Devam", + "labels": { + "loginname": "Kullanıcı adı", + "username": "Kullanıcı adı", + "usernameOrPhoneNumber": "Kullanıcı adı veya telefon numarası", + "usernameOrEmail": "Kullanıcı adı veya e-posta" + }, + "required": { + "loginName": "Bu alan zorunludur" + }, + "errors": { + "internalError": "Bir iç hata oluştu", + "couldNotGetLoginSettings": "Giriş ayarları alınamadı", + "couldNotSearchUsers": "Kullanıcılar aranamadı", + "couldNotGetDomain": "Alan adı alınamadı", + "couldNotGetHost": "Host alınamadı", + "couldNotStartIDPFlow": "IDP akışı başlatılamadı", + "moreThanOneUserFound": "Birden fazla kullanıcı bulundu. Benzersiz bir tanımlayıcı sağlayın.", + "userNotFound": "Kullanıcı sistemde bulunamadı", + "couldNotCreateSession": "Kullanıcı için oturum oluşturulamadı", + "initialUserNotSupported": "İlk kullanıcı desteklenmiyor", + "localAuthenticationNotAllowed": "Yerel kimlik doğrulamasına izin verilmiyor! Daha fazla bilgi için yöneticinize başvurun.", + "passkeysNotAllowed": "Passkey'ler izin verilmiyor! Daha fazla bilgi için yöneticinizle iletişime geçin.", + "couldNotFindIdentityProvider": "Kimlik sağlayıcı bulunamadı.", + "userNotActive": "Kullanıcı aktif değil. Daha fazla bilgi için yöneticinizle iletişime geçin." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Bir hata oluştu", + "multipleUsersFound": "Birden fazla kullanıcı bulundu", + "userNotFound": "Kullanıcı sistemde bulunamadı" + } + }, + "password": { + "verify": { + "title": "Şifre", + "description": "Şifrenizi girin.", + "resetPassword": "Şifreyi Sıfırla", + "submit": "Devam", + "labels": { + "password": "Şifre" + }, + "required": { + "password": "Bu alan zorunludur" + }, + "errors": { + "couldNotVerifyPassword": "Şifre doğrulanamadı", + "couldNotResetPassword": "Şifre sıfırlanamadı" + }, + "info": { + "passwordResetSent": "Şifre sıfırlandı. Lütfen e-postanızı kontrol edin" + } + }, + "set": { + "title": "Şifre Belirle", + "description": "Hesabınız için şifre belirleyin", + "codeSent": "E-posta adresinize yeni bir kod gönderildi.", + "noCodeReceived": "Kod almadınız mı?", + "resend": "Kodu tekrar gönder", + "submit": "Devam", + "labels": { + "code": "Kod", + "newPassword": "Yeni Şifre", + "confirmPassword": "Şifreyi Onayla" + }, + "required": { + "code": "Bu alan zorunludur", + "newPassword": "Bir şifre sağlamalısınız!", + "confirmPassword": "Bu alan zorunludur" + }, + "errors": { + "couldNotSetPassword": "Şifre belirlenemedi", + "couldNotResetPassword": "Şifre sıfırlanamadı", + "couldNotVerifyPassword": "Şifre doğrulanamadı" + } + }, + "change": { + "title": "Şifre Değiştir", + "description": "Hesabınız için şifre belirleyin", + "submit": "Devam", + "labels": { + "currentPassword": "Mevcut Şifre", + "newPassword": "Yeni Şifre", + "confirmPassword": "Şifreyi Onayla" + }, + "required": { + "currentPassword": "Mevcut şifrenizi girmelisiniz!", + "newPassword": "Yeni bir şifre sağlamalısınız!", + "confirmPassword": "Bu alan zorunludur" + }, + "errors": { + "currentPasswordInvalid": "Mevcut şifre yanlış.", + "couldNotChangePassword": "Şifre değiştirilemedi", + "couldNotVerifyPassword": "Şifre doğrulanamadı", + "unknownError": "Bilinmeyen hata" + } + }, + "complexity": { + "length": "En az {minLength} karakter uzunluğunda olmalıdır.", + "hasSymbol": "Bir sembol içermelidir.", + "hasNumber": "Bir sayı içermelidir.", + "hasUppercase": "Bir büyük harf içermelidir.", + "hasLowercase": "Bir küçük harf içermelidir.", + "equals": "Şifre onayı eşleşti.", + "matches": "Eşleşiyor", + "doesNotMatch": "Eşleşmiyor" + }, + "errors": { + "noHostFound": "Host bulunamadı", + "couldNotSendResetLink": "Şifre Sıfırlama Bağlantısı gönderilemedi", + "couldNotCreateSessionForUser": "Kullanıcı için oturum oluşturulamadı", + "couldNotVerifyPassword": "Şifre doğrulanamadı", + "failedToAuthenticate": "Kimlik doğrulama başarısız. {maxPasswordAttempts} denemeden {failedAttempts} tanesini kullandınız.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Kimlik doğrulama başarısız.", + "accountLockedContactAdmin": " Hesabınızın kilidini açmak için yöneticinizle iletişime geçin", + "userNotFound": "Kullanıcı sistemde bulunamadı", + "initialUserNotSupported": "İlk kullanıcı desteklenmiyor", + "userInitialStateNotSupported": "Kullanıcı İlk Durumu desteklenmiyor", + "codeOrVerificationRequired": "Bir kod sağlamalı veya geçerli bir Kullanıcı Doğrulama Kontrolüne sahip olmalısınız", + "verificationRequired": "Kullanıcı Doğrulama Kontrolü yapılmalıdır", + "couldNotLoadSession": "Oturum yüklenemedi", + "couldNotLoadAuthMethods": "Kimlik doğrulama yöntemleri yüklenemedi", + "failedPrecondition": "Ön koşul başarısız", + "sessionNotValid": "Oturum geçerli değil", + "passwordVerificationMissing": "Şifre doğrulaması eksik.", + "passwordVerificationTooOld": "Şifre doğrulaması çok eski. Lütfen şifrenizi tekrar doğrulayın.", + "passwordResetNotAllowed": "Şifre sıfırlamaya izin verilmiyor. Daha fazla bilgi için yöneticinizle iletişime geçin.", + "localAuthenticationNotAllowed": "Yerel kimlik doğrulamasına izin verilmiyor! Daha fazla bilgi için yöneticinize başvurun." + } + }, + "idp": { + "title": "SSO ile Giriş", + "description": "Giriş yapmak için aşağıdaki sağlayıcılardan birini seçin", + "orSignInWith": "veya şununla giriş yapın", + "signInWithApple": "Apple ile Giriş", + "signInWithGoogle": "Google ile Giriş", + "signInWithAzureAD": "AzureAD ile Giriş", + "signInWithGithub": "GitHub ile Giriş", + "signInWithGitlab": "GitLab ile Giriş", + "signInWithZitadel": "Zitadel ile Giriş", + "loginError": { + "title": "Giriş başarısız", + "description": "Giriş yapılmaya çalışılırken bir hata oluştu." + }, + "linkingError": { + "title": "Hesap bağlama başarısız", + "description": "Hesabınız bağlanmaya çalışılırken bir hata oluştu." + }, + "completeRegister": { + "title": "Bilgilerinizi tamamlayın", + "description": "E-posta adresinizi ve adınızı sağlayarak kaydınızı tamamlamalısınız." + }, + "accountNotFound": { + "title": "Hesap Bulunamadı", + "description": "Kimlik sağlayıcı bilgilerinizle ilişkili bir hesap bulamadık.", + "info": "Mevcut bir hesap bulunamadı. Lütfen mevcut bir hesapla giriş yapın veya yardım için yöneticinizle iletişime geçin.", + "backToLogin": "Girişe Dön" + }, + "registrationFailed": { + "title": "Kayıt Kullanılamıyor", + "description": "Kayıt işlemini tamamlayamadık.", + "info": "Kayıt için organizasyon belirlenemedi. Lütfen yardım için yöneticinizle iletişime geçin.", + "backToLogin": "Girişe Dön" + }, + "processing": { + "message": "Kimlik doğrulama işleniyor...", + "noRedirect": "Sunucudan yönlendirme veya hata dönmedi", + "unexpectedError": "Beklenmeyen bir hata oluştu" + }, + "errors": { + "missingParameters": "Eksik gerekli parametreler", + "missingIdpInfo": "IDP bilgisi eksik", + "idpNotFound": "Kimlik sağlayıcı bulunamadı", + "linkingNotAllowed": "Bu kimlik sağlayıcı için bağlantıya izin verilmiyor", + "linkingFailed": "Kimlik sağlayıcı hesaba bağlanamadı", + "autoLinkingFailed": "Hesap otomatik olarak bağlanamadı", + "userCreationFailed": "Kullanıcı hesabı oluşturulamadı", + "orgResolutionFailed": "Kayıt için organizasyon belirlenemedi", + "sessionCreationFailed": "Oturum oluşturulamadı veya yönlendirme belirlenemedi", + "unknownError": "Bilinmeyen bir hata oluştu" + } + }, + "ldap": { + "title": "LDAP Girişi", + "description": "LDAP bilgilerinizi girin.", + "submit": "Devam", + "labels": { + "username": "Kullanıcı adı", + "password": "Şifre" + }, + "required": { + "username": "Bu alan zorunludur", + "password": "Bu alan zorunludur" + } + }, + "mfa": { + "verify": { + "title": "Kimliğinizi doğrulayın", + "description": "Aşağıdaki faktörlerden birini seçin.", + "noResults": "Kurulum için ikinci faktör mevcut değil." + }, + "set": { + "title": "2 Faktörlü Doğrulama Kur", + "description": "Aşağıdaki ikinci faktörlerden birini seçin.", + "skip": "Atla" + } + }, + "otp": { + "verify": { + "title": "2 Faktörlü Doğrulama", + "totpDescription": "Kimlik doğrulama uygulamanızdaki kodu girin.", + "smsDescription": "SMS ile aldığınız kodu girin.", + "emailDescription": "E-posta ile aldığınız kodu girin.", + "noCodeReceived": "Kod almadınız mı?", + "resendCode": "Kodu tekrar gönder", + "resendCodeIn": "Kodu tekrar gönder ({seconds} sn)", + "submit": "Devam", + "labels": { + "code": "Kod" + }, + "required": { + "code": "Bu alan zorunludur" + } + }, + "set": { + "title": "2 Faktörlü Doğrulama Kur", + "totpDescription": "QR kodunu kimlik doğrulama uygulamanızla tarayın.", + "smsDescription": "SMS ile kod almak için telefon numaranızı girin.", + "emailDescription": "E-posta ile kod almak için e-posta adresinizi girin.", + "totpRegisterDescription": "QR Kodunu tarayın veya URL'ye manuel olarak gidin.", + "emailAddDescription": "Doğrulanmış e-posta adresinize gönderilen tek kullanımlık kodu ikinci faktör olarak kullanın.", + "smsAddDescription": "Doğrulanmış telefon numaranıza gönderilen tek kullanımlık kodu ikinci faktör olarak kullanın.", + "add": "Ekle", + "emailAdded": "E-posta ile kod eklendi.", + "smsAdded": "SMS ile kod eklendi.", + "submit": "Devam", + "labels": { + "code": "Kod" + }, + "required": { + "code": "Bu alan zorunludur" + } + }, + "errors": { + "couldNotRequestChallenge": "OTP meydan okuması istenemedi", + "couldNotVerifyCode": "OTP kodu doğrulanamadı", + "couldNotGetSession": "Oturumunuz yüklenemedi. Lütfen yeniden oturum açın.", + "invalidMethod": "Bu ikinci faktör desteklenmiyor.", + "couldNotAddEmail": "E-posta ile kod eklenemedi.", + "couldNotAddSms": "SMS ile kod eklenemedi.", + "emailNotVerified": "E-posta ile kod eklemeden önce e-posta adresinizi doğrulayın.", + "phoneNotVerified": "SMS ile kod eklemeden önce telefon numaranızı doğrulayın." + } + }, + "passkey": { + "verify": { + "title": "Passkey ile kimlik doğrulama", + "description": "Cihazınız parmak izinizi, yüzünüzü veya ekran kilidinizi isteyecektir", + "usePassword": "Şifre kullan", + "submit": "Devam", + "errors": { + "couldNotRequestChallenge": "Passkey meydan okuması istenemedi", + "couldNotVerifyPasskey": "Passkey doğrulanamadı", + "noResponseReceived": "Passkey doğrulaması başarısız - yanıt alınamadı", + "noRedirectProvided": "Passkey doğrulaması tamamlandı ancak yönlendirme sağlanmadı", + "couldNotRetrievePasskey": "Passkey alınırken bir hata oluştu", + "verificationCancelled": "Passkey doğrulaması iptal edildi", + "verificationFailed": "Passkey doğrulaması sırasında bir hata oluştu", + "couldNotFindSession": "Oturum bulunamadı", + "couldNotUpdateSession": "Oturum güncellenemedi", + "userNotFound": "Kullanıcı sistemde bulunamadı", + "couldNotDetermineRedirect": "Passkey doğrulamasından sonra yönlendirme URL'si belirlenemedi" + } + }, + "set": { + "title": "Passkey kur", + "description": "Cihazınız parmak izinizi, yüzünüzü veya ekran kilidinizi isteyecektir", + "info": { + "description": "Passkey, parmak izi, Apple FaceID veya benzeri gibi bir cihazdaki kimlik doğrulama yöntemidir. ", + "link": "Passkey ile Kimlik Doğrulama" + }, + "skip": "Atla", + "submit": "Devam" + } + }, + "u2f": { + "verify": { + "title": "2 Faktörlü Doğrulama", + "description": "Hesabınızı cihazınızla doğrulayın." + }, + "set": { + "title": "2 Faktörlü Doğrulama Kur", + "description": "İkinci faktör olarak bir cihaz kurun.", + "submit": "Devam" + } + }, + "register": { + "methods": { + "passkey": "Passkey", + "password": "Şifre" + }, + "disabled": { + "title": "Kayıt devre dışı", + "description": "Kayıt devre dışı. Lütfen yöneticinizle iletişime geçin." + }, + "missingdata": { + "title": "Eksik veri", + "description": "Kayıt olmak için e-posta, ad ve soyadı sağlayın." + }, + "title": "Kayıt", + "description": "Zitadel hesabınızı oluşturun.", + "noMethodAvailableWarning": "Kullanılabilir kimlik doğrulama yöntemi yok. Lütfen yöneticinizle iletişime geçin.", + "selectMethod": "Kimlik doğrulaması yapmak istediğiniz yöntemi seçin", + "agreeTo": "Kayıt olmak için şartları ve koşulları kabul etmelisiniz", + "termsOfService": "Hizmet Şartları", + "privacyPolicy": "Gizlilik Politikası", + "submit": "Devam", + "password": { + "title": "Şifre Belirle", + "description": "Hesabınız için şifre belirleyin", + "submit": "Devam", + "labels": { + "password": "Şifre", + "confirmPassword": "Şifreyi Onayla" + }, + "required": { + "password": "Bir şifre sağlamalısınız!", + "confirmPassword": "Bu alan zorunludur" + } + }, + "labels": { + "firstname": "Ad", + "lastname": "Soyad", + "email": "E-posta" + }, + "required": { + "firstname": "Bu alan zorunludur", + "lastname": "Bu alan zorunludur", + "email": "Bu alan zorunludur" + }, + "errors": { + "couldNotCreateUser": "Kullanıcı oluşturulamadı", + "couldNotCreateSession": "Oturum oluşturulamadı", + "userNotFound": "Kullanıcı sistemde bulunamadı", + "couldNotLinkIDP": "IDP kullanıcıya bağlanamadı", + "couldNotRegisterUser": "Kullanıcı kayıt edilemedi", + "sessionMismatch": "Kayıt başka bir tarayıcıda başlatıldı. Lütfen kimlik sağlayıcınızla yeniden oturum açın." + } + }, + "invite": { + "title": "Kullanıcı Davet Et", + "description": "Davet etmek istediğiniz kullanıcının e-posta adresini ve adını sağlayın.", + "info": "Kullanıcı, daha fazla talimat içeren bir e-posta alacaktır.", + "notAllowed": "Ayarlarınız kullanıcı davet etmenize izin vermiyor.", + "submit": "Devam", + "success": { + "title": "Kullanıcı davet edildi", + "description": "E-posta başarıyla gönderildi.", + "verified": "Kullanıcı davet edildi ve e-postasını zaten doğruladı.", + "notVerifiedYet": "Kullanıcı davet edildi. Daha fazla talimat içeren bir e-posta alacaktır.", + "submit": "Başka kullanıcı davet et" + } + }, + "signedin": { + "title": "Hoş geldin {user}!", + "description": "Giriş yaptınız.", + "continue": "Devam", + "error": { + "title": "Hata", + "description": "Giriş yapılmaya çalışılırken bir hata oluştu." + } + }, + "verify": { + "userIdMissing": "userId sağlanmadı!", + "successTitle": "Kullanıcı doğrulandı", + "successDescription": "Kullanıcı başarıyla doğrulandı.", + "successContinue": "Devam", + "setupAuthenticator": "Kimlik doğrulayıcı kur", + "verify": { + "title": "Kullanıcıyı doğrula", + "description": "Doğrulama e-postasında sağlanan Kodu girin.", + "noCodeReceived": "Kod almadınız mı?", + "resendCode": "Kodu tekrar gönder", + "codeSent": "E-posta adresinize bir kod gönderildi.", + "submit": "Devam", + "labels": { + "code": "Kod" + }, + "required": { + "code": "Bu alan zorunludur" + } + }, + "errors": { + "couldNotResendEmail": "E-posta yeniden gönderilemedi", + "couldNotVerifyUser": "Kullanıcı doğrulanamadı", + "couldNotVerifyInvite": "Davet doğrulanamadı", + "couldNotVerifyEmail": "E-posta doğrulanamadı", + "couldNotVerify": "Doğrulanamadı", + "couldNotLoadUser": "Kullanıcı yüklenemedi", + "couldNotLoadAuthenticators": "Olası kimlik doğrulayıcılar yüklenemedi", + "couldNotCreateSession": "Oturum oluşturulamadı", + "noHostFound": "Host bulunamadı", + "userAlreadyVerified": "Kullanıcı zaten doğrulanmış!", + "couldNotResendInvite": "Davet yeniden gönderilemedi", + "contextMissing": "Bir hata oluştu. Lütfen tekrar deneyin.", + "inviteSendFailed": "Davet e-postası gönderilemedi", + "emailSendFailed": "Doğrulama e-postası gönderilemedi" + } + }, + "authenticator": { + "title": "Kimlik doğrulama yöntemi seçin", + "description": "Kimlik doğrulaması yapmak istediğiniz yöntemi seçin", + "noMethodsAvailable": "Kullanılabilir kimlik doğrulama yöntemi yok", + "allSetup": "Zaten bir kimlik doğrulayıcı kurdunuz!", + "linkWithIDP": "veya bir Kimlik Sağlayıcı ile bağlantı kurun", + "methods": { + "totp": "Kimlik doğrulayıcı uygulaması", + "u2f": "Evrensel ikinci faktör", + "otpEmail": "E-posta ile kod", + "otpSms": "SMS ile kod", + "passkey": "Passkey", + "password": "Şifre" + } + }, + "device": { + "usercode": { + "title": "Cihaz kodu", + "description": "Uygulamanızda veya cihazınızda görüntülenen kodu girin.", + "submit": "Devam", + "labels": { + "code": "Kod" + }, + "required": { + "code": "Bu alan zorunludur" + } + }, + "request": { + "title": "{appName} bağlanmak istiyor", + "description": "{appName} şunlara erişim sahibi olacak:", + "disclaimer": "İzin Ver'e tıklayarak, {appName} ve Zitadel'in bilgilerinizi kendi hizmet şartları ve gizlilik politikalarına uygun olarak kullanmasına izin vermiş olursunuz. Bu erişimi istediğiniz zaman iptal edebilirsiniz.", + "submit": "İzin Ver", + "deny": "Reddet" + }, + "scope": { + "openid": "Kimliğinizi doğrulayın.", + "email": "E-posta adresinizi görüntüleyin.", + "profile": "Tam profil bilgilerinizi görüntüleyin.", + "offline_access": "Hesabınıza çevrimdışı erişime izin verin." + } + }, + "error": { + "noUserCode": "Kullanıcı kodu sağlanmadı!", + "noDeviceRequest": "Cihaz isteği bulunamadı.", + "unknownContext": "Kullanıcının bağlamı alınamadı. Önce kullanıcı adını girdiğinizden emin olun veya searchParam olarak bir loginName sağlayın.", + "sessionExpired": "Oturumunuzun süresi doldu veya yeniden kimlik doğrulaması gerekiyor. Lütfen tekrar giriş yapın.", + "failedLoading": "Veri yüklenemedi. Lütfen tekrar deneyin.", + "tryagain": "Tekrar Dene", + "couldNotContinueSession": "Oturuma devam edilemedi - kullanıcı bilgileri eksik", + "couldNotClearSession": "Oturum sonlandırılamadı. Lütfen tekrar deneyin." + } +} diff --git a/auth/ui/v2/apps/login/locales/uk.json b/auth/ui/v2/apps/login/locales/uk.json new file mode 100644 index 0000000..7bb4b29 --- /dev/null +++ b/auth/ui/v2/apps/login/locales/uk.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "Назад", + "title": "Вхід через Zitadel" + }, + "accounts": { + "title": "Облікові записи", + "description": "Виберіть обліковий запис, який хочете використовувати.", + "addAnother": "Додати інший обліковий запис", + "noResults": "Облікові записи не знайдено", + "verified": "підтверджено", + "expired": "закінчився" + }, + "logout": { + "title": "Вихід", + "description": "Натисніть на обліковий запис, щоб завершити сеанс", + "noResults": "Облікові записи не знайдено", + "clear": "Завершити сеанс", + "verifiedAt": "Остання активність: {time}", + "success": { + "title": "Вихід успішний", + "description": "Ви успішно вийшли з системи." + } + }, + "loginname": { + "title": "З поверненням!", + "description": "Введіть свої дані для входу.", + "register": "Зареєструвати нового користувача", + "submit": "Продовжити", + "labels": { + "loginname": "Ім'я для входу", + "username": "Ім'я користувача", + "usernameOrPhoneNumber": "Ім'я користувача або номер телефону", + "usernameOrEmail": "Ім'я користувача або електронна пошта" + }, + "required": { + "loginName": "Це поле обов'язкове" + }, + "errors": { + "internalError": "Сталася внутрішня помилка", + "couldNotGetLoginSettings": "Не вдалося отримати налаштування входу", + "couldNotSearchUsers": "Не вдалося знайти користувачів", + "couldNotGetDomain": "Не вдалося отримати домен", + "couldNotGetHost": "Не вдалося отримати хост", + "couldNotStartIDPFlow": "Не вдалося запустити потік IDP", + "moreThanOneUserFound": "Знайдено більше одного користувача. Вкажіть унікальний ідентифікатор.", + "userNotFound": "Користувача не знайдено в системі", + "couldNotCreateSession": "Не вдалося створити сеанс для користувача", + "initialUserNotSupported": "Початковий користувач не підтримується", + "localAuthenticationNotAllowed": "Локальна аутентифікація заборонена! Зверніться до адміністратора за додатковою інформацією.", + "passkeysNotAllowed": "Ключі доступу не дозволені! Зверніться до адміністратора для отримання додаткової інформації.", + "couldNotFindIdentityProvider": "Не вдалося знайти постачальника ідентичності.", + "userNotActive": "Користувач неактивний. Зверніться до адміністратора для отримання додаткової інформації." + } + }, + "zitadel": { + "errors": { + "errorOccured": "Сталася помилка", + "multipleUsersFound": "Знайдено кількох користувачів", + "userNotFound": "Користувача не знайдено в системі" + } + }, + "password": { + "verify": { + "title": "Пароль", + "description": "Введіть свій пароль.", + "resetPassword": "Скинути пароль", + "submit": "Продовжити", + "labels": { + "password": "Пароль" + }, + "required": { + "password": "Це поле обов'язкове" + }, + "errors": { + "couldNotVerifyPassword": "Не вдалося перевірити пароль", + "couldNotResetPassword": "Не вдалося скинути пароль" + }, + "info": { + "passwordResetSent": "Пароль було скинуто. Будь ласка, перевірте свою електронну пошту" + } + }, + "set": { + "title": "Встановити пароль", + "description": "Встановіть пароль для свого облікового запису", + "codeSent": "Новий код надіслано на вашу електронну адресу.", + "noCodeReceived": "Не отримали код?", + "resend": "Надіслати код повторно", + "submit": "Продовжити", + "labels": { + "code": "Код", + "newPassword": "Новий пароль", + "confirmPassword": "Підтвердити пароль" + }, + "required": { + "code": "Це поле обов'язкове", + "newPassword": "Ви повинні вказати пароль!", + "confirmPassword": "Це поле обов'язкове" + }, + "errors": { + "couldNotSetPassword": "Не вдалося встановити пароль", + "couldNotResetPassword": "Не вдалося скинути пароль", + "couldNotVerifyPassword": "Не вдалося перевірити пароль" + } + }, + "change": { + "title": "Змінити пароль", + "description": "Встановіть пароль для свого облікового запису", + "submit": "Продовжити", + "labels": { + "currentPassword": "Поточний пароль", + "newPassword": "Новий пароль", + "confirmPassword": "Підтвердити пароль" + }, + "required": { + "currentPassword": "Ви повинні вказати поточний пароль!", + "newPassword": "Ви повинні вказати новий пароль!", + "confirmPassword": "Це поле обов'язкове" + }, + "errors": { + "currentPasswordInvalid": "Поточний пароль невірний.", + "couldNotChangePassword": "Не вдалося змінити пароль", + "couldNotVerifyPassword": "Не вдалося перевірити пароль", + "unknownError": "Невідома помилка" + } + }, + "complexity": { + "length": "Повинен містити щонайменше {minLength} символів.", + "hasSymbol": "Повинен містити символ.", + "hasNumber": "Повинен містити цифру.", + "hasUppercase": "Повинен містити велику літеру.", + "hasLowercase": "Повинен містити малу літеру.", + "equals": "Підтвердження пароля збігається.", + "matches": "Збігається", + "doesNotMatch": "Не збігається" + }, + "errors": { + "noHostFound": "Хост не знайдено", + "couldNotSendResetLink": "Не вдалося надіслати посилання для скидання пароля", + "couldNotCreateSessionForUser": "Не вдалося створити сеанс для користувача", + "couldNotVerifyPassword": "Не вдалося перевірити пароль", + "failedToAuthenticate": "Не вдалося автентифікуватися. Ви використали {failedAttempts} з {maxPasswordAttempts} спроб введення пароля.{lockoutMessage}", + "failedToAuthenticateNoLimit": "Не вдалося автентифікуватися.", + "accountLockedContactAdmin": " Зверніться до адміністратора, щоб розблокувати свій обліковий запис", + "userNotFound": "Користувача не знайдено в системі", + "initialUserNotSupported": "Початковий користувач не підтримується", + "userInitialStateNotSupported": "Початковий стан користувача не підтримується", + "codeOrVerificationRequired": "Ви повинні надати код або мати дійсну перевірку користувача", + "verificationRequired": "Необхідно виконати перевірку користувача", + "couldNotLoadSession": "Не вдалося завантажити сеанс", + "couldNotLoadAuthMethods": "Не вдалося завантажити методи автентифікації", + "failedPrecondition": "Не виконано передумову", + "sessionNotValid": "Сеанс недійсний", + "passwordVerificationMissing": "Відсутня перевірка пароля.", + "passwordVerificationTooOld": "Перевірка пароля застаріла. Будь ласка, перевірте пароль ще раз.", + "passwordResetNotAllowed": "Скидання пароля заборонено. Зверніться до адміністратора за додатковою інформацією.", + "localAuthenticationNotAllowed": "Локальна аутентифікація заборонена! Зверніться до адміністратора за додатковою інформацією." + } + }, + "idp": { + "title": "Увійти через SSO", + "description": "Виберіть одного з наступних постачальників для входу", + "orSignInWith": "або увійти через", + "signInWithApple": "Увійти через Apple", + "signInWithGoogle": "Увійти через Google", + "signInWithAzureAD": "Увійти через AzureAD", + "signInWithGithub": "Увійти через GitHub", + "signInWithGitlab": "Увійти через GitLab", + "signInWithZitadel": "Увійти через Zitadel", + "loginError": { + "title": "Помилка входу", + "description": "Сталася помилка під час спроби входу." + }, + "linkingError": { + "title": "Помилка прив'язки облікового запису", + "description": "Сталася помилка під час спроби прив'язати ваш обліковий запис." + }, + "completeRegister": { + "title": "Заповніть свої дані", + "description": "Вам потрібно завершити реєстрацію, вказавши свою електронну адресу та ім'я." + }, + "accountNotFound": { + "title": "Обліковий запис не знайдено", + "description": "Ми не змогли знайти обліковий запис, пов'язаний з вашими обліковими даними постачальника ідентичності.", + "info": "Існуючий обліковий запис не знайдено. Будь ласка, увійдіть за допомогою існуючого облікового запису або зверніться до адміністратора за допомогою.", + "backToLogin": "Повернутися до входу" + }, + "registrationFailed": { + "title": "Реєстрація недоступна", + "description": "Ми не змогли завершити процес реєстрації.", + "info": "Не вдалося визначити організацію для реєстрації. Будь ласка, зверніться до адміністратора за допомогою.", + "backToLogin": "Повернутися до входу" + }, + "processing": { + "message": "Обробка автентифікації...", + "noRedirect": "Сервер не повернув перенаправлення або помилку", + "unexpectedError": "Сталася неочікувана помилка" + }, + "errors": { + "missingParameters": "Відсутні обов'язкові параметри", + "missingIdpInfo": "Відсутня інформація IDP", + "idpNotFound": "Постачальника ідентичності не знайдено", + "linkingNotAllowed": "Прив'язка не дозволена для цього постачальника ідентичності", + "linkingFailed": "Не вдалося прив'язати постачальника ідентичності до облікового запису", + "autoLinkingFailed": "Не вдалося автоматично прив'язати обліковий запис", + "userCreationFailed": "Не вдалося створити обліковий запис користувача", + "orgResolutionFailed": "Не вдалося визначити організацію для реєстрації", + "sessionCreationFailed": "Не вдалося створити сеанс або визначити перенаправлення", + "unknownError": "Сталася невідома помилка" + } + }, + "ldap": { + "title": "Вхід LDAP", + "description": "Введіть свої облікові дані LDAP.", + "submit": "Продовжити", + "labels": { + "username": "Ім'я користувача", + "password": "Пароль" + }, + "required": { + "username": "Це поле обов'язкове", + "password": "Це поле обов'язкове" + } + }, + "mfa": { + "verify": { + "title": "Підтвердіть свою особу", + "description": "Виберіть один з наступних факторів.", + "noResults": "Немає доступних других факторів для налаштування." + }, + "set": { + "title": "Налаштувати 2-факторну автентифікацію", + "description": "Виберіть один з наступних других факторів.", + "skip": "Пропустити" + } + }, + "otp": { + "verify": { + "title": "Перевірити 2-факторну автентифікацію", + "totpDescription": "Введіть код з вашого додатку автентифікації.", + "smsDescription": "Введіть код, отриманий через SMS.", + "emailDescription": "Введіть код, отриманий на електронну пошту.", + "noCodeReceived": "Не отримали код?", + "resendCode": "Надіслати код повторно", + "resendCodeIn": "Надіслати код повторно ({seconds} с)", + "submit": "Продовжити", + "labels": { + "code": "Код" + }, + "required": { + "code": "Це поле обов'язкове" + } + }, + "set": { + "title": "Налаштувати 2-факторну автентифікацію", + "totpDescription": "Відскануйте QR-код вашим додатком автентифікації.", + "smsDescription": "Введіть номер телефону для отримання коду через SMS.", + "emailDescription": "Введіть електронну адресу для отримання коду на пошту.", + "totpRegisterDescription": "Відскануйте QR-код або перейдіть за URL вручну.", + "emailAddDescription": "Використовуйте одноразовий код, що надсилається на вашу підтверджену електронну адресу, як другий фактор.", + "smsAddDescription": "Використовуйте одноразовий код, що надсилається на ваш підтверджений номер телефону, як другий фактор.", + "add": "Додати", + "emailAdded": "Код електронною поштою додано.", + "smsAdded": "Код через SMS додано.", + "submit": "Продовжити", + "labels": { + "code": "Код" + }, + "required": { + "code": "Це поле обов'язкове" + } + }, + "errors": { + "couldNotRequestChallenge": "Не вдалося запросити OTP-виклик", + "couldNotVerifyCode": "Не вдалося перевірити OTP-код", + "couldNotGetSession": "Не вдалося завантажити сеанс. Увійдіть знову.", + "invalidMethod": "Цей другий фактор не підтримується.", + "couldNotAddEmail": "Не вдалося додати код електронною поштою.", + "couldNotAddSms": "Не вдалося додати код через SMS.", + "emailNotVerified": "Підтвердьте електронну адресу, перш ніж додавати коди електронною поштою.", + "phoneNotVerified": "Підтвердьте номер телефону, перш ніж додавати коди через SMS." + } + }, + "passkey": { + "verify": { + "title": "Автентифікація за допомогою ключа доступу", + "description": "Ваш пристрій запитає відбиток пальця, обличчя або блокування екрана", + "usePassword": "Використати пароль", + "submit": "Продовжити", + "errors": { + "couldNotRequestChallenge": "Не вдалося запросити виклик ключа доступу", + "couldNotVerifyPasskey": "Не вдалося перевірити ключ доступу", + "noResponseReceived": "Перевірка ключа доступу не вдалася - відповідь не отримано", + "noRedirectProvided": "Перевірка ключа доступу завершена, але перенаправлення не надано", + "couldNotRetrievePasskey": "Сталася помилка під час отримання ключа доступу", + "verificationCancelled": "Перевірку ключа доступу скасовано", + "verificationFailed": "Сталася помилка під час перевірки ключа доступу", + "couldNotFindSession": "Не вдалося знайти сеанс", + "couldNotUpdateSession": "Не вдалося оновити сеанс", + "userNotFound": "Користувача не знайдено в системі", + "couldNotDetermineRedirect": "Не вдалося визначити URL перенаправлення після перевірки ключа доступу" + } + }, + "set": { + "title": "Налаштувати ключ доступу", + "description": "Ваш пристрій запитає відбиток пальця, обличчя або блокування екрана", + "info": { + "description": "Ключ доступу - це метод автентифікації на пристрої, такий як відбиток пальця, Apple FaceID або подібний. ", + "link": "Автентифікація за допомогою ключа доступу" + }, + "skip": "Пропустити", + "submit": "Продовжити" + } + }, + "u2f": { + "verify": { + "title": "Перевірити 2-факторну автентифікацію", + "description": "Підтвердіть свій обліковий запис за допомогою пристрою." + }, + "set": { + "title": "Налаштувати 2-факторну автентифікацію", + "description": "Налаштуйте пристрій як другий фактор.", + "submit": "Продовжити" + } + }, + "register": { + "methods": { + "passkey": "Ключ доступу", + "password": "Пароль" + }, + "disabled": { + "title": "Реєстрацію вимкнено", + "description": "Реєстрацію вимкнено. Будь ласка, зверніться до адміністратора." + }, + "missingdata": { + "title": "Відсутні дані", + "description": "Вкажіть електронну пошту, ім'я та прізвище для реєстрації." + }, + "title": "Реєстрація", + "description": "Створіть свій обліковий запис Zitadel.", + "noMethodAvailableWarning": "Немає доступного методу автентифікації. Будь ласка, зверніться до адміністратора.", + "selectMethod": "Виберіть метод автентифікації", + "agreeTo": "Для реєстрації ви повинні погодитися з умовами та положеннями", + "termsOfService": "Умови надання послуг", + "privacyPolicy": "Політика конфіденційності", + "submit": "Продовжити", + "password": { + "title": "Встановити пароль", + "description": "Встановіть пароль для свого облікового запису", + "submit": "Продовжити", + "labels": { + "password": "Пароль", + "confirmPassword": "Підтвердити пароль" + }, + "required": { + "password": "Ви повинні вказати пароль!", + "confirmPassword": "Це поле обов'язкове" + } + }, + "labels": { + "firstname": "Ім'я", + "lastname": "Прізвище", + "email": "Електронна пошта" + }, + "required": { + "firstname": "Це поле обов'язкове", + "lastname": "Це поле обов'язкове", + "email": "Це поле обов'язкове" + }, + "errors": { + "couldNotCreateUser": "Не вдалося створити користувача", + "couldNotCreateSession": "Не вдалося створити сеанс", + "userNotFound": "Користувача не знайдено в системі", + "couldNotLinkIDP": "Не вдалося прив'язати IDP до користувача", + "couldNotRegisterUser": "Не вдалося зареєструвати користувача", + "sessionMismatch": "Реєстрацію було розпочато в іншому браузері. Увійдіть знову через вашого постачальника ідентифікації." + } + }, + "invite": { + "title": "Запросити користувача", + "description": "Вкажіть електронну адресу та ім'я користувача, якого хочете запросити.", + "info": "Користувач отримає електронний лист з подальшими інструкціями.", + "notAllowed": "Ваші налаштування не дозволяють запрошувати користувачів.", + "submit": "Продовжити", + "success": { + "title": "Користувача запрошено", + "description": "Електронний лист успішно надіслано.", + "verified": "Користувача запрошено, і він вже підтвердив свою електронну пошту.", + "notVerifiedYet": "Користувача запрошено. Він отримає електронний лист з подальшими інструкціями.", + "submit": "Запросити іншого користувача" + } + }, + "signedin": { + "title": "Ласкаво просимо, {user}!", + "description": "Ви увійшли в систему.", + "continue": "Продовжити", + "error": { + "title": "Помилка", + "description": "Сталася помилка під час спроби входу." + } + }, + "verify": { + "userIdMissing": "userId не надано!", + "successTitle": "Користувача підтверджено", + "successDescription": "Користувача успішно підтверджено.", + "successContinue": "Продовжити", + "setupAuthenticator": "Налаштувати автентифікатор", + "verify": { + "title": "Підтвердити користувача", + "description": "Введіть код, наданий у листі підтвердження.", + "noCodeReceived": "Не отримали код?", + "resendCode": "Надіслати код повторно", + "codeSent": "Код щойно надіслано на вашу електронну адресу.", + "submit": "Продовжити", + "labels": { + "code": "Код" + }, + "required": { + "code": "Це поле обов'язкове" + } + }, + "errors": { + "couldNotResendEmail": "Не вдалося повторно надіслати електронний лист", + "couldNotVerifyUser": "Не вдалося підтвердити користувача", + "couldNotVerifyInvite": "Не вдалося підтвердити запрошення", + "couldNotVerifyEmail": "Не вдалося підтвердити електронну пошту", + "couldNotVerify": "Не вдалося підтвердити", + "couldNotLoadUser": "Не вдалося завантажити користувача", + "couldNotLoadAuthenticators": "Не вдалося завантажити можливі автентифікатори", + "couldNotCreateSession": "Не вдалося створити сеанс", + "noHostFound": "Хост не знайдено", + "userAlreadyVerified": "Користувача вже підтверджено!", + "couldNotResendInvite": "Не вдалося повторно надіслати запрошення", + "inviteSendFailed": "Не вдалося надіслати лист-запрошення", + "emailSendFailed": "Не вдалося надіслати лист підтвердження", + "contextMissing": "Сталася помилка. Будь ласка, спробуйте ще раз." + } + }, + "authenticator": { + "title": "Виберіть метод автентифікації", + "description": "Виберіть метод автентифікації", + "noMethodsAvailable": "Немає доступних методів автентифікації", + "allSetup": "Ви вже налаштували автентифікатор!", + "linkWithIDP": "або прив'яжіть до постачальника ідентичності", + "methods": { + "totp": "Додаток автентифікації", + "u2f": "Універсальний другий фактор", + "otpEmail": "Код через електронну пошту", + "otpSms": "Код через SMS", + "passkey": "Ключ доступу", + "password": "Пароль" + } + }, + "device": { + "usercode": { + "title": "Код пристрою", + "description": "Введіть код, показаний у вашому додатку або на пристрої.", + "submit": "Продовжити", + "labels": { + "code": "Код" + }, + "required": { + "code": "Це поле обов'язкове" + } + }, + "request": { + "title": "{appName} хоче підключитися", + "description": "{appName} матиме доступ до:", + "disclaimer": "Натискаючи Дозволити, ви дозволяєте {appName} та Zitadel використовувати вашу інформацію відповідно до їхніх умов надання послуг та політик конфіденційності. Ви можете скасувати цей доступ у будь-який час.", + "submit": "Дозволити", + "deny": "Відхилити" + }, + "scope": { + "openid": "Підтвердити вашу особу.", + "email": "Переглянути вашу електронну адресу.", + "profile": "Переглянути повну інформацію вашого профілю.", + "offline_access": "Дозволити офлайн-доступ до вашого облікового запису." + } + }, + "error": { + "noUserCode": "Код користувача не надано!", + "noDeviceRequest": "Запит пристрою не знайдено.", + "unknownContext": "Не вдалося отримати контекст користувача. Переконайтеся, що спочатку ввели ім'я користувача або вкажіть loginName як параметр пошуку.", + "sessionExpired": "Ваш сеанс закінчився або потребує повторної автентифікації. Будь ласка, увійдіть знову.", + "failedLoading": "Не вдалося завантажити дані. Будь ласка, спробуйте ще раз.", + "tryagain": "Спробувати ще раз", + "couldNotContinueSession": "Не вдалося продовжити сеанс - відсутня інформація про користувача", + "couldNotClearSession": "Не вдалося завершити сеанс. Будь ласка, спробуйте ще раз." + } +} diff --git a/auth/ui/v2/apps/login/locales/zh.json b/auth/ui/v2/apps/login/locales/zh.json new file mode 100644 index 0000000..6200f5f --- /dev/null +++ b/auth/ui/v2/apps/login/locales/zh.json @@ -0,0 +1,490 @@ +{ + "common": { + "back": "返回", + "title": "使用 Zitadel 登录" + }, + "accounts": { + "title": "账户", + "description": "选择您要使用的账户。", + "addAnother": "添加另一个账户", + "noResults": "未找到账户", + "verified": "已验证", + "expired": "已过期" + }, + "logout": { + "title": "注销", + "description": "选择您想注销的账户", + "noResults": "未找到账户", + "clear": "注销会话", + "verifiedAt": "最后活动时间:{time}", + "success": { + "title": "注销成功", + "description": "您已成功注销。" + } + }, + "loginname": { + "title": "欢迎回来!", + "description": "请输入您的登录信息。", + "register": "注册新用户", + "submit": "继续", + "labels": { + "loginname": "登录名", + "username": "用户名", + "usernameOrPhoneNumber": "用户名或电话号码", + "usernameOrEmail": "用户名或电子邮箱" + }, + "required": { + "loginName": "此字段为必填项" + }, + "errors": { + "internalError": "发生内部错误", + "couldNotGetLoginSettings": "无法获取登录设置", + "couldNotSearchUsers": "无法搜索用户", + "couldNotGetDomain": "无法获取域名", + "couldNotGetHost": "无法获取主机", + "couldNotStartIDPFlow": "无法启动身份提供者流程", + "moreThanOneUserFound": "找到多个用户。请提供唯一标识符。", + "userNotFound": "系统中未找到用户", + "couldNotCreateSession": "无法为用户创建会话", + "initialUserNotSupported": "不支持初始用户", + "localAuthenticationNotAllowed": "不允许本地身份验证!请联系您的管理员以获取更多信息。", + "passkeysNotAllowed": "不允许使用 Passkey!请联系管理员了解更多信息。", + "couldNotFindIdentityProvider": "找不到身份提供者。", + "userNotActive": "用户未激活。请联系管理员了解更多信息。" + } + }, + "zitadel": { + "errors": { + "errorOccured": "发生错误", + "multipleUsersFound": "找到多个用户", + "userNotFound": "系统中未找到用户" + } + }, + "password": { + "verify": { + "title": "密码", + "description": "请输入您的密码。", + "resetPassword": "重置密码", + "submit": "继续", + "labels": { + "password": "密码" + }, + "required": { + "password": "此字段为必填项" + }, + "errors": { + "couldNotVerifyPassword": "无法验证密码", + "couldNotResetPassword": "无法重置密码" + }, + "info": { + "passwordResetSent": "密码已重置。请检查您的电子邮件" + } + }, + "set": { + "title": "设置密码", + "description": "为您的账户设置密码", + "codeSent": "新代码已发送到您的电子邮件地址。", + "noCodeReceived": "没有收到验证码?", + "resend": "重发验证码", + "submit": "继续", + "labels": { + "code": "验证码", + "newPassword": "新密码", + "confirmPassword": "确认密码" + }, + "required": { + "code": "此字段为必填项", + "newPassword": "必须提供密码!", + "confirmPassword": "此字段为必填项" + }, + "errors": { + "couldNotSetPassword": "无法设置密码", + "couldNotResetPassword": "无法重置密码", + "couldNotVerifyPassword": "无法验证密码" + } + }, + "change": { + "title": "更改密码", + "description": "为您的账户设置密码", + "submit": "继续", + "labels": { + "currentPassword": "当前密码", + "newPassword": "新密码", + "confirmPassword": "确认密码" + }, + "required": { + "currentPassword": "必须提供当前密码!", + "newPassword": "必须提供新密码!", + "confirmPassword": "此字段为必填项" + }, + "errors": { + "currentPasswordInvalid": "当前密码不正确。", + "couldNotChangePassword": "无法更改密码", + "couldNotVerifyPassword": "无法验证密码", + "unknownError": "未知错误" + } + }, + "complexity": { + "length": "必须至少有 {minLength} 个字符。", + "hasSymbol": "必须包含一个符号。", + "hasNumber": "必须包含一个数字。", + "hasUppercase": "必须包含一个大写字母。", + "hasLowercase": "必须包含一个小写字母。", + "equals": "密码确认匹配。", + "matches": "匹配", + "doesNotMatch": "不匹配" + }, + "errors": { + "noHostFound": "未找到主机", + "couldNotSendResetLink": "无法发送密码重置链接", + "couldNotCreateSessionForUser": "无法为用户创建会话", + "couldNotVerifyPassword": "无法验证密码", + "failedToAuthenticate": "身份验证失败。您已尝试输入密码 {failedAttempts} 次,共允许 {maxPasswordAttempts} 次。{lockoutMessage}", + "failedToAuthenticateNoLimit": "身份验证失败。", + "accountLockedContactAdmin": " 请联系管理员以解锁您的账户", + "userNotFound": "系统中未找到用户", + "initialUserNotSupported": "不支持初始用户", + "userInitialStateNotSupported": "不支持用户初始状态", + "codeOrVerificationRequired": "您必须提供验证码或通过有效的用户验证", + "verificationRequired": "必须完成用户验证", + "couldNotLoadSession": "无法加载会话", + "couldNotLoadAuthMethods": "无法加载验证方法", + "failedPrecondition": "前置条件失败", + "sessionNotValid": "会话无效", + "passwordVerificationMissing": "缺少密码验证。", + "passwordVerificationTooOld": "密码验证已过期。请重新通过验证。", + "passwordResetNotAllowed": "不允许重置密码。请联系您的管理员以获取更多信息。", + "localAuthenticationNotAllowed": "不允许本地身份验证!请联系您的管理员以获取更多信息。" + } + }, + "idp": { + "title": "使用 SSO 登录", + "description": "选择以下提供商中的一个进行登录", + "orSignInWith": "或使用以下方式登录", + "signInWithApple": "用 Apple 登录", + "signInWithGoogle": "用 Google 登录", + "signInWithAzureAD": "用 AzureAD 登录", + "signInWithGithub": "用 GitHub 登录", + "signInWithGitlab": "用 GitLab 登录", + "signInWithZitadel": "用 Zitadel 登录", + "loginError": { + "title": "登录失败", + "description": "登录时发生错误。" + }, + "linkingError": { + "title": "账户链接失败", + "description": "链接账户时发生错误。" + }, + "completeRegister": { + "title": "完成注册", + "description": "完成您的账户注册。" + }, + "accountNotFound": { + "title": "未找到账户", + "description": "我们无法找到与您的身份提供商凭据关联的账户。", + "info": "未找到现有账户。请使用现有账户登录或联系您的管理员寻求帮助。", + "backToLogin": "返回登录" + }, + "registrationFailed": { + "title": "注册不可用", + "description": "我们无法完成注册过程。", + "info": "无法确定注册的组织。请联系您的管理员寻求帮助。", + "backToLogin": "返回登录" + }, + "processing": { + "message": "正在处理身份验证...", + "noRedirect": "未从服务器收到重定向或错误", + "unexpectedError": "发生意外错误" + }, + "errors": { + "missingParameters": "缺少必需参数", + "missingIdpInfo": "缺少身份提供商信息", + "idpNotFound": "未找到身份提供商", + "linkingNotAllowed": "此身份提供商不允许关联", + "linkingFailed": "无法将身份提供商关联到账户", + "autoLinkingFailed": "无法自动关联账户", + "userCreationFailed": "无法创建用户账户", + "orgResolutionFailed": "无法确定注册的组织", + "sessionCreationFailed": "无法创建会话或确定重定向", + "unknownError": "发生未知错误" + } + }, + "ldap": { + "title": "使用 LDAP 登录", + "description": "请输入您的 LDAP 凭据。", + "submit": "继续", + "labels": { + "username": "用户名", + "password": "密码" + }, + "required": { + "username": "此字段为必填项", + "password": "此字段为必填项" + } + }, + "mfa": { + "verify": { + "title": "验证您的身份", + "description": "选择以下的一个因素。", + "noResults": "没有可设置的第二因素。" + }, + "set": { + "title": "设置双因素认证", + "description": "选择以下的一个第二因素。", + "skip": "跳过" + } + }, + "otp": { + "verify": { + "title": "验证双因素", + "totpDescription": "请输入认证应用程序中的验证码。", + "smsDescription": "输入通过短信收到的验证码。", + "emailDescription": "输入通过电子邮件收到的验证码。", + "noCodeReceived": "没有收到验证码?", + "resendCode": "重发验证码", + "resendCodeIn": "重发验证码 ({seconds}秒)", + "submit": "继续", + "labels": { + "code": "验证码" + }, + "required": { + "code": "此字段为必填项" + } + }, + "set": { + "title": "设置双因素认证", + "totpDescription": "使用认证应用程序扫描二维码。", + "smsDescription": "输入您的电话号码以接收短信验证码。", + "emailDescription": "输入您的电子邮箱地址以接收电子邮件验证码。", + "totpRegisterDescription": "扫描二维码或手动导航到URL。", + "emailAddDescription": "使用发送到您已验证电子邮件地址的一次性验证码作为第二因素。", + "smsAddDescription": "使用发送到您已验证手机号码的一次性验证码作为第二因素。", + "add": "添加", + "emailAdded": "已添加电子邮件验证码。", + "smsAdded": "已添加短信验证码。", + "submit": "继续", + "labels": { + "code": "验证码" + }, + "required": { + "code": "此字段为必填项" + } + }, + "errors": { + "couldNotRequestChallenge": "无法请求 OTP 质询", + "couldNotVerifyCode": "无法验证 OTP 验证码", + "couldNotGetSession": "无法加载您的会话。请重新登录。", + "invalidMethod": "不支持此第二因素。", + "couldNotAddEmail": "无法添加电子邮件验证码。", + "couldNotAddSms": "无法添加短信验证码。", + "emailNotVerified": "添加电子邮件验证码前,请先验证您的电子邮件地址。", + "phoneNotVerified": "添加短信验证码前,请先验证您的手机号码。" + } + }, + "passkey": { + "verify": { + "title": "使用密钥认证", + "description": "您的设备将请求指纹、面部识别或屏幕锁", + "usePassword": "使用密码", + "submit": "继续", + "errors": { + "couldNotRequestChallenge": "无法请求密钥挑战", + "couldNotVerifyPasskey": "无法验证密钥", + "noResponseReceived": "密钥验证失败 - 未收到响应", + "noRedirectProvided": "密钥验证完成但未提供重定向", + "couldNotRetrievePasskey": "检索密钥时发生错误", + "verificationCancelled": "密钥验证已取消", + "verificationFailed": "密钥验证期间发生错误", + "couldNotFindSession": "找不到会话", + "couldNotUpdateSession": "无法更新会话", + "userNotFound": "系统中未找到用户", + "couldNotDetermineRedirect": "密钥验证后无法确定重定向URL" + } + }, + "set": { + "title": "设置密钥", + "description": "您的设备将请求指纹、面部识别或屏幕锁", + "info": { + "description": "密钥是在设备上如指纹、Apple FaceID 或类似的认证方法。", + "link": "密码密钥认证" + }, + "skip": "跳过", + "submit": "继续" + } + }, + "u2f": { + "verify": { + "title": "验证双因素", + "description": "使用您的设备验证帐户。" + }, + "set": { + "title": "设置双因素认证", + "description": "设置设备为第二因素。", + "submit": "继续" + } + }, + "register": { + "methods": { + "passkey": "密钥", + "password": "密码" + }, + "disabled": { + "title": "注册已禁用", + "description": "您的设置不允许注册新用户。" + }, + "missingdata": { + "title": "缺少数据", + "description": "请提供所有必需的数据。" + }, + "title": "注册", + "description": "创建您的 Zitadel 账户。", + "noMethodAvailableWarning": "没有可用的认证方法。请联系您的系统管理员。", + "selectMethod": "选择您想使用的认证方法", + "agreeTo": "注册即表示您同意条款和条件", + "termsOfService": "服务条款", + "privacyPolicy": "隐私政策", + "submit": "继续", + "password": { + "title": "设置密码", + "description": "为您的账户设置密码", + "submit": "继续", + "labels": { + "password": "密码", + "confirmPassword": "确认密码" + }, + "required": { + "password": "必须提供密码!", + "confirmPassword": "此字段为必填项" + } + }, + "labels": { + "firstname": "名字", + "lastname": "姓氏", + "email": "电子邮箱" + }, + "required": { + "firstname": "此字段为必填项", + "lastname": "此字段为必填项", + "email": "此字段为必填项" + }, + "errors": { + "couldNotCreateUser": "无法创建用户", + "couldNotCreateSession": "无法创建会话", + "userNotFound": "系统中未找到用户", + "couldNotLinkIDP": "无法将 IDP 关联到用户", + "couldNotRegisterUser": "无法注册用户", + "sessionMismatch": "注册是在另一个浏览器中开始的。请使用您的身份提供商重新登录。" + } + }, + "invite": { + "title": "邀请用户", + "description": "提供您想邀请的用户的电子邮箱地址和姓名。", + "info": "用户将收到一封包含进一步说明的电子邮件。", + "notAllowed": "您的设置不允许邀请用户。", + "submit": "继续", + "success": { + "title": "用户已邀请", + "description": "邮件已成功发送。", + "verified": "用户已被邀请并已验证其电子邮件。", + "notVerifiedYet": "用户已被邀请。他们将收到一封包含进一步说明的电子邮件。", + "submit": "邀请另一位用户" + } + }, + "signedin": { + "title": "欢迎 {user}!", + "description": "您已登录。", + "continue": "继续", + "error": { + "title": "错误", + "description": "登录时发生错误。" + } + }, + "verify": { + "userIdMissing": "未提供用户 ID!", + "successTitle": "用户已验证", + "successDescription": "用户已成功验证。", + "successContinue": "继续", + "setupAuthenticator": "设置认证器", + "verify": { + "title": "验证用户", + "description": "输入验证邮件中的验证码。", + "noCodeReceived": "没有收到验证码?", + "resendCode": "重发验证码", + "codeSent": "刚刚发送了一封包含验证码的电子邮件。", + "submit": "继续", + "labels": { + "code": "验证码" + }, + "required": { + "code": "此字段为必填项" + } + }, + "errors": { + "couldNotResendEmail": "无法重新发送邮件", + "couldNotVerifyUser": "无法验证用户", + "couldNotVerifyInvite": "无法验证邀请", + "couldNotVerifyEmail": "无法验证邮箱", + "couldNotVerify": "无法验证", + "couldNotLoadUser": "无法加载用户", + "couldNotLoadAuthenticators": "无法加载可用的身份验证器", + "couldNotCreateSession": "无法创建会话", + "noHostFound": "未找到主机", + "userAlreadyVerified": "用户已验证!", + "couldNotResendInvite": "无法重新发送邀请", + "inviteSendFailed": "发送邀请邮件失败", + "emailSendFailed": "发送验证邮件失败", + "contextMissing": "发生错误。请重试。" + } + }, + "authenticator": { + "title": "选择认证方式", + "description": "选择您想使用的认证方法", + "noMethodsAvailable": "没有可用的认证方法", + "allSetup": "您已经设置好了一个认证器!", + "linkWithIDP": "或将其与身份提供者关联", + "methods": { + "totp": "认证器应用", + "u2f": "通用第二因素", + "otpEmail": "通过电子邮件接收验证码", + "otpSms": "通过短信接收验证码", + "passkey": "密钥", + "password": "密码" + } + }, + "device": { + "usercode": { + "title": "设备代码", + "description": "输入代码。", + "submit": "继续", + "labels": { + "code": "验证码" + }, + "required": { + "code": "此字段为必填项" + } + }, + "request": { + "title": "{appName} 想要连接:", + "description": "{appName} 将访问:", + "disclaimer": "点击“允许”即表示您允许此应用程序和 Zitadel 根据其各自的服务条款和隐私政策使用您的信息。您可以随时撤销此访问权限。", + "submit": "允许", + "deny": "拒绝" + }, + "scope": { + "openid": "验证您的身份。", + "email": "访问您的电子邮件地址。", + "profile": "访问您的完整个人资料信息。", + "offline_access": "允许离线访问您的账户。" + } + }, + "error": { + "noUserCode": "未提供用户代码!", + "noDeviceRequest": "没有找到设备请求。", + "unknownContext": "无法获取用户的上下文。请先输入用户名或提供 loginName 作为搜索参数。", + "sessionExpired": "会话已过期或需要重新验证身份,请重新登录。", + "failedLoading": "加载数据失败,请再试一次。", + "tryagain": "重试", + "couldNotContinueSession": "无法继续会话 - 缺少用户信息", + "couldNotClearSession": "无法结束会话。请重试。" + } +} diff --git a/auth/ui/v2/apps/login/next-env-vars.d.ts b/auth/ui/v2/apps/login/next-env-vars.d.ts new file mode 100644 index 0000000..a66e5e2 --- /dev/null +++ b/auth/ui/v2/apps/login/next-env-vars.d.ts @@ -0,0 +1,135 @@ +declare namespace NodeJS { + interface ProcessEnv { + // Allow any environment variable that matches the pattern + [key: `${string}_AUDIENCE`]: string; // The system api url + [key: `${string}_SYSTEM_USER_ID`]: string; // The service account id + [key: `${string}_SYSTEM_USER_PRIVATE_KEY`]: string; // The service account private key + [key: `${string}_SYSTEM_USER_PRIVATE_KEY_FILE`]: string; // The service account private key file path + + AUDIENCE: string; // The fallback system api url + SYSTEM_USER_ID: string; // The fallback service account id + SYSTEM_USER_PRIVATE_KEY: string; // The fallback service account private key + SYSTEM_USER_PRIVATE_KEY_FILE: string; // The fallback service account private key file path + + /** + * The Zitadel API url + */ + ZITADEL_API_URL: string; + + /** + * The service account token + * If ZITADEL_SERVICE_USER_TOKEN is set, its value is used. + * If ZITADEL_SERVICE_USER_TOKEN is not set but ZITADEL_SERVICE_USER_TOKEN_FILE is set, the application blocks until the file is created. + * As soon as the file exists, its content is read and ZITADEL_SERVICE_USER_TOKEN is set. + */ + ZITADEL_SERVICE_USER_TOKEN: string; + + /** + * Secret used to sign LoginV2 `sessions` cookie entries, the `verificationCheck` cookie and the + * `flowFingerprint` of external IdP flows (purpose-bound signing keys are derived via HKDF). + * Recommended configuration; will become required in a future major release. + * Every value must be at least 32 characters long (e.g. `openssl rand -base64 32`); a shorter value + * disables signing and makes /ready fail instead of falling back to the API credential. + * Deprecated fallback if unset: the configured API credential is used (ZITADEL_SERVICE_USER_TOKEN, + * SYSTEM_USER_PRIVATE_KEY(_FILE) or ZITADEL_LOGINCLIENT_KEYFILE) and a warning is logged at startup. + * A comma-separated list is supported for rotation: the first value signs, all values verify. + * Unsigned or tampered cookie entries are ignored so a client cannot patch an arbitrary session + * or claim a user verification (email / invite code) that never happened. + * All replicas of a deployment must resolve the same secret. + */ + ZITADEL_SESSION_COOKIE_SECRET?: string; + + /** + * Path to a private key file for login client JWT authentication. + * When set, the login service reads this key and signs JWTs with a + * hardcoded subject of "login-client". + * AUDIENCE defaults to ZITADEL_API_URL if not explicitly set. + */ + ZITADEL_LOGINCLIENT_KEYFILE?: string; + + /** + * Optional: wheter a user must have verified email + */ + EMAIL_VERIFICATION: string; + + /** + * Optional: custom request headers to be added to every request + * Split by comma, key value pairs separated by colon + * For example: to call the Zitadel API at an internal address, you can set: + * `CUSTOM_REQUEST_HEADERS=Host:http://zitadel-internal:8080` + */ + CUSTOM_REQUEST_HEADERS?: string; + + /** + * The base path the app is served from, e.g. /ui/v2/login + */ + NEXT_PUBLIC_BASE_PATH: string; + + /** + * Optional: The application name shown in the login and invite emails + */ + NEXT_PUBLIC_APPLICATION_NAME?: string; + + /** + * Optional: override the redirect URI after successful login. + * If the value starts with "/", it will be used as a relative path and prepended with the host of the request (useful for rewrites). + * Otherwise, it will use the value as an absolute redirect URI. + * Takes precedence over organization settings. + */ + DEFAULT_REDIRECT_URI?: string; + + /** + * Optional: Comma-separated list of additional allowed origins for Server Actions. + * Origins should include the protocol, e.g., 'https://zitadel.com,http://localhost:3000'. + * If not set, it defaults to an empty list, allowing only same-origin requests. + */ + SERVER_ACTION_ALLOWED_ORIGINS?: string; + + /** + * Optional: Enable automatic code submission on page load. + * Set to "true" to auto-submit verification codes (e.g. email verification, Email OTP). + * Default behavior (undefined) requires users to click a Submit button, + * which is safer for environments with enterprise email link scanners. + */ + NEXT_PUBLIC_AUTO_SUBMIT_CODE?: string; + + /** + * Optional: Minimum number of seconds between two OTP SMS codes sent for the same session. + * Enforced by the Login UI's server action and shown as a countdown on the "Resend code" button, + * it keeps users from requesting codes in a loop. Defaults to 30, set to "0" to disable. + */ + OTP_SMS_RESEND_COOLDOWN_SECONDS?: string; + + /** + * Optional: Enable the SWR in-memory cache for API requests globally. + * Defaults to true. Set to "false" to disable completely. + */ + API_CACHE_ENABLED?: string; + + /** + * Optional: JSON string to configure the cache TTLs (in minutes) and size limits for specific backend API routes or global fallbacks. + * Example: '{"defaultMinutes": 15, "longMinutes": 60, "maxSize": 200, "getBrandingSettings": 120}' + * + * Properties: + * - \`defaultMinutes\`: The globally utilized default TTL in minutes (falls back to 15 if not set). + * - \`longMinutes\`: The TTL utilized string for long-cached routes, like branding/translation (falls back to 60 if not set). + * - \`maxSize\`: Maximum number of entries the in-memory cache may hold. Oldest entries are evicted when capacity is reached (defaults to 100). + * - \`[route_name]\`: Explicit overrides per specific API method (e.g., \`getHostedLoginTranslation\`). + */ + API_CACHE_CONFIG?: string; + + /** + * Optional: Disable the proxy's runtime CSP fetch from the ZITADEL API. + * Defaults to true (enabled). Set to "false" to skip fetching iframe origins + * and use a restrictive default CSP instead. + */ + CSP_FETCH_ENABLED?: string; + + /** + * Optional: Disable OpenTelemetry instrumentation. + * Set to "true" to bypass OTEL initialization. + * In local development (NODE_ENV=development), it is disabled by default unless explicitly set to "false". + */ + OTEL_SDK_DISABLED?: string; + } +} diff --git a/auth/ui/v2/apps/login/next.config.mjs b/auth/ui/v2/apps/login/next.config.mjs new file mode 100644 index 0000000..c90bc9c --- /dev/null +++ b/auth/ui/v2/apps/login/next.config.mjs @@ -0,0 +1,82 @@ +import createNextIntlPlugin from "next-intl/plugin"; + +const withNextIntl = createNextIntlPlugin(); + +const secureHeaders = [ + { + key: "Strict-Transport-Security", + value: "max-age=63072000; includeSubDomains; preload", + }, + { + key: "Referrer-Policy", + value: "origin-when-cross-origin", + }, + { + key: "X-Content-Type-Options", + value: "nosniff", + }, + { + key: "X-XSS-Protection", + value: "1; mode=block", + }, + { key: "X-Frame-Options", value: "deny" }, +]; + +/** @type {import('next').NextConfig} */ +const nextConfig = { + basePath: process.env.NEXT_PUBLIC_BASE_PATH, + output: process.env.NEXT_OUTPUT_MODE || undefined, + reactStrictMode: true, + typescript: { + // Since Next.js 16.3 the build type-checks every file matched by tsconfig.json, + // including unit tests, which vitest runs without type-checking. + tsconfigPath: "tsconfig.build.json", + }, + experimental: { + // Add React 19 compatibility optimizations + optimizePackageImports: ["@radix-ui/react-tooltip", "@heroicons/react"], + serverActions: { + ...(process.env.SERVER_ACTION_ALLOWED_ORIGINS + ? { allowedOrigins: process.env.SERVER_ACTION_ALLOWED_ORIGINS.split(",").map((o) => o.trim()) } + : {}), + }, + }, + // Packages that must not be bundled by webpack and should remain as external + // requires at runtime. These packages use native modules or have bundling + // incompatibilities. Keep this list in sync with package.json dependencies + // when adding new OpenTelemetry or logging packages. + serverExternalPackages: [ + 'winston', + '@opentelemetry/api', + '@opentelemetry/api-logs', + '@opentelemetry/sdk-node', + '@opentelemetry/sdk-metrics', + '@opentelemetry/sdk-logs', + '@opentelemetry/exporter-metrics-otlp-http', + '@opentelemetry/exporter-logs-otlp-http', + '@opentelemetry/exporter-prometheus', + '@opentelemetry/resources', + '@opentelemetry/semantic-conventions', + '@opentelemetry/auto-instrumentations-node', + '@opentelemetry/winston-transport', + '@opentelemetry/resource-detector-container', + '@opentelemetry/resource-detector-gcp', + ], + // Improve SSR stability - not actually needed for React 19 SSR issues + // onDemandEntries: { + // maxInactiveAge: 25 * 1000, + // pagesBufferLength: 2, + // }, + // Better error handling for production builds + poweredByHeader: false, + async headers() { + return [ + { + source: "/:path*", + headers: secureHeaders, + }, + ]; + }, +}; + +export default withNextIntl(nextConfig); diff --git a/auth/ui/v2/apps/login/package.json b/auth/ui/v2/apps/login/package.json new file mode 100644 index 0000000..9f6dc86 --- /dev/null +++ b/auth/ui/v2/apps/login/package.json @@ -0,0 +1,123 @@ +{ + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264", + "name": "@zitadel/login", + "private": true, + "type": "module", + "scripts": { + "build": "NEXT_OUTPUT_MODE=standalone next build && node checks/server-actions.mjs && cp -r public scripts/* .next/standalone/ && mv .next/standalone/apps/login/server.js .next/standalone/apps/login/next-server.js && cp .next/standalone/server.mjs .next/standalone/apps/login/server.js && cp -r .next/static .next/standalone/apps/login/.next/ && rm .next/standalone/apps/login/.env", + "build-vercel": "next build && node checks/server-actions.mjs", + "dev": "HOSTNAME=127.0.0.1 ./scripts/entrypoint.sh next dev", + "prod": "cd ./.next/standalone && HOSTNAME=127.0.0.1 ./entrypoint.sh node apps/login/server.js", + "lint-check-next": "eslint .", + "lint-check-prettier": "prettier --check .", + "lint-fix": "prettier --write .", + "test-unit": "vitest --run", + "test-dockerized": "vitest --run --config vitest.config.dockerized.ts", + "lint-staged": "lint-staged", + "clean": "rm -rf node_modules .next" + }, + "git": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*": "prettier --write --ignore-unknown" + }, + "browserslist": [ + "chrome 64", + "edge 79", + "firefox 67", + "opera 51", + "safari 12" + ], + "dependencies": { + "@braintree/sanitize-url": "^7.1.2", + "@connectrpc/connect": "^2.1.1", + "@connectrpc/connect-node": "^2.1.1", + "@headlessui/react": "^2.2.10", + "@heroicons/react": "^2.2.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.218.0", + "@opentelemetry/auto-instrumentations-node": "^0.76.0", + "@opentelemetry/resource-detector-container": "^0.8.8", + "@opentelemetry/resource-detector-gcp": "^0.53.0", + "@opentelemetry/resources": "^2.7.1", + "@opentelemetry/sdk-node": "^0.218.0", + "@opentelemetry/winston-transport": "^0.28.0", + "@radix-ui/react-tooltip": "^1.2.8", + "@tailwindcss/forms": "^0.5.11", + "clsx": "^2.1.1", + "copy-to-clipboard": "^3.3.3", + "escape-html": "^1.0.3", + "lru-cache": "^11.3.6", + "lucide-react": "^0.577.0", + "moment": "^2.31.0", + "next": "16.4.3", + "next-intl": "^4.11.2", + "next-themes": "^0.4.6", + "nice-grpc": "^2.1.16", + "qrcode.react": "^4.2.0", + "react": "19.2.6", + "react-dom": "19.2.6", + "react-hook-form": "^7.75.0", + "server-only": "^0.0.1", + "tinycolor2": "^1.6.0", + "uuid": "^14.0.0", + "winston": "^3.19.0" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@faker-js/faker": "^10.6.0", + "@next/eslint-plugin-next": "16.4.3", + "@opentelemetry/sdk-trace-base": "^2.7.1", + "@opentelemetry/sdk-trace-node": "^2.7.1", + "@otplib/core": "^12.0.1", + "@otplib/plugin-crypto": "^12.0.1", + "@otplib/plugin-thirty-two": "^12.0.1", + "@playwright/test": "^1.60.0", + "@tailwindcss/postcss": "^4.3.0", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.2", + "@types/escape-html": "^1.0.4", + "@types/node": "^25.7.0", + "@types/node-forge": "^1.3.14", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "@types/tinycolor2": "^1.4.6", + "@types/uuid": "^11.0.0", + "@typescript-eslint/eslint-plugin": "^8.59.3", + "@typescript-eslint/parser": "^8.59.3", + "@vercel/git-hooks": "^1.0.0", + "@vitejs/plugin-react": "^4.7.0", + "@zitadel/client": "workspace:*", + "@zitadel/proto": "workspace:*", + "concurrently": "^10.0.6", + "dotenv-cli": "^11.0.0", + "env-cmd": "^11.0.0", + "esbuild": "^0.28.1", + "eslint": "^10.3.0", + "eslint-config-prettier": "^10.1.8", + "eslint-import-resolver-typescript": "^4.4.4", + "eslint-plugin-cypress": "^4.3.0", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-react-hooks": "^7.1.1", + "gaxios": "^7.1.4", + "globals": "^17.6.0", + "grpc-tools": "^1.13.1", + "jsdom": "^26.1.0", + "lint-staged": "^16.4.0", + "node-forge": "^1.4.2", + "nodemon": "^3.1.14", + "postcss": "^8.5.14", + "prettier": "^3.8.3", + "prettier-plugin-organize-imports": "^4.3.0", + "prettier-plugin-tailwindcss": "^0.8.0", + "sass": "^1.99.0", + "start-server-and-test": "^3.0.4", + "tailwindcss": "^4.3.0", + "testcontainers": "^12.1.0", + "ts-proto": "^2.11.8", + "typescript": "^5.9.3", + "vite-tsconfig-paths": "^5.1.4", + "vitest": "^4.1.12" + } +} diff --git a/auth/ui/v2/apps/login/postcss.config.cjs b/auth/ui/v2/apps/login/postcss.config.cjs new file mode 100644 index 0000000..483f378 --- /dev/null +++ b/auth/ui/v2/apps/login/postcss.config.cjs @@ -0,0 +1,5 @@ +module.exports = { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; diff --git a/auth/ui/v2/apps/login/prettier.config.mjs b/auth/ui/v2/apps/login/prettier.config.mjs new file mode 100644 index 0000000..8981dd3 --- /dev/null +++ b/auth/ui/v2/apps/login/prettier.config.mjs @@ -0,0 +1,11 @@ +export default { + printWidth: 125, + tabWidth: 2, + useTabs: false, + semi: true, + singleQuote: false, + trailingComma: "all", + bracketSpacing: true, + arrowParens: "always", + plugins: ["prettier-plugin-organize-imports", "prettier-plugin-tailwindcss"], +}; diff --git a/auth/ui/v2/apps/login/project.json b/auth/ui/v2/apps/login/project.json new file mode 100644 index 0000000..648d7b0 --- /dev/null +++ b/auth/ui/v2/apps/login/project.json @@ -0,0 +1,147 @@ +{ + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "targets": { + "prod": { + "description": "Runs the Next.js Login application in production mode from the standalone build", + "continuous": true, + "dependsOn": ["build"], + "defaultConfiguration": "default", + "configurations": { + "default": {} + } + }, + "dev": { + "description": "Runs the Next.js Login application in development mode with hot-reloading", + "continuous": true, + "dependsOn": ["^build"] + }, + "build": { + "description": "Builds the Next.js Login application in standalone mode for production", + "cache": true, + "dependsOn": ["^build"], + "inputs": [ + "default", + "{workspaceRoot}/pnpm-lock.yaml", + "!{projectRoot}/.env.*", + "!{projectRoot}/.local.env", + "!{projectRoot}/acceptance/**/*", + "!{projectRoot}/dockerized/**/*" + ], + "outputs": ["{projectRoot}/.next/standalone"] + }, + "pack": { + "description": "Builds a local Docker image for the ZITADEL Login UI (zitadel/zitadel-login:local). Requires Docker daemon.", + "dependsOn": ["build"], + "command": "docker build -f apps/login/Dockerfile -t zitadel/zitadel-login:local apps/login", + "cache": false, + "inputs": [ + "default", + "{workspaceRoot}/pnpm-lock.yaml", + "{projectRoot}/Dockerfile", + "!{projectRoot}/.env.*", + "!{projectRoot}/acceptance/**/*" + ] + }, + "pack-fips": { + "description": "Builds a local FIPS-hardened Docker image for the ZITADEL Login UI (zitadel/zitadel-login:local-fips). Requires Docker daemon.", + "dependsOn": ["build"], + "command": "docker build -f apps/login/Dockerfile.fips -t zitadel/zitadel-login:local-fips apps/login", + "cache": false, + "inputs": [ + "default", + "{workspaceRoot}/pnpm-lock.yaml", + "{projectRoot}/Dockerfile.fips", + "!{projectRoot}/.env.*", + "!{projectRoot}/acceptance/**/*" + ] + }, + "build-vercel": { + "description": "Builds the Next.js Login application for Vercel deployment", + "cache": false, + "dependsOn": ["^build"], + "inputs": [ + "default", + "{workspaceRoot}/pnpm-lock.yaml", + "!{projectRoot}/.env.*", + "!{projectRoot}/.local.env", + "!{projectRoot}/acceptance/**/*", + "!{projectRoot}/dockerized/**/*" + ], + "outputs": ["{projectRoot}/.next/!(cache|standalone)/**"] + }, + "lint": { + "description": "Runs all linters", + "dependsOn": ["lint-check-*"] + }, + "lint-check-prettier": { + "description": "Checks code formatting with Prettier", + "cache": true, + "inputs": ["default"] + }, + "lint-check-next": { + "description": "Runs Next.js specific lint checks", + "cache": true, + "inputs": ["default"], + "dependsOn": ["^build"] + }, + "test": { + "description": "Runs all tests (unit, and dockerized)", + "dependsOn": ["test-unit", "test-dockerized"] + }, + "test-unit": { + "description": "Runs unit tests using Vitest", + "dependsOn": ["build"] + }, + "test-dockerized": { + "description": "Runs dockerized integration tests (OpenTelemetry and custom CA certificate tests)", + "dependsOn": ["build"], + "executor": "nx:run-commands", + "cache": true, + "inputs": ["default", "!{projectRoot}/acceptance/**/*", "!{projectRoot}/dockerized/**/output/**/*"], + "options": { + "cwd": "{projectRoot}", + "commands": ["pnpm vitest --run --config vitest.config.dockerized.ts"] + } + }, + "test-ssl": { + "description": "Runs TLS integration tests using testcontainers", + "dependsOn": ["build"], + "executor": "nx:run-commands", + "cache": true, + "inputs": ["default", "!{projectRoot}/acceptance/**/*", "!{projectRoot}/dockerized/**/output/**/*"], + "options": { + "cwd": "{projectRoot}", + "commands": ["pnpm vitest --run --config vitest.config.dockerized.ts dockerized/ssl"] + } + }, + "test-acceptance": { + "description": "Runs the Playwright acceptance test suite in apps/login/acceptance/ against a running ZITADEL stack. Requires LOGIN_BASE_URL, ZITADEL_API_URL, and ZITADEL_ADMIN_TOKEN to be set (or apps/login/.env.test.local to exist). Run the setup script at acceptance/setup/setup.sh first to seed config.", + "executor": "nx:run-commands", + "options": { + "cwd": "{projectRoot}", + "command": "pnpm exec playwright test --config acceptance/playwright.config.ts" + }, + "inputs": [ + "{projectRoot}/acceptance/**", + "!{projectRoot}/acceptance/playwright-report/**", + "!{projectRoot}/acceptance/test-results/**", + "{workspaceRoot}/pnpm-lock.yaml" + ] + }, + "pack-archive": { + "description": "Packages the standalone Login application build into an archive", + "dependsOn": ["build"], + "executor": "nx:run-commands", + "options": { + "parallel": false, + "env": { + "STANDALONE_DIR": "{projectRoot}/.next/standalone", + "PACK_DIR": "{workspaceRoot}/.artifacts/pack" + }, + "commands": ["mkdir -p ${PACK_DIR}", "tar -czf ${PACK_DIR}/zitadel-login.tar.gz -C ${STANDALONE_DIR} ."] + }, + "cache": true, + "outputs": ["{workspaceRoot}/.artifacts/pack/zitadel-login.tar.gz"] + } + } +} diff --git a/auth/ui/v2/apps/login/public/checkbox.svg b/auth/ui/v2/apps/login/public/checkbox.svg new file mode 100644 index 0000000..94a3298 --- /dev/null +++ b/auth/ui/v2/apps/login/public/checkbox.svg @@ -0,0 +1 @@ + diff --git a/auth/ui/v2/apps/login/public/favicon.ico b/auth/ui/v2/apps/login/public/favicon.ico new file mode 100644 index 0000000..a901edd Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon.ico differ diff --git a/auth/ui/v2/apps/login/public/favicon/android-chrome-192x192.png b/auth/ui/v2/apps/login/public/favicon/android-chrome-192x192.png new file mode 100644 index 0000000..f22bd44 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/android-chrome-192x192.png differ diff --git a/auth/ui/v2/apps/login/public/favicon/android-chrome-512x512.png b/auth/ui/v2/apps/login/public/favicon/android-chrome-512x512.png new file mode 100644 index 0000000..6987ed1 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/android-chrome-512x512.png differ diff --git a/auth/ui/v2/apps/login/public/favicon/apple-touch-icon.png b/auth/ui/v2/apps/login/public/favicon/apple-touch-icon.png new file mode 100644 index 0000000..4816102 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/apple-touch-icon.png differ diff --git a/auth/ui/v2/apps/login/public/favicon/browserconfig.xml b/auth/ui/v2/apps/login/public/favicon/browserconfig.xml new file mode 100644 index 0000000..75efb24 --- /dev/null +++ b/auth/ui/v2/apps/login/public/favicon/browserconfig.xml @@ -0,0 +1,9 @@ + + + + + + #000000 + + + diff --git a/auth/ui/v2/apps/login/public/favicon/favicon-16x16.png b/auth/ui/v2/apps/login/public/favicon/favicon-16x16.png new file mode 100644 index 0000000..4f45702 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/favicon-16x16.png differ diff --git a/auth/ui/v2/apps/login/public/favicon/favicon-32x32.png b/auth/ui/v2/apps/login/public/favicon/favicon-32x32.png new file mode 100644 index 0000000..a598da0 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/favicon-32x32.png differ diff --git a/auth/ui/v2/apps/login/public/favicon/favicon.ico b/auth/ui/v2/apps/login/public/favicon/favicon.ico new file mode 100644 index 0000000..af98450 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/favicon.ico differ diff --git a/auth/ui/v2/apps/login/public/favicon/mstile-150x150.png b/auth/ui/v2/apps/login/public/favicon/mstile-150x150.png new file mode 100644 index 0000000..ab51848 Binary files /dev/null and b/auth/ui/v2/apps/login/public/favicon/mstile-150x150.png differ diff --git a/auth/ui/v2/apps/login/public/favicon/site.webmanifest b/auth/ui/v2/apps/login/public/favicon/site.webmanifest new file mode 100644 index 0000000..567c2c6 --- /dev/null +++ b/auth/ui/v2/apps/login/public/favicon/site.webmanifest @@ -0,0 +1,19 @@ +{ + "name": "ZITADEL Login", + "short_name": "ZITADEL Login", + "icons": [ + { + "src": "/favicon/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/favicon/android-chrome-512x512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#000000", + "background_color": "#000000", + "display": "standalone" +} diff --git a/auth/ui/v2/apps/login/public/grid-dark.svg b/auth/ui/v2/apps/login/public/grid-dark.svg new file mode 100644 index 0000000..d467ad6 --- /dev/null +++ b/auth/ui/v2/apps/login/public/grid-dark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/auth/ui/v2/apps/login/public/grid-light.svg b/auth/ui/v2/apps/login/public/grid-light.svg new file mode 100644 index 0000000..114c118 --- /dev/null +++ b/auth/ui/v2/apps/login/public/grid-light.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/auth/ui/v2/apps/login/public/logo/zitadel-logo-solo-darkdesign.svg b/auth/ui/v2/apps/login/public/logo/zitadel-logo-solo-darkdesign.svg new file mode 100644 index 0000000..4a4e8be --- /dev/null +++ b/auth/ui/v2/apps/login/public/logo/zitadel-logo-solo-darkdesign.svg @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/auth/ui/v2/apps/login/public/logo/zitadel-logo-solo-lightdesign.svg b/auth/ui/v2/apps/login/public/logo/zitadel-logo-solo-lightdesign.svg new file mode 100644 index 0000000..33ea6b5 --- /dev/null +++ b/auth/ui/v2/apps/login/public/logo/zitadel-logo-solo-lightdesign.svg @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/auth/ui/v2/apps/login/public/zitadel-logo-dark.svg b/auth/ui/v2/apps/login/public/zitadel-logo-dark.svg new file mode 100644 index 0000000..6dcfe06 --- /dev/null +++ b/auth/ui/v2/apps/login/public/zitadel-logo-dark.svg @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/auth/ui/v2/apps/login/public/zitadel-logo-light.svg b/auth/ui/v2/apps/login/public/zitadel-logo-light.svg new file mode 100644 index 0000000..d48a5ee --- /dev/null +++ b/auth/ui/v2/apps/login/public/zitadel-logo-light.svg @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/auth/ui/v2/apps/login/screenshots/accounts.png b/auth/ui/v2/apps/login/screenshots/accounts.png new file mode 100644 index 0000000..a859114 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/accounts.png differ diff --git a/auth/ui/v2/apps/login/screenshots/accounts_jumpto.png b/auth/ui/v2/apps/login/screenshots/accounts_jumpto.png new file mode 100644 index 0000000..0fd126b Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/accounts_jumpto.png differ diff --git a/auth/ui/v2/apps/login/screenshots/collage.png b/auth/ui/v2/apps/login/screenshots/collage.png new file mode 100644 index 0000000..9d5a9c3 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/collage.png differ diff --git a/auth/ui/v2/apps/login/screenshots/idp.png b/auth/ui/v2/apps/login/screenshots/idp.png new file mode 100644 index 0000000..9bf58c6 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/idp.png differ diff --git a/auth/ui/v2/apps/login/screenshots/loginname.png b/auth/ui/v2/apps/login/screenshots/loginname.png new file mode 100644 index 0000000..342e607 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/loginname.png differ diff --git a/auth/ui/v2/apps/login/screenshots/mfa.png b/auth/ui/v2/apps/login/screenshots/mfa.png new file mode 100644 index 0000000..1fd73f2 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/mfa.png differ diff --git a/auth/ui/v2/apps/login/screenshots/mfaset.png b/auth/ui/v2/apps/login/screenshots/mfaset.png new file mode 100644 index 0000000..c00ee4e Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/mfaset.png differ diff --git a/auth/ui/v2/apps/login/screenshots/otp.png b/auth/ui/v2/apps/login/screenshots/otp.png new file mode 100644 index 0000000..3818a5a Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/otp.png differ diff --git a/auth/ui/v2/apps/login/screenshots/otpset.png b/auth/ui/v2/apps/login/screenshots/otpset.png new file mode 100644 index 0000000..f75c215 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/otpset.png differ diff --git a/auth/ui/v2/apps/login/screenshots/passkey.png b/auth/ui/v2/apps/login/screenshots/passkey.png new file mode 100644 index 0000000..7a5686c Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/passkey.png differ diff --git a/auth/ui/v2/apps/login/screenshots/password.png b/auth/ui/v2/apps/login/screenshots/password.png new file mode 100644 index 0000000..05cf874 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/password.png differ diff --git a/auth/ui/v2/apps/login/screenshots/password_change.png b/auth/ui/v2/apps/login/screenshots/password_change.png new file mode 100644 index 0000000..183de6d Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/password_change.png differ diff --git a/auth/ui/v2/apps/login/screenshots/password_set.png b/auth/ui/v2/apps/login/screenshots/password_set.png new file mode 100644 index 0000000..15b5ff4 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/password_set.png differ diff --git a/auth/ui/v2/apps/login/screenshots/register.png b/auth/ui/v2/apps/login/screenshots/register.png new file mode 100644 index 0000000..ba9f695 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/register.png differ diff --git a/auth/ui/v2/apps/login/screenshots/register_password.png b/auth/ui/v2/apps/login/screenshots/register_password.png new file mode 100644 index 0000000..31515bd Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/register_password.png differ diff --git a/auth/ui/v2/apps/login/screenshots/signedin.png b/auth/ui/v2/apps/login/screenshots/signedin.png new file mode 100644 index 0000000..f96ea17 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/signedin.png differ diff --git a/auth/ui/v2/apps/login/screenshots/u2f.png b/auth/ui/v2/apps/login/screenshots/u2f.png new file mode 100644 index 0000000..6b8eca0 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/u2f.png differ diff --git a/auth/ui/v2/apps/login/screenshots/u2fset.png b/auth/ui/v2/apps/login/screenshots/u2fset.png new file mode 100644 index 0000000..3711554 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/u2fset.png differ diff --git a/auth/ui/v2/apps/login/screenshots/verify.png b/auth/ui/v2/apps/login/screenshots/verify.png new file mode 100644 index 0000000..c13e6a3 Binary files /dev/null and b/auth/ui/v2/apps/login/screenshots/verify.png differ diff --git a/auth/ui/v2/apps/login/scripts/entrypoint.sh b/auth/ui/v2/apps/login/scripts/entrypoint.sh new file mode 100644 index 0000000..2da2aca --- /dev/null +++ b/auth/ui/v2/apps/login/scripts/entrypoint.sh @@ -0,0 +1,23 @@ +#!/bin/sh + +if [ -f /.env-file/.env ]; then + set -o allexport + . /.env-file/.env + set +o allexport +fi + +if [ -n "${ZITADEL_SERVICE_USER_TOKEN_FILE}" ]; then + echo "ZITADEL_SERVICE_USER_TOKEN_FILE=${ZITADEL_SERVICE_USER_TOKEN_FILE} is set. Awaiting file and reading token." + while [ ! -f "${ZITADEL_SERVICE_USER_TOKEN_FILE}" ]; do + sleep 2 + done + echo "token file found, reading token" + export ZITADEL_SERVICE_USER_TOKEN=$(cat "${ZITADEL_SERVICE_USER_TOKEN_FILE}") +fi + +# Log OTEL configuration on startup (if enabled) +if [ -n "${OTEL_EXPORTER_OTLP_ENDPOINT}" ]; then + echo "OTEL enabled: service=${OTEL_SERVICE_NAME:-zitadel-login}, endpoint=${OTEL_EXPORTER_OTLP_ENDPOINT}" +fi + +exec $@ diff --git a/auth/ui/v2/apps/login/scripts/healthcheck.mjs b/auth/ui/v2/apps/login/scripts/healthcheck.mjs new file mode 100644 index 0000000..e2ec461 --- /dev/null +++ b/auth/ui/v2/apps/login/scripts/healthcheck.mjs @@ -0,0 +1,28 @@ +import { getFips } from "node:crypto"; +import * as http from "node:http"; +import * as https from "node:https"; + +if (process.env.ZITADEL_FIPS_REQUIRED === "true" && getFips() !== 1) { + console.error("Healthcheck failed: FIPS mode required but not enabled"); + process.exit(1); +} + +const scheme = process.env.ZITADEL_TLS_ENABLED === "true" ? "https" : "http"; +const port = process.env.PORT || "3000"; +const url = new URL(process.argv[2] || `/ui/v2/login/healthy`, `${scheme}://localhost:${port}`); + +const get = scheme === "https" ? https.get : http.get; + +try { + const res = await new Promise((resolve, reject) => { + // Safe: localhost-only probe, self-signed certs expected + get(url, { rejectUnauthorized: false }, (res) => { + res.resume(); + resolve(res); + }).on("error", reject); + }); + process.exit(res.statusCode >= 200 && res.statusCode < 400 ? 0 : 1); +} catch (e) { + console.error("Healthcheck failed:", e); + process.exit(1); +} diff --git a/auth/ui/v2/apps/login/scripts/load-ssl-cert-dir.cjs b/auth/ui/v2/apps/login/scripts/load-ssl-cert-dir.cjs new file mode 100644 index 0000000..386e5a1 --- /dev/null +++ b/auth/ui/v2/apps/login/scripts/load-ssl-cert-dir.cjs @@ -0,0 +1,96 @@ +// Preload script that makes Node.js read CA certificates from SSL_CERT_DIR +// the same way Go's crypto/x509 does: every regular file in the directory is +// read regardless of filename. OpenSSL (used by Node when --use-openssl-ca +// is set) only reads files named with a subject-hash (e.g. "9d66eef0.0"), +// silently ignoring plain names like "corp-ca.crt". This script closes that +// gap so operators get identical behaviour across the Go backend and the +// Node.js login container. +// +// Usage: node --require /app/load-ssl-cert-dir.cjs ... +// +// The script is a no-op when SSL_CERT_DIR is not set. + +"use strict"; + +const tls = require("tls"); +const fs = require("fs"); +const path = require("path"); + +const sslCertDir = process.env.SSL_CERT_DIR; +if (!sslCertDir) { + return; // nothing to do — system trust via SSL_CERT_FILE is sufficient +} + +// Go splits on ":" and walks every directory in order. +const dirs = sslCertDir.split(":").filter(Boolean); +const certs = []; + +for (const dir of dirs) { + let entries; + try { + entries = fs.readdirSync(dir); + } catch { + // Directory doesn't exist or isn't readable — skip, like Go does. + continue; + } + + for (const entry of entries) { + const filePath = path.join(dir, entry); + + try { + const stat = fs.lstatSync(filePath); + + // Go's readUniqueDirectoryEntries skips symlinks whose target is a + // bare filename (no slash), because those are the c_rehash hash links + // pointing at files in the same directory. This avoids loading the + // same certificate twice. + if (stat.isSymbolicLink()) { + const target = fs.readlinkSync(filePath); + if (!target.includes("/")) { + continue; + } + } + + if (!stat.isFile() && !stat.isSymbolicLink()) { + continue; + } + + const content = fs.readFileSync(filePath, "utf8"); + if (content.includes("-----BEGIN CERTIFICATE-----")) { + certs.push(content); + } + } catch { + // Unreadable file — skip silently, matching Go behaviour. + continue; + } + } +} + +if (certs.length === 0) { + return; +} + +const origCreateSecureContext = tls.createSecureContext; + +tls.createSecureContext = function (options) { + const ctx = origCreateSecureContext.call(this, options); + + // Only inject directory CAs when the caller did not pass an explicit "ca" + // option. This matches Go's SystemCertPool() semantics: the extra certs + // are part of the system pool, not a forced override. + if (!options || !options.ca) { + for (let i = 0; i < certs.length; i++) { + try { + ctx.context.addCACert(certs[i]); + } catch (err) { + // Log once per bad cert, then remove it so subsequent contexts + // don't pay the cost of retrying a known-bad certificate. + console.error("load-ssl-cert-dir: skipping malformed certificate at index " + i + ": " + err.message); + certs.splice(i, 1); + i--; + } + } + } + + return ctx; +}; diff --git a/auth/ui/v2/apps/login/scripts/server.mjs b/auth/ui/v2/apps/login/scripts/server.mjs new file mode 100644 index 0000000..2722ca9 --- /dev/null +++ b/auth/ui/v2/apps/login/scripts/server.mjs @@ -0,0 +1,264 @@ +import { accessSync, constants, readFileSync } from "node:fs"; +import { request as httpRequest } from "node:http"; +import { createServer, request as httpsRequest } from "node:https"; +import { createRequire } from "node:module"; + +/** + * Parses a Go-style duration string into milliseconds. + * + * This uses the same format as Go's time.ParseDuration (e.g. "30s", "5m", + * "1m30s") to stay consistent with the ZITADEL backend, which uses + * time.Duration for its own ZITADEL_DATABASE_POSTGRES_AWAITINITIALCONN + * setting. Operators configuring both services use the same syntax. + * + * Valid units are "ms", "s", "m", and "h". + * Returns null if the string is empty, zero, or contains invalid syntax. + */ +function parseDuration(raw) { + const trimmed = raw.trim(); + if (!trimmed) return null; + + let totalMs = 0; + let remaining = trimmed; + const unitMap = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 }; + + while (remaining.length > 0) { + const match = remaining.match(/^(\d+)(ms|s|m|h)/); + if (!match) return null; + totalMs += parseInt(match[1], 10) * unitMap[match[2]]; + remaining = remaining.slice(match[0].length); + } + + return totalMs > 0 ? totalMs : null; +} + +/** + * Polls an HTTP(S) URL until it returns HTTP 200 or the deadline is reached. + */ +async function pollReady(url, timeoutMs) { + const parsedUrl = new URL(url); + const doRequest = parsedUrl.protocol === "https:" ? httpsRequest : httpRequest; + const deadline = Date.now() + timeoutMs; + + while (Date.now() < deadline) { + const ok = await new Promise((resolve) => { + const req = doRequest(parsedUrl, { method: "GET", timeout: 5_000, rejectUnauthorized: false }, (res) => { + res.resume(); + resolve(res.statusCode === 200); + }); + req.on("error", () => resolve(false)); + req.on("timeout", () => { + req.destroy(); + resolve(false); + }); + req.end(); + }); + + if (ok) return true; + + await new Promise((r) => setTimeout(r, 1_000)); + } + + return false; +} + +/** + * Waits for the ZITADEL API to become ready before starting the server. + * + * When ZITADEL_API_AWAITINITIALCONN is set (e.g. "60s", "5m", "120s"), this + * function blocks until GET {ZITADEL_API_URL}/debug/ready returns HTTP 200 + * or the timeout expires. This replaces the wait4x init container that was + * previously used in the Helm chart. + * + * If the timeout expires without a successful response, the process exits + * with code 1. + */ +async function awaitApiReady() { + const raw = process.env.ZITADEL_API_AWAITINITIALCONN; + if (!raw) return; + + const apiUrl = process.env.ZITADEL_API_URL; + if (!apiUrl) { + console.error("ZITADEL_API_AWAITINITIALCONN is set but ZITADEL_API_URL is not configured."); + process.exit(1); + } + + const timeoutMs = parseDuration(raw); + if (timeoutMs === null) { + console.error( + `Invalid ZITADEL_API_AWAITINITIALCONN value "${raw}". Expected a Go-style duration like "30s", "5m", or "1m30s".`, + ); + process.exit(1); + } + + const readyUrl = new URL("/debug/ready", apiUrl).toString(); + console.log(`Waiting up to ${raw} for API to be ready at ${readyUrl} ...`); + + const ok = await pollReady(readyUrl, timeoutMs); + if (ok) { + console.log("API is ready."); + } else { + console.error(`Timed out after ${raw} waiting for API readiness at ${readyUrl}`); + process.exit(1); + } +} + +await awaitApiReady(); + +if (process.env.ZITADEL_TLS_ENABLED !== "true") { + // The build script must rename the Next.js-generated server.js to next-server.js. + // Validate that the file exists before importing to provide a clearer error if the build step fails. + try { + accessSync(new URL("./next-server.js", import.meta.url), constants.R_OK); + } catch (err) { + console.error( + 'Unable to find or read "./next-server.js". Ensure the build script has renamed Next.js\'s server.js to next-server.js.', + err, + ); + process.exit(1); + } + await import("./next-server.js"); +} else { + const certPath = process.env.ZITADEL_TLS_CERTPATH; + const keyPath = process.env.ZITADEL_TLS_KEYPATH; + + if (!certPath || !keyPath) { + console.error( + "ZITADEL_TLS_ENABLED is set to true but ZITADEL_TLS_CERTPATH or ZITADEL_TLS_KEYPATH are missing. Both must be set when TLS is enabled.", + ); + process.exit(1); + } + + try { + accessSync(certPath, constants.R_OK); + } catch (err) { + console.error(`Certificate file is not readable: ${certPath}`, err); + process.exit(1); + } + + try { + accessSync(keyPath, constants.R_OK); + } catch (err) { + console.error(`Key file is not readable: ${keyPath}`, err); + process.exit(1); + } + + const cert = readFileSync(certPath); + const key = readFileSync(keyPath); + + // Requires Node.js >= 20.11.0 (or >= 21.2.0) for import.meta.dirname support. + const appDir = import.meta.dirname; + + const requiredServerFilesPath = new URL(".next/required-server-files.json", import.meta.url); + + let requiredServerFiles; + try { + accessSync(requiredServerFilesPath, constants.R_OK); + const requiredServerFilesContent = readFileSync(requiredServerFilesPath, "utf8"); + requiredServerFiles = JSON.parse(requiredServerFilesContent); + } catch (err) { + console.error( + "Failed to load .next/required-server-files.json. The Next.js build may be incomplete or the file may contain invalid JSON.", + err, + ); + process.exit(1); + } + process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(requiredServerFiles.config); + + process.env.NODE_ENV = "production"; + process.chdir(appDir); + + const currentPort = parseInt(process.env.PORT, 10) || 3000; + const hostname = process.env.HOSTNAME || "0.0.0.0"; + + // KEEP_ALIVE_TIMEOUT is expected to be in milliseconds. + // Reject values that are negative or unreasonably large to avoid resource issues. + const MAX_KEEP_ALIVE_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes + + let keepAliveTimeout = parseInt(process.env.KEEP_ALIVE_TIMEOUT, 10); + if ( + Number.isNaN(keepAliveTimeout) || + !Number.isFinite(keepAliveTimeout) || + keepAliveTimeout < 0 || + keepAliveTimeout > MAX_KEEP_ALIVE_TIMEOUT_MS + ) { + keepAliveTimeout = undefined; + } + + const require = createRequire(import.meta.url); + require("next"); + // NOTE: This imports an internal Next.js API that is not part of the public, semver-stable surface. + // - Verified with Next.js version 15.5.10 (see package.json). + // - This may break on Next.js upgrades; if Next.js is updated, re-check that + // `next/dist/server/lib/start-server` still exists and that `getRequestHandlers` behaves as expected. + // - This is currently required to support HTTPS with self-signed certificates in production mode, + // as there is no equivalent public API in Next.js at this time. + const { getRequestHandlers } = require("next/dist/server/lib/start-server"); + + const httpsServer = createServer({ key, cert }); + + if (keepAliveTimeout !== undefined) { + httpsServer.keepAliveTimeout = keepAliveTimeout; + } + + const { requestHandler, upgradeHandler } = await getRequestHandlers({ + dir: appDir, + port: currentPort, + isDev: false, + server: httpsServer, + hostname, + keepAliveTimeout, + }); + + httpsServer.on("request", async (req, res) => { + try { + await requestHandler(req, res); + } catch (err) { + res.statusCode = 500; + res.end("Internal Server Error"); + console.error(`Failed to handle request for ${req.url}`); + console.error(err); + } + }); + + httpsServer.on("upgrade", async (req, socket, head) => { + try { + await upgradeHandler(req, socket, head); + } catch (err) { + socket.destroy(); + console.error(`Failed to handle upgrade for ${req.url}`); + console.error(err); + } + }); + + httpsServer.on("error", (err) => { + console.error("Failed to start HTTPS server"); + console.error(err); + process.exit(1); + }); + + let cleanupStarted = false; + const cleanup = () => { + if (cleanupStarted) return; + cleanupStarted = true; + httpsServer.close((err) => { + if (err) { + console.error(err); + process.exit(1); + } else { + process.exit(0); + } + }); + }; + + if (!process.env.NEXT_MANUAL_SIG_HANDLE) { + process.on("SIGINT", cleanup); + process.on("SIGTERM", cleanup); + } + + httpsServer.listen(currentPort, hostname, () => { + const formattedHost = hostname.includes(":") ? `[${hostname}]` : hostname; + const readyUrl = new URL(`https://${formattedHost}:${currentPort}`); + console.log(`> Ready on ${readyUrl}`); + }); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/accounts/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/accounts/page.tsx new file mode 100644 index 0000000..ba4c93b --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/accounts/page.tsx @@ -0,0 +1,135 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SessionsList } from "@/components/sessions-list"; +import { Translated } from "@/components/translated"; +import { getAllSessions } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg, listSessions, ServiceConfig } from "@/lib/server/zitadel"; +import { UserPlusIcon } from "@heroicons/react/24/outline"; +import { create } from "@zitadel/client"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Session, SessionSchema } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +// import { getLocale } from "next-intl/server"; +import { headers } from "next/headers"; +import Link from "next/link"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("accounts"); + return { title: t("title") }; +} + +async function loadSessions({ serviceConfig, organization }: { serviceConfig: ServiceConfig; organization?: string }) { + // Deliberately no cleanup: expired cookie entries are still listed (as invalid + // accounts) so the user can re-authenticate with one click, like Login V1. + const sessionCookies = await getAllSessions(); + + if (!sessionCookies || !sessionCookies.length) { + console.info("No session cookie found."); + return []; + } + + // listSessions is a plain search: ids of terminated or unknown sessions are + // simply absent from the response, it does not fail. Transport failures are + // deliberately not caught here, they must surface instead of downgrading + // live sessions to invalid cards. + const ids = sessionCookies.map((s) => s.id).filter((id) => !!id) as string[]; + let liveSessions: Session[] = []; + if (ids.length) { + const response = await listSessions({ serviceConfig, ids }); + liveSessions = response?.sessions ?? []; + } + + // For cookie entries whose server-side session no longer exists (e.g. after + // an RP-initiated logout) synthesize an invalid Session so the account stays + // selectable and the user can re-authenticate with one click. + const liveIds = new Set(liveSessions.map((s) => s.id)); + const synthesized: Session[] = sessionCookies + .filter((c) => !!c.id && !!c.loginName && !liveIds.has(c.id)) + .map((c) => + create(SessionSchema, { + id: c.id, + factors: { + user: { + loginName: c.loginName, + // No displayName: the cookie does not carry one, and reusing the + // loginName would render it twice and break the avatar initials. + organizationId: c.organization ?? "", + }, + }, + }), + ); + + let sessions = [...liveSessions, ...synthesized]; + if (organization) { + sessions = sessions.filter((s) => s.factors?.user?.organizationId === organization); + } + + return sessions; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const requestId = searchParams?.requestId; + const organization = searchParams?.organization; + const orgDomain = searchParams?.orgDomain; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + let sessions = await loadSessions({ serviceConfig, organization }); + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + const params = new URLSearchParams(); + + if (requestId) { + params.append("requestId", requestId); + } + + if (organization) { + params.append("organization", organization); + } + + if (orgDomain) { + params.append("orgDomain", orgDomain); + } + + return ( + +
+

+ +

+

+ +

+
+ +
+
+ + +
+
+ +
+ + + +
+ +
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/authenticator/set/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/authenticator/set/page.tsx new file mode 100644 index 0000000..82f68ad --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/authenticator/set/page.tsx @@ -0,0 +1,202 @@ +import { Alert } from "@/components/alert"; +import { BackButton } from "@/components/back-button"; +import { ChooseAuthenticatorToSetup } from "@/components/choose-authenticator-to-setup"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SignInWithIdp } from "@/components/sign-in-with-idp"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { checkUserVerification } from "@/lib/server/verify-helper"; +import { + getActiveIdentityProviders, + getBrandingSettings, + getLoginSettings, + getSession, + getUserByID, + listAuthenticationMethodTypes, +} from "@/lib/server/zitadel"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +// import { getLocale } from "next-intl/server"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("authenticator"); + return { title: t("title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { loginName, requestId, organization, sessionId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const sessionWithData = sessionId + ? await loadSessionById(sessionId, organization) + : await loadSessionByLoginname(loginName, organization); + + async function getAuthMethodsAndUser(session?: Session) { + const userId = session?.factors?.user?.id; + + if (!userId) { + throw Error("Could not get user id from session"); + } + + const methods = await listAuthenticationMethodTypes({ serviceConfig, userId }); + const user = await getUserByID({ serviceConfig, userId }); + + const humanUser = user.user?.type.case === "human" ? user.user?.type.value : undefined; + + return { + id: session?.id, + factors: session?.factors, + authMethods: methods.authMethodTypes ?? [], + phoneVerified: humanUser?.phone?.isVerified ?? false, + emailVerified: humanUser?.email?.isVerified ?? false, + expirationDate: session?.expirationDate, + }; + } + + async function loadSessionByLoginname(loginName?: string, organization?: string) { + const session = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + + return getAuthMethodsAndUser(session); + } + + async function loadSessionById(sessionId: string, organization?: string) { + const recent = await getSessionCookieById({ sessionId, organization }); + + if (!recent) { + return undefined; + } + + const sessionResponse = await getSession({ serviceConfig, sessionId: recent.id, sessionToken: recent.token }); + return getAuthMethodsAndUser(sessionResponse.session); + } + + if (!sessionWithData || !sessionWithData.factors || !sessionWithData.factors.user) { + return ( + + {/* context was provided but the session could not be resolved (cookie missing, invalid or expired) */} + + + ); + } + + const branding = await getBrandingSettings({ serviceConfig, organization: sessionWithData.factors.user?.organizationId }); + + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: sessionWithData.factors.user?.organizationId, + }); + + // check if user was verified recently + const isUserVerified = await checkUserVerification(sessionWithData.factors.user?.id); + + if (!isUserVerified) { + const params = new URLSearchParams({ + loginName: sessionWithData.factors.user.loginName as string, + invite: "true", + send: "true", // set this to true to request a new code immediately + }); + + if (requestId) { + params.append("requestId", requestId); + } + + if (organization || sessionWithData.factors.user.organizationId) { + params.append("organization", organization ?? (sessionWithData.factors.user.organizationId as string)); + } + + redirect(`/verify?` + params); + } + + const { identityProviders } = await getActiveIdentityProviders({ + serviceConfig, + orgId: sessionWithData.factors?.user?.organizationId, + linking_allowed: true, + }); + + const params = new URLSearchParams({ + initial: "true", // defines that a code is not required and is therefore not shown in the UI + }); + + if (sessionWithData.factors?.user?.loginName) { + params.set("loginName", sessionWithData.factors?.user?.loginName); + } + + if (sessionWithData.factors?.user?.organizationId) { + params.set("organization", sessionWithData.factors?.user?.organizationId); + } + + if (requestId) { + params.set("requestId", requestId); + } + + return ( + +
+

+ +

+ +

+ +

+ + +
+ +
+ {loginSettings && ( + + )} + + {loginSettings?.allowExternalIdp && !!identityProviders.length && ( + <> +
+

+ +

+
+ + + + )} + +
+ + +
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/device/consent/page.test.tsx b/auth/ui/v2/apps/login/src/app/(login)/device/consent/page.test.tsx new file mode 100644 index 0000000..0c39651 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/device/consent/page.test.tsx @@ -0,0 +1,116 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import Page from "./page"; + +const { redirect } = vi.hoisted(() => ({ + redirect: vi.fn((url: string) => { + throw new Error(`NEXT_REDIRECT ${url}`); + }), +})); + +vi.mock("next/navigation", () => ({ redirect })); + +vi.mock("@/lib/server/zitadel", () => ({ + getBrandingSettings: vi.fn(), + getDefaultOrg: vi.fn(), + getDeviceAuthorizationRequest: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + loadMostRecentSession: vi.fn(), + loadSessionById: vi.fn(), +})); + +vi.mock("@/lib/server/device-code-check", () => ({ + checkDeviceCodeCheckCookie: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +vi.mock("@/components/consent", () => ({ ConsentScreen: vi.fn(() => null) })); +vi.mock("@/components/user-avatar", () => ({ UserAvatar: vi.fn(() => null) })); +vi.mock("@/components/dynamic-theme", () => ({ DynamicTheme: ({ children }: { children: React.ReactNode }) => children })); +vi.mock("@/components/translated", () => ({ Translated: vi.fn(() => null) })); + +const session = { + id: "session-1", + factors: { user: { id: "user-1", loginName: "user@example.com", displayName: "User", organizationId: "org-1" } }, +}; + +describe("device consent page", () => { + let checkDeviceCodeCheckCookie: any; + let loadSessionById: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const zitadel = await import("@/lib/server/zitadel"); + const sessionLib = await import("@/lib/server/session"); + const deviceCodeCheck = await import("@/lib/server/device-code-check"); + + checkDeviceCodeCheckCookie = vi.mocked(deviceCodeCheck.checkDeviceCodeCheckCookie); + loadSessionById = vi.mocked(sessionLib.loadSessionById); + + checkDeviceCodeCheckCookie.mockResolvedValue(true); + loadSessionById.mockResolvedValue(session); + vi.mocked(sessionLib.loadMostRecentSession).mockResolvedValue(session as any); + vi.mocked(zitadel.getDeviceAuthorizationRequest).mockResolvedValue({ + deviceAuthorizationRequest: { id: "device-request-1", appName: "My Device", scope: ["openid"] }, + } as any); + vi.mocked(zitadel.getBrandingSettings).mockResolvedValue({} as any); + vi.mocked(zitadel.getDefaultOrg).mockResolvedValue(null as any); + }); + + afterEach(cleanup); + + test("redirects to the code entry page when the device code was not entered in this browser", async () => { + checkDeviceCodeCheckCookie.mockResolvedValue(false); + + await expect( + Page({ searchParams: Promise.resolve({ requestId: "device_ABCD-1234", sessionId: "session-1" }) }), + ).rejects.toThrow("NEXT_REDIRECT"); + + expect(checkDeviceCodeCheckCookie).toHaveBeenCalledWith("ABCD-1234"); + expect(redirect).toHaveBeenCalledWith("/device?user_code=ABCD-1234"); + expect(loadSessionById).not.toHaveBeenCalled(); + }); + + test("redirects to the login funnel when the session is stale", async () => { + loadSessionById.mockResolvedValue(undefined); + + await expect( + Page({ searchParams: Promise.resolve({ requestId: "device_ABCD-1234", sessionId: "session-1" }) }), + ).rejects.toThrow("NEXT_REDIRECT"); + + expect(redirect).toHaveBeenCalledWith("/loginname?requestId=device_ABCD-1234"); + }); + + test("passes the displayed session to the consent screen", async () => { + const { ConsentScreen } = await import("@/components/consent"); + const { UserAvatar } = await import("@/components/user-avatar"); + + render( + await Page({ + searchParams: Promise.resolve({ + requestId: "device_ABCD-1234", + sessionId: "session-1", + loginName: "other@example.com", + organization: "org-1", + }), + }), + ); + + // React 19 calls function components with (props, undefined) + expect(ConsentScreen).toHaveBeenCalledWith( + expect.objectContaining({ userCode: "ABCD-1234", sessionId: "session-1", organization: "org-1" }), + undefined, + ); + expect(ConsentScreen).toHaveBeenCalledWith(expect.not.objectContaining({ loginName: expect.anything() }), undefined); + expect(UserAvatar).toHaveBeenCalledWith(expect.objectContaining({ loginName: "user@example.com" }), undefined); + }); +}); diff --git a/auth/ui/v2/apps/login/src/app/(login)/device/consent/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/device/consent/page.tsx new file mode 100644 index 0000000..33a4e0a --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/device/consent/page.tsx @@ -0,0 +1,107 @@ +import { ConsentScreen } from "@/components/consent"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { checkDeviceCodeCheckCookie } from "@/lib/server/device-code-check"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession, loadSessionById } from "@/lib/server/session"; +import { getBrandingSettings, getDefaultOrg, getDeviceAuthorizationRequest } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const requestId = searchParams?.requestId; + const sessionId = searchParams?.sessionId; + const loginName = searchParams?.loginName; + const organization = searchParams?.organization; + + if (!requestId || !requestId.startsWith("device_")) { + return ( +
+ +
+ ); + } + + const userCode = requestId.replace("device_", ""); + + // consent can only be given in the browser that entered the user code + if (!(await checkDeviceCodeCheckCookie(userCode))) { + return redirect("/device?" + new URLSearchParams({ user_code: userCode })); + } + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { deviceAuthorizationRequest } = await getDeviceAuthorizationRequest({ serviceConfig, userCode }); + + if (!deviceAuthorizationRequest) { + return ( +
+ +
+ ); + } + + const sessionFactors = sessionId + ? await loadSessionById(serviceConfig, sessionId, organization) + : await loadMostRecentSession({ serviceConfig, sessionParams: { loginName, organization } }); + + // consent is only given by an authenticated user, so send the user through the login funnel first + if (!sessionFactors) { + const loginParams = new URLSearchParams({ requestId }); + + if (organization) { + loginParams.append("organization", organization); + } + + return redirect(`/loginname?` + loginParams); + } + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + return ( + +
+

+ +

+ +

+ +

+ + +
+ +
+ +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/device/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/device/page.tsx new file mode 100644 index 0000000..e1bffee --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/device/page.tsx @@ -0,0 +1,51 @@ +import { DeviceCodeForm } from "@/components/device-code-form"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("device"); + return { title: t("usercode.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const userCode = searchParams?.user_code; + const organization = searchParams?.organization; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + return ( + +
+

+ +

+

+ +

+
+ +
+ +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/error.tsx b/auth/ui/v2/apps/login/src/app/(login)/error.tsx new file mode 100644 index 0000000..d14150a --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/error.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { Boundary } from "@/components/boundary"; +import { Button } from "@/components/button"; +import { Translated } from "@/components/translated"; +import { useEffect } from "react"; + +export default function Error({ error, reset }: any) { + useEffect(() => { + console.log("logging error:", error); + }, [error]); + + return ( + +
+
+ Error: {error?.message} +
+
+ +
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/account-not-found/page.test.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/account-not-found/page.test.tsx new file mode 100644 index 0000000..cc460b4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/account-not-found/page.test.tsx @@ -0,0 +1,45 @@ +import Link from "next/link"; +import { isValidElement, ReactNode } from "react"; +import { describe, expect, test, vi } from "vitest"; +import Page from "./page"; + +vi.mock("@/lib/server/zitadel", () => ({ + getBrandingSettings: vi.fn(async () => ({})), + getDefaultOrg: vi.fn(async () => null), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +function findLinks(node: ReactNode): { href: string }[] { + if (Array.isArray(node)) return node.flatMap(findLinks); + if (!isValidElement<{ children?: ReactNode; href: string }>(node)) return []; + return [...(node.type === Link ? [node.props] : []), ...findLinks(node.props.children)]; +} + +const render = (searchParams: Record) => Page({ searchParams: Promise.resolve(searchParams) }); + +describe("account-not-found page", () => { + test("renders no back link for an external postErrorRedirectUrl", async () => { + const links = findLinks(await render({ postErrorRedirectUrl: "https://evil.example" })); + expect(links).toEqual([]); + }); + + test("renders no back link without postErrorRedirectUrl", async () => { + expect(findLinks(await render({}))).toEqual([]); + }); + + test("renders the back link for /loginname", async () => { + const links = findLinks(await render({ postErrorRedirectUrl: "/loginname" })); + expect(links.map((l) => l.href)).toEqual(["/loginname"]); + }); +}); diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/account-not-found/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/account-not-found/page.tsx new file mode 100644 index 0000000..2f917c3 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/account-not-found/page.tsx @@ -0,0 +1,62 @@ +import { Alert, AlertType } from "@/components/alert"; +import { Button } from "@/components/button"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { isAllowedPostErrorRedirectUrl } from "@/lib/client-utils"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; +import Link from "next/link"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("idp"); + return { title: t("accountNotFound.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + const { organization, postErrorRedirectUrl } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + return ( + +
+

+ +

+

+ +

+ +
+ + + +
+ + {isAllowedPostErrorRedirectUrl(postErrorRedirectUrl) && ( + + + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/complete-registration/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/complete-registration/page.tsx new file mode 100644 index 0000000..e07bbd1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/complete-registration/page.tsx @@ -0,0 +1,57 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { RegisterFormIDPIncomplete } from "@/components/register-form-idp-incomplete"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings } from "@/lib/server/zitadel"; +import { headers } from "next/headers"; + +/** + * Complete registration page - shown when manual user registration is required + */ +export default async function CompleteRegistrationPage(props: { + searchParams: Promise>; + params: Promise<{ provider: string }>; +}) { + const searchParams = await props.searchParams; + const { id, token, requestId, organization, idpUserName, givenName, familyName, email, flowFingerprint } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + if (!id || !token || !organization) { + throw new Error("Missing required parameters"); + } + + return ( + +
+

+ +

+

+ +

+
+ +
+ +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/failure/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/failure/page.tsx new file mode 100644 index 0000000..d3dfb4f --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/failure/page.tsx @@ -0,0 +1,93 @@ +import { Alert, AlertType } from "@/components/alert"; +import { ChooseAuthenticatorToLogin } from "@/components/choose-authenticator-to-login"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { isKnownIdpError } from "@/lib/idp-errors"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getLoginSettings, getUserByID, listAuthenticationMethodTypes } from "@/lib/server/zitadel"; +import { HumanUser, User } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { headers } from "next/headers"; + +export default async function Page(props: { + searchParams: Promise>; + params: Promise<{ provider: string }>; +}) { + const searchParams = await props.searchParams; + + const { organization, userId, error } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const loginSettings = await getLoginSettings({ serviceConfig, organization }); + + let authMethods: AuthenticationMethodType[] = []; + let user: User | undefined = undefined; + let human: HumanUser | undefined = undefined; + + const params = new URLSearchParams({}); + if (organization) { + params.set("organization", organization); + } + if (userId) { + params.set("userId", userId); + } + + if (userId) { + const userResponse = await getUserByID({ serviceConfig, userId }); + if (userResponse) { + user = userResponse.user; + if (user?.type.case === "human") { + human = user.type.value as HumanUser; + } + + if (user?.preferredLoginName) { + params.set("loginName", user.preferredLoginName); + } + } + + const authMethodsResponse = await listAuthenticationMethodTypes({ serviceConfig, userId }); + if (authMethodsResponse.authMethodTypes) { + authMethods = authMethodsResponse.authMethodTypes; + } + } + + return ( + +
+

+ +

+
+ +
+ + + + {isKnownIdpError(error) &&

{error}

} + + {userId && authMethods.length && ( + <> + {user && human && ( + + )} + + + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/linking-failed/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/linking-failed/page.tsx new file mode 100644 index 0000000..672a5ee --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/linking-failed/page.tsx @@ -0,0 +1,36 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { isKnownIdpError } from "@/lib/idp-errors"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings } from "@/lib/server/zitadel"; +import { headers } from "next/headers"; + +/** + * Linking failed page - shown when IDP linking fails + */ +export default async function LinkingFailedPage(props: { + searchParams: Promise>; + params: Promise<{ provider: string }>; +}) { + const searchParams = await props.searchParams; + const { organization, error } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + return ( + +
+

+ +

+

+ +

+ {isKnownIdpError(error) &&

{error}

} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/process/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/process/page.tsx new file mode 100644 index 0000000..119f8d4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/process/page.tsx @@ -0,0 +1,56 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { IdpProcessHandler } from "@/components/idp-process-handler"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { headers } from "next/headers"; + +/** + * This page handles the initial IDP callback with the single-use token. + * It delegates to a client component which calls the server action. + * The client component is needed so that cookies can be set properly. + */ +export default async function ProcessPage(props: { + searchParams: Promise>; + params: Promise<{ provider: string }>; +}) { + const params = await props.params; + const searchParams = await props.searchParams; + + const { provider } = params; + const { id, token, requestId, organization, link, postErrorRedirectUrl, linkToSessionId, flowFingerprint } = searchParams; + + // Validate required parameters before passing to client component + if (!id || !token) { + throw new Error("Missing required IDP callback parameters"); + } + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + return ( + + + + ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/registration-failed/page.test.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/registration-failed/page.test.tsx new file mode 100644 index 0000000..6048016 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/registration-failed/page.test.tsx @@ -0,0 +1,45 @@ +import Link from "next/link"; +import { isValidElement, ReactNode } from "react"; +import { describe, expect, test, vi } from "vitest"; +import Page from "./page"; + +vi.mock("@/lib/server/zitadel", () => ({ + getBrandingSettings: vi.fn(async () => ({})), + getDefaultOrg: vi.fn(async () => null), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +function findLinks(node: ReactNode): { href: string }[] { + if (Array.isArray(node)) return node.flatMap(findLinks); + if (!isValidElement<{ children?: ReactNode; href: string }>(node)) return []; + return [...(node.type === Link ? [node.props] : []), ...findLinks(node.props.children)]; +} + +const render = (searchParams: Record) => Page({ searchParams: Promise.resolve(searchParams) }); + +describe("registration-failed page", () => { + test("renders no back link for an external postErrorRedirectUrl", async () => { + const links = findLinks(await render({ postErrorRedirectUrl: "https://evil.example" })); + expect(links).toEqual([]); + }); + + test("renders no back link without postErrorRedirectUrl", async () => { + expect(findLinks(await render({}))).toEqual([]); + }); + + test("renders the back link for /loginname", async () => { + const links = findLinks(await render({ postErrorRedirectUrl: "/loginname" })); + expect(links.map((l) => l.href)).toEqual(["/loginname"]); + }); +}); diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/registration-failed/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/registration-failed/page.tsx new file mode 100644 index 0000000..63152b0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/[provider]/registration-failed/page.tsx @@ -0,0 +1,62 @@ +import { Alert, AlertType } from "@/components/alert"; +import { Button } from "@/components/button"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { isAllowedPostErrorRedirectUrl } from "@/lib/client-utils"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; +import Link from "next/link"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("idp"); + return { title: t("registrationFailed.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + const { organization, postErrorRedirectUrl } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + return ( + +
+

+ +

+

+ +

+ +
+ + + +
+ + {isAllowedPostErrorRedirectUrl(postErrorRedirectUrl) && ( + + + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/ldap/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/ldap/page.tsx new file mode 100644 index 0000000..fb458b4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/ldap/page.tsx @@ -0,0 +1,57 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { LDAPUsernamePasswordForm } from "@/components/ldap-username-password-form"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { headers } from "next/headers"; + +export default async function Page(props: { + searchParams: Promise>; + params: Promise<{ provider: string }>; +}) { + const searchParams = await props.searchParams; + const { idpId, organization, link, requestId, postErrorRedirectUrl, linkToSessionId } = searchParams; + + if (!idpId) { + throw new Error("No idpId provided in searchParams"); + } + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + // return login failed if no linking or creation is allowed and no user was found + return ( + +
+

+ +

+

+ +

+
+ +
+ +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/idp/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/idp/page.tsx new file mode 100644 index 0000000..152d360 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/idp/page.tsx @@ -0,0 +1,54 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SignInWithIdp } from "@/components/sign-in-with-idp"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getActiveIdentityProviders, getBrandingSettings } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("idp"); + return { title: t("title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const requestId = searchParams?.requestId; + const organization = searchParams?.organization; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const identityProviders = await getActiveIdentityProviders({ serviceConfig, orgId: organization }).then((resp) => { + return resp.identityProviders; + }); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + return ( + +
+

+ +

+

+ +

+
+ +
+ {!!identityProviders?.length && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/layout.tsx b/auth/ui/v2/apps/login/src/app/(login)/layout.tsx new file mode 100644 index 0000000..99317af --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/layout.tsx @@ -0,0 +1,86 @@ +import "@/styles/globals.scss"; + +import { BackgroundWrapper } from "@/components/background-wrapper"; +import { LanguageProvider } from "@/components/language-provider"; +import { LanguageSwitcher } from "@/components/language-switcher"; +import { Skeleton } from "@/components/skeleton"; +import { ThemeProvider } from "@/components/theme-provider"; +import ThemeSwitch from "@/components/theme-switch"; +import { LANGS, getLanguage } from "@/lib/i18n"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getAllowedLanguages } from "@/lib/server/zitadel"; +import * as Tooltip from "@radix-ui/react-tooltip"; +import type { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { Lato } from "next/font/google"; +import { headers } from "next/headers"; +import React, { Suspense } from "react"; + +const lato = Lato({ + weight: ["400", "700", "900"], + subsets: ["latin"], +}); + +export async function generateMetadata(): Promise { + const t = await getTranslations("common"); + return { title: t("title") }; +} + +export default async function RootLayout({ children }: { children: React.ReactNode }) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let languages = LANGS; + try { + const settings = await getAllowedLanguages({ serviceConfig }); + if (settings.allowedLanguages?.length) { + languages = settings.allowedLanguages + .filter((code) => LANGS.find((l) => l.code === code)) + .map((code) => getLanguage(code)); + } + } catch (e) { + console.error("Failed to load supported languages", e); + } + + return ( + + + + + + +
+ +
+
+
+ +
+
+ + } + > + + +
+
{children}
+
+ + +
+
+
+
+
+
+
+ + + ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/loginname/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/loginname/page.tsx new file mode 100644 index 0000000..72fff97 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/loginname/page.tsx @@ -0,0 +1,94 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SignInWithIdp } from "@/components/sign-in-with-idp"; +import { Translated } from "@/components/translated"; +import { UsernameForm } from "@/components/username-form"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getActiveIdentityProviders, getBrandingSettings, getDefaultOrg, getLoginSettings } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("loginname"); + return { title: t("title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const loginName = searchParams?.loginName; + const requestId = searchParams?.requestId; + const organization = searchParams?.organization; + const orgDomain = searchParams?.orgDomain; + const submit: boolean = searchParams?.submit === "true"; + + // With an org domain suffix the login name may only be the local part (the + // form shows the suffix separately), so put it back together for the IdP + // login hint the same way sendLoginname does for the username form. + const idpLoginHint = loginName && orgDomain && !loginName.includes("@") ? `${loginName}@${orgDomain}` : loginName; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + const loginSettings = await getLoginSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + const identityProviders = await getActiveIdentityProviders({ + serviceConfig, + orgId: organization ?? defaultOrganization, + }).then((resp) => { + return resp.identityProviders; + }); + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + return ( + +
+

+ +

+

+ +

+
+ +
+ {loginSettings?.allowLocalAuthentication && ( + + )} + + {loginSettings?.allowExternalIdp && !!identityProviders?.length && ( +
+ +
+ )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/logout/done/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/logout/done/page.tsx new file mode 100644 index 0000000..37ea22c --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/logout/done/page.tsx @@ -0,0 +1,30 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings } from "@/lib/server/zitadel"; +import { headers } from "next/headers"; + +export default async function Page(props: { searchParams: Promise }) { + const searchParams = await props.searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { organization } = searchParams; + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + return ( + +
+

+ +

+

+ +

+
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/logout/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/logout/page.tsx new file mode 100644 index 0000000..e316dc6 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/logout/page.tsx @@ -0,0 +1,104 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SessionsClearList } from "@/components/sessions-clear-list"; +import { Translated } from "@/components/translated"; +import { getAllSessionCookieIds } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getBrandingSettings, getDefaultOrg, listSessions, ServiceConfig } from "@/lib/server/zitadel"; +import { verifyJwt } from "@zitadel/client/node"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("logout"); + return { title: t("title") }; +} + +async function loadSessions({ serviceConfig }: { serviceConfig: ServiceConfig }) { + const cookieIds = await getAllSessionCookieIds(); + + if (cookieIds && cookieIds.length) { + const response = await listSessions({ serviceConfig, ids: cookieIds.filter((id) => !!id) as string[] }); + return response?.sessions ?? []; + } else { + console.info("No session cookie found."); + return []; + } +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const organization = searchParams?.organization; + const logoutToken = searchParams?.logout_token; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let postLogoutRedirectUri, logoutHint; + if (logoutToken) { + try { + const payload = await verifyJwt<{ post_logout_redirect_uri?: string; logoutHint?: string }>( + logoutToken, + `${serviceConfig.baseUrl}/oauth/v2/keys`, + { + instanceHost: serviceConfig.instanceHost, + publicHost: serviceConfig.publicHost, + }, + ); + console.log("logout token payload", payload); + + if (payload.post_logout_redirect_uri && typeof payload.post_logout_redirect_uri === "string") { + postLogoutRedirectUri = payload.post_logout_redirect_uri; + } + if (payload.logout_hint && typeof payload.logout_hint === "string") { + logoutHint = payload.logout_hint; + } + } catch (error) { + console.error("Failed to verify logout token", error); + } + } + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + let sessions = await loadSessions({ serviceConfig }); + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + const params = new URLSearchParams(); + + if (organization) { + params.append("organization", organization); + } + + return ( + +
+

+ +

+

+ +

+
+ +
+
+ +
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/mfa/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/mfa/page.tsx new file mode 100644 index 0000000..a440b3a --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/mfa/page.tsx @@ -0,0 +1,120 @@ +import { Alert } from "@/components/alert"; +import { BackButton } from "@/components/back-button"; +import { ChooseSecondFactor } from "@/components/choose-second-factor"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getSession, listAuthenticationMethodTypes } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("mfa"); + return { title: t("verify.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { loginName, requestId, organization, sessionId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const sessionFactors = sessionId + ? await loadSessionById(sessionId, organization) + : await loadSessionByLoginname(loginName, organization); + + async function loadSessionByLoginname(loginName?: string, organization?: string) { + return loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }).then((session) => { + if (session && session.factors?.user?.id) { + return listAuthenticationMethodTypes({ serviceConfig, userId: session.factors.user.id }).then((methods) => { + return { + factors: session?.factors, + authMethods: methods.authMethodTypes ?? [], + }; + }); + } + }); + } + + async function loadSessionById(sessionId: string, organization?: string) { + const recent = await getSessionCookieById({ sessionId, organization }); + + if (!recent) { + return undefined; + } + + return getSession({ serviceConfig, sessionId: recent.id, sessionToken: recent.token }).then((response) => { + if (response?.session && response.session.factors?.user?.id) { + return listAuthenticationMethodTypes({ serviceConfig, userId: response.session.factors.user.id }).then((methods) => { + return { + factors: response.session?.factors, + authMethods: methods.authMethodTypes ?? [], + }; + }); + } + }); + } + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + return ( + +
+

+ +

+

+ +

+ + {sessionFactors && ( + + )} +
+ +
+ {!(loginName || sessionId) && ( + + + + )} + + {sessionFactors ? ( + + ) : ( + + + + )} + +
+ + +
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/mfa/set/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/mfa/set/page.tsx new file mode 100644 index 0000000..a01b2de --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/mfa/set/page.tsx @@ -0,0 +1,189 @@ +import { Alert } from "@/components/alert"; +import { BackButton } from "@/components/back-button"; +import { ChooseSecondFactorToSetup } from "@/components/choose-second-factor-to-setup"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { hasVerifiedPrimaryFactor, loadMostRecentSession } from "@/lib/server/session"; +import { + getBrandingSettings, + getLoginSettings, + getSession, + getUserByID, + listAuthenticationMethodTypes, +} from "@/lib/server/zitadel"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { SecondFactorType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("mfa"); + return { title: t("set.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { loginName, checkAfter, force, requestId, organization, sessionId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const sessionWithData = sessionId + ? await loadSessionById(sessionId, organization) + : await loadSessionByLoginname(loginName, organization); + + async function getAuthMethodsAndUser(session?: Session) { + const userId = session?.factors?.user?.id; + + if (!userId) { + throw Error("Could not get user id from session"); + } + + return listAuthenticationMethodTypes({ serviceConfig, userId }).then((methods) => { + return getUserByID({ serviceConfig, userId }).then((user) => { + const humanUser = user.user?.type.case === "human" ? user.user?.type.value : undefined; + + return { + id: session.id, + factors: session?.factors, + authMethods: methods.authMethodTypes ?? [], + phoneVerified: humanUser?.phone?.isVerified ?? false, + emailVerified: humanUser?.email?.isVerified ?? false, + expirationDate: session?.expirationDate, + }; + }); + }); + } + + async function loadSessionByLoginname(loginName?: string, organization?: string) { + return loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }).then((session) => { + return getAuthMethodsAndUser(session); + }); + } + + async function loadSessionById(sessionId: string, organization?: string) { + const recent = await getSessionCookieById({ sessionId, organization }); + + if (!recent) { + return undefined; + } + + return getSession({ serviceConfig, sessionId: recent.id, sessionToken: recent.token }).then((sessionResponse) => { + return getAuthMethodsAndUser(sessionResponse.session); + }); + } + + const branding = await getBrandingSettings({ serviceConfig, organization }); + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: sessionWithData?.factors?.user?.organizationId, + }); + + const { valid } = sessionWithData ? hasVerifiedPrimaryFactor(sessionWithData) : { valid: false }; + + if (force === "true" && valid && sessionWithData?.factors?.user?.loginName && loginSettings) { + const emailVerified = sessionWithData.emailVerified ?? false; + const phoneVerified = sessionWithData.phoneVerified ?? false; + const hasVisibleFactor = loginSettings.secondFactors.some((f) => { + switch (f) { + case SecondFactorType.OTP: + case SecondFactorType.U2F: + return true; + case SecondFactorType.OTP_EMAIL: + return emailVerified; + case SecondFactorType.OTP_SMS: + return phoneVerified; + default: + return false; + } + }); + + if (!hasVisibleFactor && !emailVerified && loginSettings.secondFactors.includes(SecondFactorType.OTP_EMAIL)) { + const verifyParams = new URLSearchParams({ + loginName: sessionWithData.factors.user.loginName, + send: "true", + }); + const org = organization ?? sessionWithData.factors.user.organizationId; + + if (requestId) { + verifyParams.set("requestId", requestId); + } + + if (org) { + verifyParams.set("organization", org as string); + } + redirect(`/verify?${verifyParams}`); + } + } + + return ( + +
+

+ +

+ +

+ +

+ + {sessionWithData && ( + + )} +
+ +
+
+ {!(loginName || sessionId) && ( + + + + )} + + {!valid && ( + + + + )} + + {valid && loginSettings && sessionWithData && sessionWithData.factors?.user?.id && ( + + )} + +
+ + +
+
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/page.test.tsx b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/page.test.tsx new file mode 100644 index 0000000..e0b93dd --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/page.test.tsx @@ -0,0 +1,108 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import Page from "./page"; + +vi.mock("@/lib/server/zitadel", () => ({ + getBrandingSettings: vi.fn(), + getLoginSettings: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + loadMostRecentSession: vi.fn(), + loadSessionById: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("@/components/dynamic-theme", () => ({ + DynamicTheme: ({ children }: any) =>
{children}
, +})); + +vi.mock("@/components/alert", () => ({ + Alert: ({ children }: any) =>
{children}
, +})); + +vi.mock("@/components/translated", () => ({ + Translated: ({ i18nKey }: any) => {i18nKey}, +})); + +vi.mock("@/components/user-avatar", () => ({ + UserAvatar: () =>
, +})); + +vi.mock("@/components/login-otp", () => ({ + LoginOTP: () =>
, +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +describe("otp page", () => { + let loadSessionById: any; + let loadMostRecentSession: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const zitadel = await import("@/lib/server/zitadel"); + const sessionLib = await import("@/lib/server/session"); + + loadSessionById = vi.mocked(sessionLib.loadSessionById); + loadMostRecentSession = vi.mocked(sessionLib.loadMostRecentSession); + vi.mocked(zitadel.getBrandingSettings).mockResolvedValue({} as any); + vi.mocked(zitadel.getLoginSettings).mockResolvedValue({} as any); + }); + + afterEach(cleanup); + + // A rejected session cookie must not crash the render: the shared loaders resolve undefined and + // the page falls back to its no-session alert on every branch. + test.each([ + { + name: "sessionId and loginName", + searchParams: { sessionId: "session-1", loginName: "user@example.com", organization: "org-1" }, + expectedAlert: "sessionExpired", + }, + { + name: "loginName only", + searchParams: { loginName: "user@example.com", organization: "org-1" }, + expectedAlert: "sessionExpired", + }, + { + name: "neither sessionId nor loginName", + searchParams: {}, + expectedAlert: "unknownContext", + }, + ])( + "renders the $expectedAlert alert and no OTP form when the session cannot be loaded ($name)", + async ({ searchParams, expectedAlert }) => { + loadSessionById.mockResolvedValue(undefined); + loadMostRecentSession.mockResolvedValue(undefined); + + const result = await Page({ + searchParams: Promise.resolve(searchParams), + params: Promise.resolve({ method: "time-based" }), + }); + render(result); + + if (searchParams.sessionId) { + expect(loadSessionById).toHaveBeenCalledWith({ baseUrl: "https://example.com" }, "session-1", "org-1"); + expect(loadMostRecentSession).not.toHaveBeenCalled(); + } else { + expect(loadMostRecentSession).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://example.com" }, + sessionParams: { loginName: searchParams.loginName, organization: searchParams.organization }, + }); + expect(loadSessionById).not.toHaveBeenCalled(); + } + expect(screen.getByRole("alert").textContent).toBe(expectedAlert); + expect(screen.queryByTestId("login-otp")).toBeNull(); + }, + ); +}); diff --git a/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/page.tsx new file mode 100644 index 0000000..59ba1d8 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/page.tsx @@ -0,0 +1,109 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { LoginOTP } from "@/components/login-otp"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession, loadSessionById } from "@/lib/server/session"; +import { getBrandingSettings, getLoginSettings } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("otp"); + return { title: t("verify.title") }; +} + +export default async function Page(props: { + searchParams: Promise>; + params: Promise>; +}) { + const params = await props.params; + const searchParams = await props.searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { + loginName, // send from password page + requestId, + sessionId, + organization, + code, + } = searchParams; + + const { method } = params; + + const session = sessionId + ? await loadSessionById(serviceConfig, sessionId, organization) + : await loadMostRecentSession({ serviceConfig, sessionParams: { loginName, organization } }); + + // email links do not come with organization, thus we need to use the session's organization + const branding = await getBrandingSettings({ + serviceConfig, + organization: organization ?? session?.factors?.user?.organizationId, + }); + + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: organization ?? session?.factors?.user?.organizationId, + }); + + return ( + +
+

+ +

+ {method === "time-based" && ( +

+ +

+ )} + {method === "sms" && ( +

+ +

+ )} + {method === "email" && ( +

+ +

+ )} + + {!session && ( +
+ + {/* context was provided but the session could not be resolved (cookie missing, invalid or expired) */} + + +
+ )} + + {session && ( + + )} +
+ +
+ {method && session && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/set/page.test.tsx b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/set/page.test.tsx new file mode 100644 index 0000000..b6a0072 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/set/page.test.tsx @@ -0,0 +1,156 @@ +import { OTPAddForm } from "@/components/otp-add-form"; +import { Translated } from "@/components/translated"; +import { isValidElement, ReactElement, ReactNode } from "react"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import Page from "./page"; + +vi.mock("@/lib/server/zitadel", () => ({ + getBrandingSettings: vi.fn(), + getLoginSettings: vi.fn(), + registerTOTP: vi.fn(), + addOTPEmail: vi.fn(), + addOTPSMS: vi.fn(), +})); + +vi.mock("@/lib/server/enrollment-guard", () => ({ + getEnrollmentAuthorizationError: vi.fn(), +})); + +vi.mock("@/lib/actions/otp", () => ({ + addOTP: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + loadMostRecentSession: vi.fn(), + loadSessionById: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +const session = { + id: "session-1", + factors: { user: { id: "user-1", loginName: "user@example.com", displayName: "User", organizationId: "org-1" } }, +}; + +// collects all elements of the given type from the (unrendered) element tree returned by the page +function findElements(node: ReactNode, type: unknown): ReactElement[] { + if (Array.isArray(node)) { + return node.flatMap((child) => findElements(child, type)); + } + if (!isValidElement(node)) { + return []; + } + const element = node as ReactElement; + return [...(element.type === type ? [element] : []), ...findElements(element.props?.children, type)]; +} + +describe("otp set page", () => { + let zitadel: any; + let sessionLib: any; + let guard: any; + let addOTP: any; + + beforeEach(async () => { + vi.clearAllMocks(); + zitadel = await import("@/lib/server/zitadel"); + sessionLib = await import("@/lib/server/session"); + guard = await import("@/lib/server/enrollment-guard"); + addOTP = vi.mocked((await import("@/lib/actions/otp")).addOTP); + + vi.mocked(zitadel.getBrandingSettings).mockResolvedValue({} as any); + vi.mocked(zitadel.getLoginSettings).mockResolvedValue({} as any); + vi.mocked(sessionLib.loadMostRecentSession).mockResolvedValue(session as any); + vi.mocked(sessionLib.loadSessionById).mockResolvedValue(session as any); + vi.mocked(guard.getEnrollmentAuthorizationError).mockResolvedValue(null); + }); + + // Rendering the page (e.g. by following a link) must never add a second factor to the + // signed-in user; OTP via email or SMS is only added on explicit confirmation. + test.each(["email", "sms"])("does not add OTP via %s while rendering but asks for confirmation", async (method) => { + const result = await Page({ + params: Promise.resolve({ method }), + searchParams: Promise.resolve({}), + }); + + expect(zitadel.addOTPEmail).not.toHaveBeenCalled(); + expect(zitadel.addOTPSMS).not.toHaveBeenCalled(); + expect(addOTP).not.toHaveBeenCalled(); + + const forms = findElements(result, OTPAddForm); + expect(forms).toHaveLength(1); + expect(forms[0].props).toMatchObject({ method, sessionId: "session-1", urlToContinue: "/accounts", checkAfter: false }); + }); + + test.each(["email", "sms"])("does not redirect for %s with checkAfter while rendering", async (method) => { + const result = await Page({ + params: Promise.resolve({ method }), + searchParams: Promise.resolve({ checkAfter: "true", loginName: "user@example.com" }), + }); + + expect(addOTP).not.toHaveBeenCalled(); + const forms = findElements(result, OTPAddForm); + expect(forms).toHaveLength(1); + expect(forms[0].props.checkAfter).toBe(true); + expect(forms[0].props.urlToContinue).toBe(`/otp/${method}?loginName=user%40example.com`); + }); + + test("hides the confirmation and shows the error when enrollment is not authorized", async () => { + vi.mocked(guard.getEnrollmentAuthorizationError).mockResolvedValue("You have to authenticate"); + + const result = await Page({ + params: Promise.resolve({ method: "email" }), + searchParams: Promise.resolve({}), + }); + + expect(findElements(result, OTPAddForm)).toHaveLength(0); + expect(JSON.stringify(result)).toContain("You have to authenticate"); + }); + + test("renders an alert instead of the confirmation without a session", async () => { + vi.mocked(sessionLib.loadMostRecentSession).mockResolvedValue(undefined); + + const result = await Page({ + params: Promise.resolve({ method: "email" }), + searchParams: Promise.resolve({}), + }); + + expect(findElements(result, OTPAddForm)).toHaveLength(0); + expect(findElements(result, Translated).map((t) => t.props.i18nKey)).toContain("unknownContext"); + }); + + test("acts on the session given by sessionId instead of the most recent one", async () => { + vi.mocked(sessionLib.loadSessionById).mockResolvedValue({ ...session, id: "session-a" } as any); + + const result = await Page({ + params: Promise.resolve({ method: "email" }), + searchParams: Promise.resolve({ sessionId: "session-a", organization: "org-1" }), + }); + + expect(sessionLib.loadSessionById).toHaveBeenCalledWith({ baseUrl: "https://example.com" }, "session-a", "org-1"); + expect(sessionLib.loadMostRecentSession).not.toHaveBeenCalled(); + expect(findElements(result, OTPAddForm)[0].props.sessionId).toBe("session-a"); + }); + + test("renders the session expired alert when the session given by sessionId can't be loaded", async () => { + vi.mocked(sessionLib.loadSessionById).mockResolvedValue(undefined); + + const result = await Page({ + params: Promise.resolve({ method: "email" }), + searchParams: Promise.resolve({ sessionId: "session-a" }), + }); + + expect(sessionLib.loadMostRecentSession).not.toHaveBeenCalled(); + expect(findElements(result, OTPAddForm)).toHaveLength(0); + expect(findElements(result, Translated).map((t) => t.props.i18nKey)).toContain("sessionExpired"); + }); +}); diff --git a/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/set/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/set/page.tsx new file mode 100644 index 0000000..538f69b --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/otp/[method]/set/page.tsx @@ -0,0 +1,177 @@ +import { Alert } from "@/components/alert"; +import { BackButton } from "@/components/back-button"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { OTPAddForm } from "@/components/otp-add-form"; +import { TotpRegister } from "@/components/totp-register"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession, loadSessionById } from "@/lib/server/session"; +import { getBrandingSettings, getLoginSettings, registerTOTP } from "@/lib/server/zitadel"; +import { RegisterTOTPResponse } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { headers } from "next/headers"; + +export default async function Page(props: { + searchParams: Promise>; + params: Promise>; +}) { + const params = await props.params; + const searchParams = await props.searchParams; + + const { loginName, organization, sessionId, requestId, checkAfter } = searchParams; + const { method } = params; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + const loginSettings = await getLoginSettings({ serviceConfig, organization }); + + // act on the session the flow was started with, and only fall back to the most recent one without it + const session = sessionId + ? await loadSessionById(serviceConfig, sessionId, organization) + : await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + + let totpResponse: RegisterTOTPResponse | undefined, error: Error | undefined; + if (session && session.factors?.user?.id) { + // Enrollment must be authorized: a bare identify-only session must not be able to + // attach a new OTP/TOTP factor to the account (GHSA-45f2-5q3r-xgg6). + const enrollmentError = await getEnrollmentAuthorizationError({ + serviceConfig, + session, + userId: session.factors.user.id, + }); + if (enrollmentError) { + error = new Error(enrollmentError); + } else if (method === "time-based") { + // registering only creates a pending secret, which is not used for authentication until + // the user verified a code from it, so it's safe to do while rendering + await registerTOTP({ serviceConfig, userId: session.factors.user.id }) + .then((resp) => { + if (resp) { + totpResponse = resp; + } + }) + .catch((err) => { + error = err; + }); + } else if (method !== "sms" && method !== "email") { + // OTP via SMS and email are only added on explicit confirmation of the user (see OTPAddForm), + // never while rendering, so that a link alone can't change the second factors of a user + throw new Error("Invalid method"); + } + } + + const paramsToContinue = new URLSearchParams({}); + let urlToContinue = "/accounts"; + + if (sessionId) { + paramsToContinue.append("sessionId", sessionId); + } + if (loginName) { + paramsToContinue.append("loginName", loginName); + } + if (organization) { + paramsToContinue.append("organization", organization); + } + + if (checkAfter) { + if (requestId) { + paramsToContinue.append("requestId", requestId); + } + urlToContinue = `/otp/${method}?` + paramsToContinue; + } else if (requestId?.startsWith("device_")) { + // device flows are completed on the consent screen, never by navigating to /signedin + paramsToContinue.append("requestId", requestId); + urlToContinue = `/device/consent?` + paramsToContinue; + } else if (requestId && sessionId) { + if (requestId) { + paramsToContinue.append("authRequest", requestId); + } + urlToContinue = `/login?` + paramsToContinue; + } else if (loginName) { + if (requestId) { + paramsToContinue.append("requestId", requestId); + } + urlToContinue = `/signedin?` + paramsToContinue; + } + + return ( + +
+

+ +

+ + {totpResponse && "uri" in totpResponse && "secret" in totpResponse ? ( +

+ +

+ ) : session && !error && (method === "email" || method === "sms") ? ( +

+ +

+ ) : null} + + {!session && ( +
+ + {/* context was provided but the session could not be resolved (cookie missing, invalid or expired) */} + + +
+ )} + + {error && ( +
+ {error?.message} +
+ )} + + {session && ( + + )} +
+ +
+ {totpResponse && "uri" in totpResponse && "secret" in totpResponse ? ( +
+ +
+ ) : session && !error && (method === "email" || method === "sms") ? ( + + ) : ( +
+ +
+ )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/page.tsx new file mode 100644 index 0000000..f1fce50 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/page.tsx @@ -0,0 +1,8 @@ +import { redirect } from "next/navigation"; + +export default function Page() { + // automatically redirect to loginname + if (process.env.DEBUG !== "true") { + redirect("/loginname"); + } +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/passkey/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/passkey/page.tsx new file mode 100644 index 0000000..e8844cd --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/passkey/page.tsx @@ -0,0 +1,107 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { LoginPasskey } from "@/components/login-passkey"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getDefaultOrg, getSession } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("passkey"); + return { title: t("verify.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { loginName, altPassword, requestId, organization, sessionId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + + if (org) { + defaultOrganization = org.id; + } + } + + let sessionFactors = sessionId ? await loadSessionById(sessionId, organization) : undefined; + + if (!sessionFactors && !sessionId) { + sessionFactors = await loadMostRecentSession({ + serviceConfig, + sessionParams: { loginName, organization }, + }); + } + + async function loadSessionById(sessionId: string, organization?: string) { + const recent = await getSessionCookieById({ sessionId, organization }); + + if (!recent) { + return undefined; + } + + return getSession({ serviceConfig, sessionId: recent.id, sessionToken: recent.token }).then((response) => { + if (response?.session) { + return response.session; + } + }); + } + + const branding = await getBrandingSettings({ + serviceConfig, + organization: organization ?? sessionFactors?.factors?.user?.organizationId ?? defaultOrganization, + }); + + return ( + +
+

+ +

+ +

+ +

+ + {sessionFactors ? ( + + ) : loginName ? ( + + ) : null} +
+ +
+ {!(loginName || sessionId) && ( + + + + )} + + {(loginName || sessionId) && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/passkey/set/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/passkey/set/page.tsx new file mode 100644 index 0000000..c5c064a --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/passkey/set/page.tsx @@ -0,0 +1,119 @@ +import { Alert, AlertType } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { RegisterPasskey } from "@/components/register-passkey"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getUserByID } from "@/lib/server/zitadel"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { HumanUser, User } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("passkey"); + return { title: t("set.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { userId, loginName, prompt, organization, requestId, code, codeId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + // also allow no session to be found for userId-based flows + let session: Session | undefined; + if (loginName) { + session = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + } + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + let user: User | undefined; + let displayName: string | undefined; + if (userId) { + const userResponse = await getUserByID({ serviceConfig, userId }); + user = userResponse.user; + + if (user?.type.case === "human") { + displayName = (user.type.value as HumanUser).profile?.displayName; + } + } + + return ( + +
+

+ +

+ +

+ +

+ + {session ? ( + + ) : user ? ( + + ) : null} +
+ +
+ + + + + + + + + + {!session && !user && ( +
+ + {/* context was provided but the session could not be resolved (cookie missing, invalid or expired) */} + + +
+ )} + + {(session?.id || userId) && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/password/change/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/password/change/page.tsx new file mode 100644 index 0000000..33ad67d --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/password/change/page.tsx @@ -0,0 +1,94 @@ +import { Alert } from "@/components/alert"; +import { ChangePasswordForm } from "@/components/change-password-form"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getPasswordComplexitySettings } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("password"); + return { title: t("change.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const searchParams = await props.searchParams; + + const { loginName, organization, requestId } = searchParams; + + // also allow no session to be found (ignoreUnkownUsername) + const sessionFactors = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const passwordComplexity = await getPasswordComplexitySettings({ + serviceConfig, + organization: sessionFactors?.factors?.user?.organizationId, + }); + + return ( + +
+

+ +

+

+ +

+ + {/* Only warn when there is no loginName to continue with; a failed session + lookup is reported by the form gate below (failedLoading), and under + enumeration protection no session may exist by design. */} + {!loginName && ( +
+ + + +
+ )} + + {sessionFactors ? ( + + ) : loginName ? ( + + ) : null} +
+ +
+ {passwordComplexity && loginName && sessionFactors?.factors?.user?.id ? ( + + ) : ( +
+ + + +
+ )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/password/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/password/page.tsx new file mode 100644 index 0000000..f6c1e71 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/password/page.tsx @@ -0,0 +1,100 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { PasswordForm } from "@/components/password-form"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getDefaultOrg, getLoginSettings } from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("password"); + return { title: t("verify.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + let { loginName, organization, requestId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + + if (org) { + defaultOrganization = org.id; + } + } + + // also allow no session to be found (ignoreUnkownUsername) + const sessionFactors = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + + const branding = await getBrandingSettings({ + serviceConfig, + organization: organization ?? sessionFactors?.factors?.user?.organizationId ?? defaultOrganization, + }); + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: organization ?? sessionFactors?.factors?.user?.organizationId ?? defaultOrganization, + }); + + return ( + +
+

+ +

+

+ +

+ + {sessionFactors ? ( + + ) : loginName ? ( + + ) : null} +
+ +
+ {/* Only warn when there is no loginName to continue with (e.g. a direct visit + without searchParams). A failed session lookup alone is not an error: the + form still works via the user-search fallback in sendPassword, and under + enumeration protection no session exists by design. */} + {!loginName && ( +
+ + + +
+ )} + + {loginName && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/password/set/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/password/set/page.tsx new file mode 100644 index 0000000..5bef893 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/password/set/page.tsx @@ -0,0 +1,164 @@ +import { Alert, AlertType } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SetPasswordForm } from "@/components/set-password-form"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { UNKNOWN_USER_ID } from "@/lib/constants"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { + getBrandingSettings, + getDefaultOrg, + getLoginSettings, + getPasswordComplexitySettings, + getUserByID, + searchUsers, +} from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { User } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("password"); + return { title: t("set.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + let { userId, loginName, organization, requestId, code, initial } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let defaultOrganization; + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + defaultOrganization = org.id; + } + } + + // also allow no session to be found (ignoreUnkownUsername) + let session: Session | undefined; + if (loginName) { + session = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + } + + const branding = await getBrandingSettings({ serviceConfig, organization: organization ?? defaultOrganization }); + + const passwordComplexity = await getPasswordComplexitySettings({ + serviceConfig, + organization: organization ?? session?.factors?.user?.organizationId ?? defaultOrganization, + }); + + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: organization ?? session?.factors?.user?.organizationId ?? defaultOrganization, + }); + + if (!loginSettings) { + return ( + +
+ + + +
+
+ ); + } + + let user: User | undefined; + if (userId) { + const userResponse = await getUserByID({ serviceConfig, userId }); + user = userResponse.user; + } else if (loginName) { + const users = await searchUsers({ + serviceConfig, + searchValue: loginName, + loginSettings: loginSettings, + organizationId: organization, + }); + + if (users.result && users.result.length === 1) { + const foundUser = users.result[0]; + userId = foundUser.userId; + user = foundUser; + } else if (loginSettings?.ignoreUnknownUsernames) { + // Prevent enumeration by pretending we found a user + userId = UNKNOWN_USER_ID; + } + } + + return ( + +
+

{session?.factors?.user?.displayName ?? }

+

+ +

+ + {/* Only warn when there is neither a loginName nor a userId to continue with. + A missing session is expected here: the set/reset flow works via code + + userId, and under enumeration protection no session exists by design. */} + {!loginName && !userId && ( +
+ + + +
+ )} + + {session ? ( + + ) : loginName ? ( + + ) : null} +
+ +
+ {!initial && ( + + + + )} + + {passwordComplexity && + (loginName ?? user?.preferredLoginName) && + (userId ?? session?.factors?.user?.id ?? (loginSettings?.ignoreUnknownUsernames ? UNKNOWN_USER_ID : undefined)) ? ( + + ) : ( +
+ + + +
+ )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/register/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/register/page.tsx new file mode 100644 index 0000000..2b3b538 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/register/page.tsx @@ -0,0 +1,128 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { RegisterForm } from "@/components/register-form"; +import { SignInWithIdp } from "@/components/sign-in-with-idp"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { + getActiveIdentityProviders, + getBrandingSettings, + getDefaultOrg, + getLegalAndSupportSettings, + getLoginSettings, + getPasswordComplexitySettings, +} from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("register"); + return { title: t("title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + let { firstname, lastname, email, organization, requestId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + organization = org.id; + } + } + + const legal = await getLegalAndSupportSettings({ serviceConfig, organization }); + const passwordComplexitySettings = await getPasswordComplexitySettings({ serviceConfig, organization }); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const loginSettings = await getLoginSettings({ serviceConfig, organization }); + + const identityProviders = await getActiveIdentityProviders({ serviceConfig, orgId: organization }).then((resp) => { + return resp.identityProviders.filter((idp) => { + return idp.options?.isAutoCreation || idp.options?.isCreationAllowed; // check if IDP allows to create account automatically or manual creation is allowed + }); + }); + + if (!loginSettings) { + return ( + +
+

+ +

+ + + +
+
+
+ ); + } + + if (!loginSettings?.allowRegister && (!loginSettings.allowExternalIdp || identityProviders.length === 0)) { + return ( + +
+

+ +

+

+ +

+
+
+
+ ); + } + + return ( + +
+

+ +

+

+ +

+
+ +
+ {!organization && ( + + + + )} + + {legal && passwordComplexitySettings && organization && loginSettings.allowLocalAuthentication && ( + + )} + + {loginSettings?.allowExternalIdp && !!identityProviders.length && ( + <> + + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/register/password/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/register/password/page.tsx new file mode 100644 index 0000000..daef0f2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/register/password/page.tsx @@ -0,0 +1,88 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { SetRegisterPasswordForm } from "@/components/set-register-password-form"; +import { Translated } from "@/components/translated"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { + getBrandingSettings, + getDefaultOrg, + getLegalAndSupportSettings, + getLoginSettings, + getPasswordComplexitySettings, +} from "@/lib/server/zitadel"; +import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb"; +import { headers } from "next/headers"; + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + let { firstname, lastname, email, organization, requestId } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + if (!organization) { + const org: Organization | null = await getDefaultOrg({ serviceConfig }); + if (org) { + organization = org.id; + } + } + + const missingData = !firstname || !lastname || !email || !organization; + + const legal = await getLegalAndSupportSettings({ serviceConfig, organization }); + const passwordComplexitySettings = await getPasswordComplexitySettings({ serviceConfig, organization }); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const loginSettings = await getLoginSettings({ serviceConfig, organization }); + + return missingData ? ( + +
+

+ +

+

+ +

+
+
+
+ ) : loginSettings?.allowRegister && loginSettings.allowLocalAuthentication ? ( + +
+

+ +

+

+ +

+
+ +
+ {legal && passwordComplexitySettings && ( + + )} +
+
+ ) : ( + +
+

+ +

+

+ +

+
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/signedin/page.test.tsx b/auth/ui/v2/apps/login/src/app/(login)/signedin/page.test.tsx new file mode 100644 index 0000000..a3d0191 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/signedin/page.test.tsx @@ -0,0 +1,86 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import Page from "./page"; + +vi.mock("@/lib/server/zitadel", () => ({ + getBrandingSettings: vi.fn(), + getLoginSettings: vi.fn(), + authorizeOrDenyDeviceAuthorization: vi.fn(), +})); + +vi.mock("@/lib/actions/device", () => ({ + approveDeviceAuthorization: vi.fn(), + denyDeviceAuthorization: vi.fn(), + completeDeviceAuthorization: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + loadMostRecentSession: vi.fn(), + loadSessionById: vi.fn(), +})); + +vi.mock("@/lib/server/next-url", () => ({ + resolveRedirectUri: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +const session = { + id: "session-1", + factors: { user: { id: "user-1", loginName: "user@example.com", displayName: "User", organizationId: "org-1" } }, +}; + +describe("signedin page", () => { + let authorizeOrDenyDeviceAuthorization: any; + let completeDeviceAuthorization: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const zitadel = await import("@/lib/server/zitadel"); + const device = await import("@/lib/actions/device"); + const sessionLib = await import("@/lib/server/session"); + const client = await import("@/lib/server/next-url"); + + authorizeOrDenyDeviceAuthorization = vi.mocked(zitadel.authorizeOrDenyDeviceAuthorization); + completeDeviceAuthorization = vi.mocked((device as any).completeDeviceAuthorization); + + vi.mocked(zitadel.getBrandingSettings).mockResolvedValue({} as any); + vi.mocked(zitadel.getLoginSettings).mockResolvedValue({} as any); + vi.mocked(sessionLib.loadMostRecentSession).mockResolvedValue(session as any); + vi.mocked(sessionLib.loadSessionById).mockResolvedValue(session as any); + vi.mocked(client.resolveRedirectUri).mockResolvedValue("/signedin"); + }); + + // Regression test for the device authorization consent bypass: rendering this page with an + // ambient session cookie must never complete a device authorization grant. + test("does not complete a device authorization when rendered with a device requestId", async () => { + const result = await Page({ searchParams: Promise.resolve({ requestId: "device_ABCD-1234" }) }); + + expect(result).toBeTruthy(); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + expect(completeDeviceAuthorization).not.toHaveBeenCalled(); + }); + + test("does not complete a device authorization when a sessionId is given", async () => { + const result = await Page({ + searchParams: Promise.resolve({ requestId: "device_ABCD-1234", sessionId: "session-1", organization: "org-1" }), + }); + + expect(result).toBeTruthy(); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + expect(completeDeviceAuthorization).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/app/(login)/signedin/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/signedin/page.tsx new file mode 100644 index 0000000..6789677 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/signedin/page.tsx @@ -0,0 +1,85 @@ +import { Alert, AlertType } from "@/components/alert"; +import { Button, ButtonVariants } from "@/components/button"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { resolveRedirectUri } from "@/lib/server/next-url"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession, loadSessionById } from "@/lib/server/session"; +import { getBrandingSettings, getLoginSettings } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; +import Link from "next/link"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("signedin"); + return { title: t("title", { user: "" }) }; +} + +export default async function Page(props: { searchParams: Promise }) { + const searchParams = await props.searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { loginName, requestId, organization, sessionId } = searchParams; + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const sessionFactors = sessionId + ? await loadSessionById(serviceConfig, sessionId, organization) + : await loadMostRecentSession({ serviceConfig, sessionParams: { loginName, organization } }); + + let loginSettings; + if (!requestId) { + loginSettings = await getLoginSettings({ serviceConfig, organization }); + } + + const redirectUri = await resolveRedirectUri( + requestId && sessionId ? { sessionId, requestId } : { loginName: loginName ?? sessionFactors?.factors?.user?.loginName }, + loginSettings?.defaultRedirectUri, + ); + + const isSamePage = redirectUri?.startsWith("/signedin") ?? false; + + return ( + +
+

+ +

+

+ +

+ + +
+ +
+ {requestId && requestId.startsWith("device_") && ( + + You can now close this window and return to the device where you started the authorization process to continue. + + )} + + {redirectUri && !isSamePage && ( +
+ + + + + +
+ )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/u2f/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/u2f/page.tsx new file mode 100644 index 0000000..2605b2f --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/u2f/page.tsx @@ -0,0 +1,88 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { LoginPasskey } from "@/components/login-passkey"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getSession } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("u2f"); + return { title: t("verify.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { loginName, requestId, sessionId, organization } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const sessionFactors = sessionId + ? await loadSessionById(sessionId, organization) + : await loadMostRecentSession({ serviceConfig, sessionParams: { loginName, organization } }); + + async function loadSessionById(sessionId: string, organization?: string) { + const recent = await getSessionCookieById({ sessionId, organization }); + + if (!recent) { + return undefined; + } + + return getSession({ serviceConfig, sessionId: recent.id, sessionToken: recent.token }).then((response) => { + if (response?.session) { + return response.session; + } + }); + } + + return ( + +
+

+ +

+ +

+ +

+ + {sessionFactors && ( + + )} + + {!(loginName || sessionId) && ( + + + + )} +
+ +
+ {(loginName || sessionId) && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/u2f/set/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/u2f/set/page.tsx new file mode 100644 index 0000000..0d0f1d3 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/u2f/set/page.tsx @@ -0,0 +1,93 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { RegisterU2f } from "@/components/register-u2f"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings } from "@/lib/server/zitadel"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("u2f"); + return { title: t("set.title") }; +} + +export default async function Page(props: { searchParams: Promise> }) { + const searchParams = await props.searchParams; + + const { loginName, organization, requestId, checkAfter } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const sessionFactors = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + // Enrollment must be authorized: a bare identify-only session must not be offered the + // authenticator-registration form (defense in depth alongside the addU2F/verifyU2F server + // actions, GHSA-45f2-5q3r-xgg6). + let enrollmentAuthorized = false; + if (sessionFactors?.id && sessionFactors.factors?.user?.id) { + const enrollmentError = await getEnrollmentAuthorizationError({ + serviceConfig, + session: sessionFactors, + userId: sessionFactors.factors.user.id, + }); + enrollmentAuthorized = !enrollmentError; + } + + return ( + +
+

+ +

+ +

+ +

+ + {sessionFactors && ( + + )} +
+ +
+ {(!sessionFactors || !enrollmentAuthorized) && ( +
+ + {/* a loginName was provided but the session could not be resolved (cookie missing, invalid or expired) */} + + +
+ )} + + {sessionFactors?.id && enrollmentAuthorized && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/verify/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/verify/page.tsx new file mode 100644 index 0000000..564bc79 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/verify/page.tsx @@ -0,0 +1,161 @@ +import { Alert } from "@/components/alert"; +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { VerifyForm } from "@/components/verify-form"; +import { UNKNOWN_USER_ID } from "@/lib/constants"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getLoginSettings, getUserByID, searchUsers } from "@/lib/server/zitadel"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { HumanUser, User } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +export async function generateMetadata(): Promise { + const t = await getTranslations("verify"); + return { title: t("verify.title") }; +} + +export default async function Page(props: { searchParams: Promise }) { + const searchParams = await props.searchParams; + + const { userId, loginName, code, organization, requestId, invite } = searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + let sessionFactors; + let user: User | undefined; + let human: HumanUser | undefined; + let id: string | undefined; + let loginSettings: LoginSettings | undefined; + + const autoSubmitCode = process.env.NEXT_PUBLIC_AUTO_SUBMIT_CODE === "true"; + + if ("loginName" in searchParams) { + sessionFactors = await loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }); + } else if ("userId" in searchParams && userId) { + const userResponse = await getUserByID({ serviceConfig, userId }); + if (userResponse) { + user = userResponse.user; + if (user?.type.case === "human") { + human = user.type.value as HumanUser; + } + } + } + + id = userId ?? sessionFactors?.factors?.user?.id; + + if (!id && loginName) { + if (!loginSettings) { + loginSettings = await getLoginSettings({ serviceConfig, organization }); + } + + if (!loginSettings) { + console.error("loginSettings not found"); + return; + } + + const users = await searchUsers({ + serviceConfig, + searchValue: loginName, + loginSettings: loginSettings, + organizationId: organization, + }); + + if (users.result && users.result.length === 1) { + const foundUser = users.result[0]; + id = foundUser.userId; + user = foundUser; + if (user.type.case === "human") { + human = user.type.value as HumanUser; + } + } else if (loginSettings?.ignoreUnknownUsernames) { + // Prevent enumeration by pretending we found a user + id = UNKNOWN_USER_ID; + } + } + + const params = new URLSearchParams({ + userId: userId, + initial: "true", // defines that a code is not required and is therefore not shown in the UI + }); + + if (loginName) { + params.set("loginName", loginName); + } + + if (organization) { + params.set("organization", organization); + } + + if (requestId) { + params.set("requestId", requestId); + } + + return ( + +
+

+ +

+

+ +

+ + {sessionFactors ? ( + + ) : ( + (user || loginName) && ( + + ) + )} +
+ +
+ {!id && ( +
+ + + +
+ )} + + {id && ( + + )} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/(login)/verify/success/page.tsx b/auth/ui/v2/apps/login/src/app/(login)/verify/success/page.tsx new file mode 100644 index 0000000..cb9e6d2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/(login)/verify/success/page.tsx @@ -0,0 +1,81 @@ +import { DynamicTheme } from "@/components/dynamic-theme"; +import { Translated } from "@/components/translated"; +import { UserAvatar } from "@/components/user-avatar"; +import { VerifySuccessContinue } from "@/components/verify-success-continue"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { getBrandingSettings, getUserByID } from "@/lib/server/zitadel"; +import { HumanUser, User } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { headers } from "next/headers"; + +export default async function Page(props: { searchParams: Promise }) { + const searchParams = await props.searchParams; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { loginName, organization, userId, requestId } = searchParams; + + const branding = await getBrandingSettings({ serviceConfig, organization }); + + const sessionFactors = await loadMostRecentSession({ serviceConfig, sessionParams: { loginName, organization } }); + + const id = userId ?? sessionFactors?.factors?.user?.id; + + if (!id) { + throw Error("Failed to get user id"); + } + + const userResponse = await getUserByID({ serviceConfig, userId: id }); + + let user: User | undefined; + let human: HumanUser | undefined; + + if (userResponse) { + user = userResponse.user; + if (user?.type.case === "human") { + human = user.type.value as HumanUser; + } + } + + // Build continue URL to re-enter the login flow with requestId preserved + let continueUrl: string | undefined; + if (requestId) { + const params = new URLSearchParams(); + if (loginName || user?.preferredLoginName) { + params.set("loginName", loginName ?? user?.preferredLoginName ?? ""); + } + if (organization) { + params.set("organization", organization); + } + params.set("requestId", requestId); + continueUrl = `/loginname?${params}`; + } + + return ( + +
+

+ +

+

+ +

+ + {sessionFactors ? ( + + ) : ( + user && ( + + ) + )} +
+
{continueUrl && }
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/app/global-error.tsx b/auth/ui/v2/apps/login/src/app/global-error.tsx new file mode 100644 index 0000000..db56324 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/global-error.tsx @@ -0,0 +1,30 @@ +"use client"; + +import { Boundary } from "@/components/boundary"; +import { Button } from "@/components/button"; +import { ThemeWrapper } from "@/components/theme-wrapper"; +import { Translated } from "@/components/translated"; + +export default function GlobalError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) { + return ( + // global-error must include html and body tags + + + + +
+
+ Error: {error?.message} +
+
+ +
+
+
+
+ + + ); +} diff --git a/auth/ui/v2/apps/login/src/app/healthy/route.ts b/auth/ui/v2/apps/login/src/app/healthy/route.ts new file mode 100644 index 0000000..da41c2c --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/healthy/route.ts @@ -0,0 +1,5 @@ +import { NextResponse } from "next/server"; + +export async function GET() { + return NextResponse.json({}, { status: 200 }); +} diff --git a/auth/ui/v2/apps/login/src/app/login/route.ts b/auth/ui/v2/apps/login/src/app/login/route.ts new file mode 100644 index 0000000..6454bfd --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/login/route.ts @@ -0,0 +1,72 @@ +import { isRSCRequest, validateAuthRequest } from "@/lib/server/auth-utils"; +import { getAllSessions } from "@/lib/server/cookies"; +import { FlowInitiationParams, handleOIDCFlowInitiation, handleSAMLFlowInitiation } from "@/lib/server/flow-initiation"; +import { createLogger } from "@/lib/server/logger"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { listSessions, ServiceConfig } from "@/lib/server/zitadel"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; + +import { NextRequest, NextResponse } from "next/server"; + +export const dynamic = "force-dynamic"; +export const revalidate = false; +export const fetchCache = "default-no-store"; + +const logger = createLogger("login-route"); + +async function loadSessions({ serviceConfig, ids }: { serviceConfig: ServiceConfig; ids: string[] }): Promise { + const response = await listSessions({ serviceConfig, ids: ids.filter((id: string | undefined) => !!id) }); + + return response?.sessions ?? []; +} + +export async function GET(request: NextRequest) { + const { serviceConfig } = getServiceConfig(request.headers); + + const searchParams = request.nextUrl.searchParams; + + // Defensive check: block RSC requests early + if (isRSCRequest(searchParams)) { + return NextResponse.json({ error: "RSC requests not supported" }, { status: 400 }); + } + + // Early validation: if no valid request parameters, return error immediately + const requestId = validateAuthRequest(searchParams); + if (!requestId) { + return NextResponse.json({ error: "No valid authentication request found" }, { status: 400 }); + } + + const sessionCookies = await getAllSessions(); + const ids = sessionCookies.map((s) => s.id); + let sessions: Session[] = []; + if (ids && ids.length) { + try { + sessions = await loadSessions({ serviceConfig, ids }); + } catch (error) { + logger.warn("Failed to load sessions", { error }); + // listSessions can fail for various reasons (stale/expired session IDs + // still in cookies, API errors, etc.). Treat any failure as "no valid + // sessions" so the user is redirected to loginname instead of a 500. + sessions = []; + } + } + + // Flow initiation - delegate to appropriate handler + const flowParams: FlowInitiationParams = { serviceConfig, requestId, sessions, sessionCookies, request }; + + try { + if (requestId.startsWith("oidc_")) { + return await handleOIDCFlowInitiation(flowParams); + } else if (requestId.startsWith("saml_")) { + return await handleSAMLFlowInitiation(flowParams); + } else if (requestId.startsWith("device_")) { + // Device Authorization does not need to start here as it is handled on the /device endpoint + return NextResponse.json({ error: "Device authorization should use /device endpoint" }, { status: 400 }); + } else { + return NextResponse.json({ error: "Invalid request ID format" }, { status: 400 }); + } + } catch (error: unknown) { + logger.error("Flow initiation failed", { requestId, error }); + return NextResponse.json({ error: "Internal server error" }, { status: 500 }); + } +} diff --git a/auth/ui/v2/apps/login/src/app/otel-test/route.ts b/auth/ui/v2/apps/login/src/app/otel-test/route.ts new file mode 100644 index 0000000..52e8cd8 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/otel-test/route.ts @@ -0,0 +1,84 @@ +import { createLogger } from "@/lib/server/logger"; +import { + recordAuthAttempt, + recordAuthFailure, + recordAuthSuccess, + recordRequestEnd, + recordRequestStart, + recordSessionCreationDuration, +} from "@/lib/server/metrics"; +import { metrics, SpanStatusCode, trace } from "@opentelemetry/api"; +import { NextResponse } from "next/server"; + +const logger = createLogger("otel-test"); + +export async function GET() { + const startTime = Date.now(); + + recordRequestStart(); + recordAuthAttempt("test", "test-org"); + + const tracer = trace.getTracer("otel-test"); + const span = tracer.startSpan("test-span"); + + try { + logger.info("OTEL test endpoint called", { test: true }); + + const meter = metrics.getMeter("otel-test"); + const counter = meter.createCounter("otel_test_requests_total", { + description: "Total number of OTEL test requests", + }); + counter.add(1, { test: "true" }); + + const histogram = meter.createHistogram("otel_test_duration_seconds", { + description: "Duration of OTEL test requests", + unit: "s", + }); + + span.setAttribute("test.attribute", "test-value"); + span.setAttribute("test.timestamp", new Date().toISOString()); + + await new Promise((resolve) => setTimeout(resolve, 10)); + + const duration = (Date.now() - startTime) / 1000; + histogram.record(duration, { test: "true" }); + + recordAuthSuccess("test", "test-org"); + recordRequestEnd(startTime, 200, "/otel-test"); + recordSessionCreationDuration(startTime, true); + + span.setStatus({ code: SpanStatusCode.OK }); + span.end(); + + logger.info("OTEL test completed successfully", { + duration, + traceId: span.spanContext().traceId, + }); + + return NextResponse.json({ + status: "ok", + message: "OTEL test completed", + traceId: span.spanContext().traceId, + spanId: span.spanContext().spanId, + duration: `${duration}s`, + timestamp: new Date().toISOString(), + }); + } catch (error) { + recordAuthFailure("test", "error", "test-org"); + recordRequestEnd(startTime, 500, "/otel-test"); + recordSessionCreationDuration(startTime, false); + + logger.error("OTEL test failed", { error }); + span.setStatus({ code: SpanStatusCode.ERROR, message: String(error) }); + span.end(); + + return NextResponse.json( + { + status: "error", + message: String(error), + traceId: span.spanContext().traceId, + }, + { status: 500 }, + ); + } +} diff --git a/auth/ui/v2/apps/login/src/app/ready/route.test.ts b/auth/ui/v2/apps/login/src/app/ready/route.test.ts new file mode 100644 index 0000000..66644d0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/ready/route.test.ts @@ -0,0 +1,138 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { GET } from "./route"; + +vi.mock("@/lib/server/logger", () => ({ + createLogger: () => ({ error: vi.fn(), warn: vi.fn() }), +})); + +function mockApiReady(status = 200) { + const fetchMock = vi.fn().mockResolvedValue( + new Response(status === 200 ? '"ok"' : "{}", { + status, + headers: { "Content-Type": "application/json" }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + return fetchMock; +} + +describe("GET /ready", () => { + let savedApiUrl: string | undefined; + let savedCookieSecret: string | undefined; + let savedCustomHeaders: string | undefined; + + beforeEach(() => { + savedApiUrl = process.env.ZITADEL_API_URL; + savedCookieSecret = process.env.ZITADEL_SESSION_COOKIE_SECRET; + savedCustomHeaders = process.env.CUSTOM_REQUEST_HEADERS; + process.env.ZITADEL_API_URL = "http://localhost:8080"; + process.env.ZITADEL_SESSION_COOKIE_SECRET = "test-session-cookie-secret-at-least-32-chars"; + delete process.env.CUSTOM_REQUEST_HEADERS; + }); + + afterEach(() => { + if (savedApiUrl === undefined) { + delete process.env.ZITADEL_API_URL; + } else { + process.env.ZITADEL_API_URL = savedApiUrl; + } + if (savedCookieSecret === undefined) { + delete process.env.ZITADEL_SESSION_COOKIE_SECRET; + } else { + process.env.ZITADEL_SESSION_COOKIE_SECRET = savedCookieSecret; + } + if (savedCustomHeaders === undefined) { + delete process.env.CUSTOM_REQUEST_HEADERS; + } else { + process.env.CUSTOM_REQUEST_HEADERS = savedCustomHeaders; + } + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + test("should return 200 when the API is ready", async () => { + const fetchMock = mockApiReady(); + + const response = await GET(); + + expect(response.status).toBe(200); + expect(response.headers.get("Content-Type")).toBe("text/plain"); + expect(await response.text()).toBe("OK"); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0].toString()).toBe("http://localhost:8080/debug/ready"); + }); + + test("should return 503 when the API is not ready", async () => { + mockApiReady(412); + + const response = await GET(); + + expect(response.status).toBe(503); + expect(response.headers.get("Content-Type")).toBe("text/plain"); + expect(await response.text()).toBe("Service unavailable"); + }); + + test("should return 503 when the API is unreachable", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("connection refused"))); + + const response = await GET(); + + expect(response.status).toBe(503); + expect(await response.text()).toBe("Service unavailable"); + }); + + test("should return 503 when no session cookie signing secret is available", async () => { + for (const name of [ + "ZITADEL_SESSION_COOKIE_SECRET", + "ZITADEL_SERVICE_USER_TOKEN", + "SYSTEM_USER_PRIVATE_KEY", + "SYSTEM_USER_PRIVATE_KEY_FILE", + "ZITADEL_LOGINCLIENT_KEYFILE", + ]) { + vi.stubEnv(name, undefined); + } + const fetchMock = mockApiReady(); + + const response = await GET(); + + expect(response.status).toBe(503); + expect(await response.text()).toBe("Service unavailable"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test("should return 503 when the dedicated session cookie secret is too short", async () => { + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "too-short"); + vi.stubEnv("ZITADEL_SERVICE_USER_TOKEN", "service-user-token"); + const fetchMock = mockApiReady(); + + const response = await GET(); + + expect(response.status).toBe(503); + expect(await response.text()).toBe("Service unavailable"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test("should return 503 when ZITADEL_API_URL is not set", async () => { + const fetchMock = mockApiReady(); + delete process.env.ZITADEL_API_URL; + + const response = await GET(); + + expect(response.status).toBe(503); + expect(response.headers.get("Content-Type")).toBe("text/plain"); + expect(await response.text()).toBe("Service unavailable"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test("should forward CUSTOM_REQUEST_HEADERS to the readiness request", async () => { + process.env.CUSTOM_REQUEST_HEADERS = "Host: zitadel.internal, X-Forwarded-Host: login.example.com"; + const fetchMock = mockApiReady(); + + await GET(); + + const headers = fetchMock.mock.calls[0][1].headers as Headers; + expect(headers.get("Host")).toBe("zitadel.internal"); + expect(headers.get("X-Forwarded-Host")).toBe("login.example.com"); + }); +}); diff --git a/auth/ui/v2/apps/login/src/app/ready/route.ts b/auth/ui/v2/apps/login/src/app/ready/route.ts new file mode 100644 index 0000000..b228744 --- /dev/null +++ b/auth/ui/v2/apps/login/src/app/ready/route.ts @@ -0,0 +1,73 @@ +import { applyCustomHeaders } from "@/lib/server/custom-headers"; +import { createLogger } from "@/lib/server/logger"; +import { getSessionCookieSecretConfigError, hasSessionCookieSecret } from "@/lib/server/session-cookie-signature"; +import { NextResponse } from "next/server"; + +const logger = createLogger("readiness"); + +const READINESS_TIMEOUT_MS = 5_000; + +/** + * Readiness probe. + * + * Reports whether the ZITADEL API is reachable and ready by calling its own + * unauthenticated readiness endpoint. This endpoint is served outside of the + * API's access-log and quota interceptors, so probe traffic is never counted + * as authenticated requests of the instance. + * + * It also fails if no session cookie signing secret is usable (a local check, + * no API call), since every login would otherwise fail when the cookie is written. + * + * The configured API credentials are validated once at process startup + * (see instrumentation.ts), not on every probe. + */ +export async function GET() { + const apiUrl = process.env.ZITADEL_API_URL; + if (!apiUrl) { + return unavailable(); + } + + // fail fast: without a signing secret every login would fail when the session cookie is written + if (!hasSessionCookieSecret()) { + logger.error( + `Readiness check failed: ${getSessionCookieSecretConfigError() ?? "no session cookie signing secret available (set ZITADEL_SESSION_COOKIE_SECRET)"}`, + ); + return unavailable(); + } + + try { + const headers = new Headers(); + applyCustomHeaders({ + set: (key, value) => headers.set(key, value), + remove: (key) => headers.delete(key), + }); + + const response = await fetch(new URL("/debug/ready", apiUrl), { + method: "GET", + headers, + cache: "no-store", + signal: AbortSignal.timeout(READINESS_TIMEOUT_MS), + }); + // consume the body so the connection can be reused + await response.arrayBuffer().catch(() => undefined); + + if (!response.ok) { + throw new Error(`ZITADEL API readiness check returned HTTP ${response.status}`); + } + + return new NextResponse("OK", { + status: 200, + headers: { "Content-Type": "text/plain", "Cache-Control": "no-store" }, + }); + } catch (e) { + logger.error("Readiness check failed", { error: e }); + return unavailable(); + } +} + +function unavailable() { + return new NextResponse("Service unavailable", { + status: 503, + headers: { "Content-Type": "text/plain", "Cache-Control": "no-store" }, + }); +} diff --git a/auth/ui/v2/apps/login/src/components/LoginLayout.tsx b/auth/ui/v2/apps/login/src/components/LoginLayout.tsx new file mode 100644 index 0000000..e69de29 diff --git a/auth/ui/v2/apps/login/src/components/address-bar.tsx b/auth/ui/v2/apps/login/src/components/address-bar.tsx new file mode 100644 index 0000000..eb9bc1d --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/address-bar.tsx @@ -0,0 +1,56 @@ +"use client"; + +import { usePathname } from "next/navigation"; +import { Fragment } from "react"; + +type Props = { + domain: string; +}; + +export function AddressBar({ domain }: Props) { + const pathname = usePathname(); + + return ( +
+
+ + + +
+
+
+ {domain} +
+ {pathname ? ( + <> + / + {pathname + .split("/") + .slice(1) + .filter((s) => !!s) + .map((segment) => { + return ( + + + + {segment} + + + + / + + ); + })} + + ) : null} +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/alert.tsx b/auth/ui/v2/apps/login/src/components/alert.tsx new file mode 100644 index 0000000..d61d977 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/alert.tsx @@ -0,0 +1,34 @@ +import { ExclamationTriangleIcon, InformationCircleIcon } from "@heroicons/react/24/outline"; +import { clsx } from "clsx"; +import { ReactNode } from "react"; + +type Props = { + children: ReactNode; + type?: AlertType; +}; + +export enum AlertType { + ALERT, + INFO, +} + +const yellow = + "border-yellow-600/40 dark:border-yellow-500/20 bg-yellow-200/30 text-yellow-600 dark:bg-yellow-700/20 dark:text-yellow-200"; +// const red = +// "border-red-600/40 dark:border-red-500/20 bg-red-200/30 text-red-600 dark:bg-red-700/20 dark:text-red-200"; +const neutral = "border-divider-light dark:border-divider-dark bg-black/5 text-gray-600 dark:bg-white/10 dark:text-gray-200"; + +export function Alert({ children, type = AlertType.ALERT }: Props) { + return ( +
+ {type === AlertType.ALERT && } + {type === AlertType.INFO && } + {children} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/app-avatar.tsx b/auth/ui/v2/apps/login/src/components/app-avatar.tsx new file mode 100644 index 0000000..df65d22 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/app-avatar.tsx @@ -0,0 +1,47 @@ +import { ColorShade, getColorHash } from "@/helpers/colors"; +import { useTheme } from "next-themes"; +import { getInitials } from "./avatar"; + +interface AvatarProps { + appName: string; + imageUrl?: string; + shadow?: boolean; +} + +export function AppAvatar({ appName, imageUrl, shadow }: AvatarProps) { + const { resolvedTheme } = useTheme(); + const credentials = getInitials(appName, appName); + + const color: ColorShade = getColorHash(appName); + + const avatarStyleDark = { + backgroundColor: color[900], + color: color[200], + }; + + const avatarStyleLight = { + backgroundColor: color[200], + color: color[900], + }; + + return ( +
+ {imageUrl ? ( + avatar + ) : ( + {credentials} + )} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/auth-methods.test.tsx b/auth/ui/v2/apps/login/src/components/auth-methods.test.tsx new file mode 100644 index 0000000..461ce4f --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/auth-methods.test.tsx @@ -0,0 +1,59 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import type { AnchorHTMLAttributes } from "react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { EMAIL, PASSKEYS, PASSWORD, SMS, TOTP, U2F } from "./auth-methods"; + +vi.mock("next-intl", () => ({ + useTranslations: (namespace?: string) => (key: string) => `${namespace ? `${namespace}.` : ""}${key}`, +})); + +vi.mock("next/link", () => ({ + default: ({ href, children, ...props }: AnchorHTMLAttributes & { href: string }) => ( + + {children} + + ), +})); + +describe("auth-methods", () => { + afterEach(cleanup); + + test.each([ + { + name: "TOTP", + card: TOTP, + translatedText: "authenticator.methods.totp", + }, + { + name: "U2F", + card: U2F, + translatedText: "authenticator.methods.u2f", + }, + { + name: "EMAIL", + card: EMAIL, + translatedText: "authenticator.methods.otpEmail", + }, + { + name: "SMS", + card: SMS, + translatedText: "authenticator.methods.otpSms", + }, + { + name: "PASSKEYS", + card: PASSKEYS, + translatedText: "authenticator.methods.passkey", + }, + { + name: "PASSWORD", + card: PASSWORD, + translatedText: "authenticator.methods.password", + }, + ])("renders $name label from translation key", ({ card, translatedText }) => { + render(card(false, "/auth/method")); + + const translatedLabel = screen.getByText(translatedText); + expect(translatedLabel).toBeInTheDocument(); + expect(translatedLabel).toHaveAttribute("data-i18n-key", translatedText); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/auth-methods.tsx b/auth/ui/v2/apps/login/src/components/auth-methods.tsx new file mode 100644 index 0000000..9fd36ef --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/auth-methods.tsx @@ -0,0 +1,191 @@ +import { CheckIcon } from "@heroicons/react/24/solid"; +import { clsx } from "clsx"; +import Link from "next/link"; +import { ReactNode } from "react"; +import { BadgeState, StateBadge } from "./state-badge"; +import { Translated } from "./translated"; + +const cardClasses = (alreadyAdded: boolean) => + clsx( + "relative bg-background-light-400 dark:bg-background-dark-400 group block space-y-1.5 rounded-md px-5 py-3 border border-divider-light dark:border-divider-dark transition-all ", + alreadyAdded ? "opacity-50 cursor-default" : "hover:shadow-lg hover:dark:bg-white/10", + ); + +const LinkWrapper = ({ alreadyAdded, children, link }: { alreadyAdded: boolean; children: ReactNode; link: string }) => { + return !alreadyAdded ? ( + + {children} + + ) : ( +
{children}
+ ); +}; + +export const TOTP = (alreadyAdded: boolean, link: string) => { + return ( + +
+ + timer-lock-outline + + {" "} + +
+ {alreadyAdded && ( + <> + + + )} +
+ ); +}; + +export const U2F = (alreadyAdded: boolean, link: string) => { + return ( + +
+ + + + +
+ {alreadyAdded && ( + <> + + + )} +
+ ); +}; + +export const EMAIL = (alreadyAdded: boolean, link: string) => { + return ( + +
+ + + + + +
+ {alreadyAdded && ( + <> + + + )} +
+ ); +}; + +export const SMS = (alreadyAdded: boolean, link: string) => { + return ( + +
+ + + + +
+ {alreadyAdded && ( + <> + + + )} +
+ ); +}; + +export const PASSKEYS = (alreadyAdded: boolean, link: string) => { + return ( + +
+ + + + +
+ {alreadyAdded && ( + <> + + + )} +
+ ); +}; + +export const PASSWORD = (alreadyAdded: boolean, link: string) => { + return ( + +
+ + form-textbox-password + + + +
+ {alreadyAdded && ( + <> + + + )} +
+ ); +}; + +function Setup() { + return ( +
+ + + +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/authentication-method-radio.tsx b/auth/ui/v2/apps/login/src/components/authentication-method-radio.tsx new file mode 100644 index 0000000..165f0e4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/authentication-method-radio.tsx @@ -0,0 +1,79 @@ +"use client"; + +import { Label, Radio, RadioGroup } from "@headlessui/react"; +import { Translated } from "./translated"; + +export enum AuthenticationMethod { + Passkey = "passkey", + Password = "password", +} + +export const methods = [AuthenticationMethod.Passkey, AuthenticationMethod.Password]; + +export function AuthenticationMethodRadio({ + selected, + selectionChanged, +}: { + selected: any; + selectionChanged: (value: any) => void; +}) { + return ( +
+
+ + +
+ {methods.map((method) => ( + + `${focus ? "ring-primary-light-500/60 ring-2 dark:ring-white/20" : ""} ${ + checked + ? "bg-background-light-400 ring-primary-light-500 dark:bg-background-dark-400 dark:ring-primary-dark-500 ring-2" + : "bg-background-light-400 dark:bg-background-dark-400" + } boder-divider-light dark:border-divider-dark relative flex h-full flex-1 cursor-pointer rounded-lg border px-5 py-4 hover:shadow-lg focus:outline-none dark:hover:bg-white/10` + } + > +
+ {method === "passkey" && ( + + + + )} + {method === "password" && ( + + form-textbox-password + + + )} + + +
+
+ ))} +
+
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/auto-submit-form.tsx b/auth/ui/v2/apps/login/src/components/auto-submit-form.tsx new file mode 100644 index 0000000..be7504d --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/auto-submit-form.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +type Props = { + url: string; + fields: Record; +}; + +export function AutoSubmitForm({ url, fields }: Props) { + const formRef = useRef(null); + + useEffect(() => { + if (formRef.current) { + formRef.current.submit(); + } + }, []); + + return ( +
+ {Object.entries(fields).map(([key, value]) => ( + + ))} + +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/avatar.test.tsx b/auth/ui/v2/apps/login/src/components/avatar.test.tsx new file mode 100644 index 0000000..38969bb --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/avatar.test.tsx @@ -0,0 +1,168 @@ +import { render } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Avatar, getInitials } from "./avatar"; + +// Mock next-themes +vi.mock("next-themes", () => ({ + useTheme: () => ({ + resolvedTheme: "light", + }), +})); + +// Mock next/image +vi.mock("next/image", () => ({ + default: ({ src, alt }: { src: string; alt: string }) => {alt}, +})); + +describe("Avatar Component", () => { + const originalEnv = process.env; + + beforeEach(() => { + process.env = { ...originalEnv }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + describe("getInitials", () => { + it("should get initials from full name", () => { + const initials = getInitials("John Doe", "john.doe@example.com"); + expect(initials).toBe("JD"); + }); + + it("should get single initial from single name", () => { + const initials = getInitials("John", "john@example.com"); + expect(initials).toBe("J"); + }); + + it("should get initials from loginName when name is empty", () => { + const initials = getInitials("", "john.doe@example.com"); + expect(initials.length).toBeGreaterThan(0); + }); + + it("should handle loginName with underscore separator", () => { + const initials = getInitials("", "john_doe@example.com"); + expect(initials).toBe("jd"); + }); + + it("should handle loginName with dash separator", () => { + const initials = getInitials("", "john-doe@example.com"); + expect(initials).toBe("jd"); + }); + + it("should handle loginName with dot separator", () => { + const initials = getInitials("", "john.doe@example.com"); + expect(initials).toBe("jd"); + }); + + it("should get initials from username part of email", () => { + const initials = getInitials("", "testuser@example.com"); + expect(initials.length).toBeGreaterThan(0); + }); + }); + + describe("Component Rendering", () => { + it("should render avatar with initials", () => { + const { container } = render(); + expect(container.querySelector(".avatar, [class*='avatar'], div")).toBeTruthy(); + }); + + it("should render with different sizes", () => { + const sizes: Array<"small" | "base" | "large"> = ["small", "base", "large"]; + + sizes.forEach((size) => { + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + }); + + it("should render with shadow prop", () => { + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + + it("should render without shadow prop", () => { + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + + it("should render with image URL", () => { + const { container } = render( + , + ); + expect(container.firstChild).toBeTruthy(); + }); + }); + + describe("Theme Integration", () => { + it("should apply theme-based roundness", () => { + const { container } = render(); + const avatar = container.firstChild as HTMLElement; + // Should render with some styling + expect(avatar).toBeTruthy(); + }); + + it("should respect theme roundness changes", () => { + // Default theme + const { container: container1 } = render(); + const avatar1 = container1.firstChild as HTMLElement; + + // Change theme + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "edgy"; + const { container: container2 } = render(); + const avatar2 = container2.firstChild as HTMLElement; + + // Both should render + expect(avatar1).toBeTruthy(); + expect(avatar2).toBeTruthy(); + }); + + it("should render with full roundness", () => { + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "full"; + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + + it("should render with mid roundness", () => { + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "mid"; + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + }); + + describe("Color Generation", () => { + it("should generate consistent colors for same loginName", () => { + const { container: container1 } = render(); + const { container: container2 } = render(); + + expect(container1.firstChild).toBeTruthy(); + expect(container2.firstChild).toBeTruthy(); + }); + + it("should render for different loginNames", () => { + const { container: container1 } = render(); + const { container: container2 } = render(); + + expect(container1.firstChild).toBeTruthy(); + expect(container2.firstChild).toBeTruthy(); + }); + }); + + describe("Props Validation", () => { + it("should handle null name", () => { + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + + it("should handle undefined name", () => { + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + + it("should require loginName", () => { + const { container } = render(); + expect(container.firstChild).toBeTruthy(); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/avatar.tsx b/auth/ui/v2/apps/login/src/components/avatar.tsx new file mode 100644 index 0000000..29621f9 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/avatar.tsx @@ -0,0 +1,83 @@ +"use client"; + +import { ColorShade, getColorHash } from "@/helpers/colors"; +import { getComponentRoundness } from "@/lib/theme"; +import { useTheme } from "next-themes"; + +interface AvatarProps { + name: string | null | undefined; + loginName: string; + imageUrl?: string; + size?: "small" | "base" | "large"; + shadow?: boolean; +} + +export function getInitials(name: string, loginName: string) { + if (name) { + const split = name.split(" "); + return split[0].charAt(0) + (split[1] ? split[1].charAt(0) : ""); + } + + const username = loginName.split("@")[0]; + let separator = "_"; + if (username.includes("-")) { + separator = "-"; + } + if (username.includes(".")) { + separator = "."; + } + const split = username.split(separator); + return split[0].charAt(0) + (split[1] ? split[1].charAt(0) : ""); +} + +// Helper function to get avatar roundness from theme +function getAvatarRoundness(): string { + return getComponentRoundness("avatar"); +} + +export function Avatar({ size = "base", name, loginName, imageUrl, shadow }: AvatarProps) { + const { resolvedTheme } = useTheme(); + const credentials = getInitials(name ?? loginName, loginName); + const avatarRoundness = getAvatarRoundness(); + + const color: ColorShade = getColorHash(loginName); + + const avatarStyleDark = { + backgroundColor: color[900], + color: color[200], + }; + + const avatarStyleLight = { + backgroundColor: color[200], + color: color[900], + }; + + return ( +
+ {imageUrl ? ( + avatar + ) : ( + {credentials} + )} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/back-button.tsx b/auth/ui/v2/apps/login/src/components/back-button.tsx new file mode 100644 index 0000000..434d723 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/back-button.tsx @@ -0,0 +1,14 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { Button, ButtonVariants } from "./button"; +import { Translated } from "./translated"; + +export function BackButton() { + const router = useRouter(); + return ( + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/background-wrapper.tsx b/auth/ui/v2/apps/login/src/components/background-wrapper.tsx new file mode 100644 index 0000000..e5c879b --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/background-wrapper.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { useThemeConfig } from "@/lib/theme-hooks"; +import { ReactNode } from "react"; + +/** + * BackgroundWrapper component handles applying background images from theme configuration. + * This needs to be a client component to access environment variables via the theme hook. + */ +export function BackgroundWrapper({ children, className = "" }: { children: ReactNode; className?: string }) { + const themeConfig = useThemeConfig(); + + const backgroundStyle = themeConfig.backgroundImage + ? { + backgroundImage: `url(${themeConfig.backgroundImage})`, + backgroundSize: "cover", + backgroundPosition: "center", + backgroundRepeat: "no-repeat", + } + : {}; + + return ( +
+ {children} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/boundary.tsx b/auth/ui/v2/apps/login/src/components/boundary.tsx new file mode 100644 index 0000000..24ca2f3 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/boundary.tsx @@ -0,0 +1,76 @@ +import { clsx } from "clsx"; +import { ReactNode } from "react"; + +const Label = ({ + children, + animateRerendering, + color, +}: { + children: ReactNode; + animateRerendering?: boolean; + color?: "default" | "pink" | "blue" | "violet" | "cyan" | "orange" | "red"; +}) => { + return ( +
+ {children} +
+ ); +}; +export const Boundary = ({ + children, + labels = ["children"], + size = "default", + color = "default", + animateRerendering = true, +}: { + children: ReactNode; + labels?: string[]; + size?: "small" | "default"; + color?: "default" | "pink" | "blue" | "violet" | "cyan" | "orange" | "red"; + animateRerendering?: boolean; +}) => { + return ( +
+
+ {labels.map((label) => { + return ( + + ); + })} +
+ + {children} +
+ ); +}; diff --git a/auth/ui/v2/apps/login/src/components/branding-context.tsx b/auth/ui/v2/apps/login/src/components/branding-context.tsx new file mode 100644 index 0000000..898a9aa --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/branding-context.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { useSyncExternalStore } from "react"; + +/** + * Module-level store for themeMode from branding settings. + * This is used instead of React Context because ThemeSwitch in the layout + * is a sibling of (not a descendant of) the ThemeWrapper/DynamicTheme tree. + */ +let currentThemeMode = 0; // Default to UNSPECIFIED +const listeners = new Set<() => void>(); + +function notifyListeners() { + listeners.forEach((listener) => listener()); +} + +export function setThemeMode(mode: number) { + if (currentThemeMode !== mode) { + currentThemeMode = mode; + notifyListeners(); + } +} + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function getSnapshot() { + return currentThemeMode; +} + +/** + * Hook to subscribe to themeMode changes using React 18+ useSyncExternalStore. + * Ensures ThemeSwitch always sees a consistent snapshot during concurrent renders. + */ +export function useThemeMode(): number { + return useSyncExternalStore(subscribe, getSnapshot, getSnapshot); +} diff --git a/auth/ui/v2/apps/login/src/components/button.test.tsx b/auth/ui/v2/apps/login/src/components/button.test.tsx new file mode 100644 index 0000000..233f9e5 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/button.test.tsx @@ -0,0 +1,215 @@ +import { render } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { Button, ButtonColors, ButtonSizes, ButtonVariants, getButtonClasses } from "./button"; + +describe("Button Component", () => { + const originalEnv = process.env; + + beforeEach(() => { + process.env = { ...originalEnv }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + describe("Component Rendering", () => { + it("should render button with children", () => { + const { getByText } = render(); + expect(getByText("Click me")).toBeTruthy(); + }); + + it("should apply custom className", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button?.className).toContain("custom-class"); + }); + + it("should pass through native button props", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button?.disabled).toBe(true); + }); + }); + + describe("Button Variants", () => { + it("should render primary variant by default", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + // Primary should have background color + expect(button?.className).toMatch(/bg-/); + }); + + it("should render secondary variant", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + // Secondary should have border + expect(button?.className).toMatch(/border/); + }); + + it("should render all variant types", () => { + const variants = [ButtonVariants.Primary, ButtonVariants.Secondary, ButtonVariants.Destructive]; + + variants.forEach((variant) => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + }); + }); + }); + + describe("Button Sizes", () => { + it("should render small size by default", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + // Should have padding styles + expect(button?.className).toMatch(/p[xy]?-/); + }); + + it("should render large size", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + // Should have padding styles + expect(button?.className).toMatch(/p[xy]?-/); + }); + + it("should render all size types", () => { + const sizes = [ButtonSizes.Small, ButtonSizes.Large]; + + sizes.forEach((size) => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + }); + }); + }); + + describe("Button Colors", () => { + it("should render primary color by default", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + // Should have background color + expect(button?.className).toMatch(/bg-/); + }); + + it("should render warn color", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + // Should have background color + expect(button?.className).toMatch(/bg-/); + }); + + it("should render all color types", () => { + const colors = [ButtonColors.Neutral, ButtonColors.Primary, ButtonColors.Warn]; + + colors.forEach((color) => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button).toBeTruthy(); + }); + }); + }); + + describe("Theme Integration", () => { + it("should apply theme-based roundness", () => { + const { container } = render(); + const button = container.querySelector("button"); + // Should have some roundness class applied + expect(button?.className).toBeTruthy(); + expect(button?.className).toMatch(/rounded/); + }); + + it("should completely override theme roundness with custom roundness prop", () => { + // Set theme to have full roundness + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "full"; + const customRoundness = "custom-round-test"; + + const { container } = render(); + const button = container.querySelector("button"); + + // Should contain the custom roundness + expect(button?.className).toContain(customRoundness); + + // The custom prop completely replaces theme roundness + expect(button).toBeTruthy(); + }); + + it("should change appearance when theme changes", () => { + // Default theme + const { container: container1 } = render(); + const button1 = container1.querySelector("button"); + const defaultClasses = button1?.className; + + // Change theme + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "full"; + const { container: container2 } = render(); + const button2 = container2.querySelector("button"); + + // Classes should be present (we don't check exact values) + expect(defaultClasses).toBeTruthy(); + expect(button2?.className).toBeTruthy(); + }); + }); + + describe("getButtonClasses", () => { + it("should return valid class string", () => { + const classes = getButtonClasses(ButtonSizes.Small, ButtonVariants.Primary, ButtonColors.Primary); + expect(typeof classes).toBe("string"); + expect(classes.length).toBeGreaterThan(0); + }); + + it("should include custom roundness classes", () => { + const customRoundness = "rounded-2xl"; + const classes = getButtonClasses(ButtonSizes.Small, ButtonVariants.Primary, ButtonColors.Primary, customRoundness); + expect(classes).toContain(customRoundness); + }); + + it("should include appearance classes", () => { + const appearance = "shadow-lg"; + const classes = getButtonClasses( + ButtonSizes.Small, + ButtonVariants.Primary, + ButtonColors.Primary, + "rounded-md", + appearance, + ); + expect(classes).toContain(appearance); + }); + + it("should generate different classes for different variants", () => { + const primaryClasses = getButtonClasses(ButtonSizes.Small, ButtonVariants.Primary, ButtonColors.Primary); + const secondaryClasses = getButtonClasses(ButtonSizes.Small, ButtonVariants.Secondary, ButtonColors.Primary); + + expect(primaryClasses).not.toBe(secondaryClasses); + }); + + it("should generate different classes for different sizes", () => { + const smallClasses = getButtonClasses(ButtonSizes.Small, ButtonVariants.Primary, ButtonColors.Primary); + const largeClasses = getButtonClasses(ButtonSizes.Large, ButtonVariants.Primary, ButtonColors.Primary); + + expect(smallClasses).not.toBe(largeClasses); + }); + }); + + describe("Accessibility", () => { + it("should have type='button' by default", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button?.type).toBe("button"); + }); + + it("should support disabled state", () => { + const { container } = render(); + const button = container.querySelector("button"); + expect(button?.disabled).toBe(true); + // Should have disabled styles + expect(button?.className).toMatch(/disabled:/); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/button.tsx b/auth/ui/v2/apps/login/src/components/button.tsx new file mode 100644 index 0000000..925d721 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/button.tsx @@ -0,0 +1,96 @@ +import { APPEARANCE_STYLES, getComponentRoundness, getThemeConfig } from "@/lib/theme"; +import { ThemeableProps } from "@/lib/themeUtils"; +import { clsx } from "clsx"; +import { ButtonHTMLAttributes, DetailedHTMLProps, forwardRef } from "react"; + +export enum ButtonSizes { + Small = "Small", + Large = "Large", +} + +export enum ButtonVariants { + Primary = "Primary", + Secondary = "Secondary", + Destructive = "Destructive", +} + +export enum ButtonColors { + Neutral = "Neutral", + Primary = "Primary", + Warn = "Warn", +} + +export type ButtonProps = DetailedHTMLProps, HTMLButtonElement> & { + size?: ButtonSizes; + variant?: ButtonVariants; + color?: ButtonColors; +} & ThemeableProps; + +export const getButtonClasses = ( + size: ButtonSizes, + variant: ButtonVariants, + color: ButtonColors, + roundnessClasses: string = "rounded-md", // Default fallback + appearance: string = "", // Theme appearance (shadows, borders, etc.) +) => + clsx( + { + "box-border leading-36px text-14px inline-flex items-center focus:outline-none transition-colors transition-shadow duration-300": true, + "disabled:border-none disabled:bg-gray-300 disabled:text-gray-600 disabled:shadow-none disabled:cursor-not-allowed disabled:dark:bg-gray-700 disabled:dark:text-gray-900": + variant === ButtonVariants.Primary, + "bg-primary-light-500 dark:bg-primary-dark-500 hover:bg-primary-light-400 hover:dark:bg-primary-dark-400 text-primary-light-contrast-500 dark:text-primary-dark-contrast-500": + variant === ButtonVariants.Primary && color !== ButtonColors.Warn, + "bg-warn-light-500 dark:bg-warn-dark-500 hover:bg-warn-light-400 hover:dark:bg-warn-dark-400 text-white dark:text-white": + variant === ButtonVariants.Primary && color === ButtonColors.Warn, + "border border-button-light-border dark:border-button-dark-border text-gray-950 hover:bg-gray-500/20 hover:dark:bg-white/10 focus:bg-gray-500/20 focus:dark:bg-white/10 dark:text-white disabled:text-gray-600 disabled:hover:bg-transparent disabled:dark:hover:bg-transparent disabled:cursor-not-allowed disabled:dark:text-gray-900": + variant === ButtonVariants.Secondary, + "border border-button-light-border dark:border-button-dark-border text-warn-light-500 dark:text-warn-dark-500 hover:bg-warn-light-500/10 dark:hover:bg-warn-light-500/10 focus:bg-warn-light-500/20 dark:focus:bg-warn-light-500/20": + color === ButtonColors.Warn && variant !== ButtonVariants.Primary, + "px-16 py-2": size === ButtonSizes.Large, + "px-4 h-[36px]": size === ButtonSizes.Small, + }, + roundnessClasses, // Apply the full roundness classes directly + appearance, // Apply appearance-specific styling (shadows, borders, etc.) + ); + +// Helper function to get default button roundness from theme +function getDefaultButtonRoundness(): string { + return getComponentRoundness("button"); +} + +// Helper function to get default button appearance from centralized theme system +function getDefaultButtonAppearance(): string { + const themeConfig = getThemeConfig(); + const appearance = APPEARANCE_STYLES[themeConfig.appearance]; + return appearance?.button || "border border-button-light-border dark:border-button-dark-border"; // Fallback to flat design +} + +export const Button = forwardRef( + ( + { + children, + className = "", + variant = ButtonVariants.Primary, + size = ButtonSizes.Small, + color = ButtonColors.Primary, + roundness, // Will use theme default if not provided + ...props + }, + ref, + ) => { + // Use theme-based values if not explicitly provided + const actualRoundness = roundness || getDefaultButtonRoundness(); + const actualAppearance = getDefaultButtonAppearance(); + + return ( + + ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/card.test.tsx b/auth/ui/v2/apps/login/src/components/card.test.tsx new file mode 100644 index 0000000..4c97afd --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/card.test.tsx @@ -0,0 +1,175 @@ +import { render } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { Card } from "./card"; + +describe("Card Component", () => { + const originalEnv = process.env; + + beforeEach(() => { + process.env = { ...originalEnv }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + describe("Component Rendering", () => { + it("should render card with children", () => { + const { getByText } = render( + +
Card Content
+
, + ); + expect(getByText("Card Content")).toBeTruthy(); + }); + + it("should render multiple children", () => { + const { getByText } = render( + +

Title

+

Description

+
, + ); + expect(getByText("Title")).toBeTruthy(); + expect(getByText("Description")).toBeTruthy(); + }); + + it("should apply custom className", () => { + const { container } = render(Content); + const card = container.firstChild as HTMLElement; + expect(card?.className).toContain("custom-class"); + }); + + it("should pass through native div props", () => { + const { container } = render( + + Content + , + ); + const card = container.firstChild as HTMLElement; + expect(card?.id).toBe("test-card"); + expect(card?.getAttribute("data-testid")).toBe("card"); + }); + }); + + describe("Theme Integration", () => { + it("should apply theme-based roundness", () => { + const { container } = render(Themed Card); + const card = container.firstChild as HTMLElement; + // Should have some roundness class applied + expect(card?.className).toBeTruthy(); + expect(card?.className).toMatch(/rounded/); + }); + + it("should completely override theme roundness with custom roundness prop", () => { + // Set theme to have mid roundness + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "mid"; + const customRoundness = "custom-card-round"; + + const { container } = render(Custom); + const card = container.firstChild as HTMLElement; + + // Should contain the custom roundness + expect(card?.className).toContain(customRoundness); + + // The custom prop completely replaces theme roundness, not merged + expect(card).toBeTruthy(); + }); + + it("should completely override theme padding with custom padding prop", () => { + // Set theme to have regular spacing + process.env.NEXT_PUBLIC_THEME_SPACING = "regular"; + const customPadding = "custom-card-padding"; + + const { container } = render(Custom); + const card = container.firstChild as HTMLElement; + + // Should contain the custom padding + expect(card?.className).toContain(customPadding); + + // The custom prop completely replaces theme padding, not merged + expect(card).toBeTruthy(); + }); + + it("should respect theme appearance changes", () => { + // Default theme + const { container: container1 } = render(Default); + const card1 = container1.firstChild as HTMLElement; + const defaultClasses = card1?.className; + + // Change theme appearance + process.env.NEXT_PUBLIC_THEME_APPEARANCE = "glass"; + const { container: container2 } = render(Glass); + const card2 = container2.firstChild as HTMLElement; + + // Classes should be present + expect(defaultClasses).toBeTruthy(); + expect(card2?.className).toBeTruthy(); + }); + + it("should respect theme spacing changes when no override provided", () => { + // Default spacing + const { container: container1 } = render(Default); + const card1 = container1.firstChild as HTMLElement; + const defaultClasses = card1?.className; + + // Compact spacing + process.env.NEXT_PUBLIC_THEME_SPACING = "compact"; + const { container: container2 } = render(Compact); + const card2 = container2.firstChild as HTMLElement; + + // Classes should be present + expect(defaultClasses).toBeTruthy(); + expect(card2?.className).toBeTruthy(); + }); + }); + + describe("Styling", () => { + it("should have base card styling", () => { + const { container } = render(Test); + const card = container.firstChild as HTMLElement; + expect(card?.className).toBeTruthy(); + expect(card?.className.length).toBeGreaterThan(0); + // Should have background color + expect(card?.className).toMatch(/bg-/); + }); + + it("should be a div element", () => { + const { container } = render(Test); + const card = container.firstChild as HTMLElement; + expect(card?.tagName).toBe("DIV"); + }); + }); + + describe("Multiple Appearance Themes", () => { + it("should render with flat appearance", () => { + process.env.NEXT_PUBLIC_THEME_APPEARANCE = "flat"; + const { container } = render(Flat Card); + const card = container.firstChild as HTMLElement; + expect(card).toBeTruthy(); + }); + + it("should render with material appearance", () => { + process.env.NEXT_PUBLIC_THEME_APPEARANCE = "material"; + const { container } = render(Material Card); + const card = container.firstChild as HTMLElement; + expect(card).toBeTruthy(); + }); + + it("should render with glass appearance", () => { + process.env.NEXT_PUBLIC_THEME_APPEARANCE = "glass"; + const { container } = render(Glass Card); + const card = container.firstChild as HTMLElement; + expect(card).toBeTruthy(); + }); + }); + + describe("Ref Forwarding", () => { + it("should support ref forwarding", () => { + const { container } = render(Content); + const card = container.firstChild as HTMLElement; + expect(card).toBeTruthy(); + expect(card.nodeType).toBe(1); // Element node + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/card.tsx b/auth/ui/v2/apps/login/src/components/card.tsx new file mode 100644 index 0000000..848f70f --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/card.tsx @@ -0,0 +1,71 @@ +import { APPEARANCE_STYLES, SPACING_STYLES, getComponentRoundness, getThemeConfig } from "@/lib/theme"; +import { clsx } from "clsx"; +import { HTMLAttributes, ReactNode, forwardRef } from "react"; + +export interface CardProps extends HTMLAttributes { + children: ReactNode; + roundness?: string; // Allow override via props + padding?: string; // Allow override via props +} + +// Helper function to get default card roundness from theme +function getDefaultCardRoundness(): string { + return getComponentRoundness("card"); +} + +// Helper function to get default padding from centralized theme system +function getDefaultCardPadding(): string { + const themeConfig = getThemeConfig(); + return SPACING_STYLES[themeConfig.spacing].padding; +} + +// Helper function to get default background from centralized theme system +function getDefaultCardBackground(): string { + const themeConfig = getThemeConfig(); + const appearance = APPEARANCE_STYLES[themeConfig.appearance]; + + // Use appearance-specific background if defined, otherwise fallback to material design (current system) + return appearance?.background || "bg-background-light-400 dark:bg-background-dark-500"; +} + +// Helper function to get default card styling from centralized theme system +function getDefaultCardStyling(): string { + const themeConfig = getThemeConfig(); + const appearance = APPEARANCE_STYLES[themeConfig.appearance]; + return appearance?.card || "shadow-sm border-0"; // Fallback to material design +} + +export const Card = forwardRef( + ( + { + children, + className = "", + roundness, // Will use theme default if not provided + padding, // Will use theme default if not provided + ...props + }, + ref, + ) => { + // Use theme-based values if not explicitly provided + const actualRoundness = roundness || getDefaultCardRoundness(); + const actualPadding = padding || getDefaultCardPadding(); + const actualBackground = getDefaultCardBackground(); + const actualCardStyling = getDefaultCardStyling(); + + return ( +
+ {children} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/change-password-form.test.tsx b/auth/ui/v2/apps/login/src/components/change-password-form.test.tsx new file mode 100644 index 0000000..420819d --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/change-password-form.test.tsx @@ -0,0 +1,45 @@ +import { cleanup, render } from "@testing-library/react"; +import { create } from "@zitadel/client"; +import { PasswordComplexitySettingsSchema } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ChangePasswordForm } from "./change-password-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/password", () => ({ + checkSessionAndSetPassword: vi.fn(), + sendPassword: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), +})); + +const defaultComplexitySettings = create(PasswordComplexitySettingsSchema, { + minLength: 8n, + requiresUppercase: false, + requiresLowercase: false, + requiresNumber: false, + requiresSymbol: false, +}); + +describe("ChangePasswordForm", () => { + afterEach(cleanup); + + test("should autofocus the current password input on mount", () => { + const { getByTestId } = render( + , + ); + expect(getByTestId("password-change-current-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/change-password-form.tsx b/auth/ui/v2/apps/login/src/components/change-password-form.tsx new file mode 100644 index 0000000..3105058 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/change-password-form.tsx @@ -0,0 +1,205 @@ +"use client"; + +import { lowerCaseValidator, numberValidator, symbolValidator, upperCaseValidator } from "@/helpers/validators"; +import { checkSessionAndSetPassword, sendPassword } from "@/lib/actions/password"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { create } from "@zitadel/client"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { PasswordComplexitySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { FieldValues, useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { PasswordComplexity } from "./password-complexity"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = + | { + currentPassword: string; + password: string; + confirmPassword: string; + } + | FieldValues; + +type Props = { + passwordComplexitySettings: PasswordComplexitySettings; + sessionId: string; + loginName: string; + requestId?: string; + organization?: string; +}; + +export function ChangePasswordForm({ passwordComplexitySettings, sessionId, loginName, requestId, organization }: Props) { + const router = useRouter(); + + const { register, handleSubmit, watch, formState } = useForm({ + mode: "onChange", + defaultValues: { + currentPassword: "", + password: "", + confirmPassword: "", + }, + }); + + const t = useTranslations("password"); + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + async function submitChange(values: Inputs) { + setLoading(true); + + const changeResponse = await checkSessionAndSetPassword({ + sessionId, + currentPassword: values.currentPassword, + password: values.password, + }).catch(() => { + setError(t("change.errors.couldNotChangePassword")); + setLoading(false); + return; + }); + + if (changeResponse && "error" in changeResponse && changeResponse.error) { + setError(typeof changeResponse.error === "string" ? changeResponse.error : t("change.errors.unknownError")); + setLoading(false); + return; + } + + if (!changeResponse) { + setError(t("change.errors.couldNotChangePassword")); + setLoading(false); + return; + } + + await new Promise((resolve) => setTimeout(resolve, 1000)); // wait for a second, to prevent eventual consistency issues + + const passwordResponse = await sendPassword({ + loginName, + organization, + checks: create(ChecksSchema, { + password: { password: values.password }, + }), + requestId, + }) + .catch(() => { + setError(t("change.errors.couldNotVerifyPassword")); + return; + }) + .finally(() => { + setLoading(false); + }); + + handleServerActionResponse(passwordResponse as any, router, setSamlData, setError); + + return; + } + + const { errors } = formState; + + const watchPassword = watch("password", ""); + const watchConfirmPassword = watch("confirmPassword", ""); + + const hasMinLength = passwordComplexitySettings && watchPassword?.length >= passwordComplexitySettings.minLength; + const hasSymbol = symbolValidator(watchPassword); + const hasNumber = numberValidator(watchPassword); + const hasUppercase = upperCaseValidator(watchPassword); + const hasLowercase = lowerCaseValidator(watchPassword); + + const policyIsValid = + passwordComplexitySettings && + (passwordComplexitySettings.requiresLowercase ? hasLowercase : true) && + (passwordComplexitySettings.requiresNumber ? hasNumber : true) && + (passwordComplexitySettings.requiresUppercase ? hasUppercase : true) && + (passwordComplexitySettings.requiresSymbol ? hasSymbol : true) && + hasMinLength; + + return ( + <> + {samlData && } +
+
+ +
+ +
+
+ +
+
+ +
+
+ + {passwordComplexitySettings && ( + + )} + + {error && {error}} + +
+ + +
+ + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/checkbox.tsx b/auth/ui/v2/apps/login/src/components/checkbox.tsx new file mode 100644 index 0000000..4fc7981 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/checkbox.tsx @@ -0,0 +1,44 @@ +import classNames from "clsx"; +import { DetailedHTMLProps, forwardRef, InputHTMLAttributes, useEffect, useState } from "react"; + +export type CheckboxProps = DetailedHTMLProps, HTMLInputElement> & { + checked: boolean; + disabled?: boolean; + onChangeVal?: (checked: boolean) => void; +}; + +export const Checkbox = forwardRef(function Checkbox( + { className = "", checked = false, disabled = false, onChangeVal, children, ...props }, + ref, +) { + const [enabled, setEnabled] = useState(checked); + + useEffect(() => { + setEnabled(checked); + }, [checked]); + + return ( +
+
+
+ { + setEnabled(event.target?.checked); + if (onChangeVal) onChangeVal(event.target?.checked); + }} + disabled={disabled} + type="checkbox" + className={classNames( + "form-checkbox text-primary-light-500 dark:text-primary-dark-500 rounded border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200/50 focus:ring-offset-0", + className, + )} + {...props} + /> +
+
+ {children} +
+ ); +}); diff --git a/auth/ui/v2/apps/login/src/components/choose-authenticator-to-login.tsx b/auth/ui/v2/apps/login/src/components/choose-authenticator-to-login.tsx new file mode 100644 index 0000000..34c421b --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/choose-authenticator-to-login.tsx @@ -0,0 +1,31 @@ +import { LoginSettings, PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { PASSKEYS, PASSWORD } from "./auth-methods"; +import { Translated } from "./translated"; + +type Props = { + authMethods: AuthenticationMethodType[]; + params: URLSearchParams; + loginSettings: LoginSettings | undefined; +}; + +export function ChooseAuthenticatorToLogin({ authMethods, params, loginSettings }: Props) { + return ( + <> + {authMethods.includes(AuthenticationMethodType.PASSWORD) && loginSettings?.allowLocalAuthentication && ( +
+ +
+ )} +
+ {authMethods.includes(AuthenticationMethodType.PASSWORD) && + loginSettings?.allowLocalAuthentication && + PASSWORD(false, "/password?" + params)} + {authMethods.includes(AuthenticationMethodType.PASSKEY) && + loginSettings?.allowLocalAuthentication && + loginSettings?.passkeysType == PasskeysType.ALLOWED && + PASSKEYS(false, "/passkey?" + params)} +
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/choose-authenticator-to-setup.tsx b/auth/ui/v2/apps/login/src/components/choose-authenticator-to-setup.tsx new file mode 100644 index 0000000..e89a7af --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/choose-authenticator-to-setup.tsx @@ -0,0 +1,32 @@ +import { LoginSettings, PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { Alert, AlertType } from "./alert"; +import { PASSKEYS, PASSWORD } from "./auth-methods"; +import { Translated } from "./translated"; + +type Props = { + authMethods: AuthenticationMethodType[]; + params: URLSearchParams; + loginSettings: LoginSettings; +}; + +export function ChooseAuthenticatorToSetup({ authMethods, params, loginSettings }: Props) { + if (authMethods.length !== 0) { + return ( + + + + ); + } else { + return ( +
+ {!authMethods.includes(AuthenticationMethodType.PASSWORD) && + loginSettings.allowLocalAuthentication && + PASSWORD(false, "/password/set?" + params)} + {!authMethods.includes(AuthenticationMethodType.PASSKEY) && + loginSettings.passkeysType == PasskeysType.ALLOWED && + PASSKEYS(false, "/passkey/set?" + params)} +
+ ); + } +} diff --git a/auth/ui/v2/apps/login/src/components/choose-second-factor-to-setup.tsx b/auth/ui/v2/apps/login/src/components/choose-second-factor-to-setup.tsx new file mode 100644 index 0000000..9a514e6 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/choose-second-factor-to-setup.tsx @@ -0,0 +1,108 @@ +"use client"; + +import { skipMFAAndContinueWithNextUrl } from "@/lib/actions/session"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { LoginSettings, SecondFactorType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Alert } from "./alert"; +import { EMAIL, SMS, TOTP, U2F } from "./auth-methods"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { Translated } from "./translated"; + +type Props = { + loginName?: string; + sessionId?: string; + requestId?: string; + organization?: string; + loginSettings: LoginSettings; + userMethods: AuthenticationMethodType[]; + checkAfter: boolean; + phoneVerified: boolean; + emailVerified: boolean; + force: boolean; +}; + +export function ChooseSecondFactorToSetup({ + loginName, + sessionId, + requestId, + organization, + loginSettings, + userMethods, + checkAfter, + phoneVerified, + emailVerified, + force, +}: Props) { + const router = useRouter(); + const params = new URLSearchParams({}); + + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + if (loginName) { + params.append("loginName", loginName); + } + if (sessionId) { + params.append("sessionId", sessionId); + } + if (requestId) { + params.append("requestId", requestId); + } + if (organization) { + params.append("organization", organization); + } + if (checkAfter) { + params.append("checkAfter", "true"); + } + + return ( + <> + {samlData && } +
+ {loginSettings.secondFactors.map((factor) => { + switch (factor) { + case SecondFactorType.OTP: + return TOTP(userMethods.includes(AuthenticationMethodType.TOTP), "/otp/time-based/set?" + params); + case SecondFactorType.U2F: + return U2F(userMethods.includes(AuthenticationMethodType.U2F), "/u2f/set?" + params); + case SecondFactorType.OTP_EMAIL: + return ( + emailVerified && EMAIL(userMethods.includes(AuthenticationMethodType.OTP_EMAIL), "/otp/email/set?" + params) + ); + case SecondFactorType.OTP_SMS: + return phoneVerified && SMS(userMethods.includes(AuthenticationMethodType.OTP_SMS), "/otp/sms/set?" + params); + default: + return null; + } + })} +
+ {!force && ( + + )} + {error && ( +
+ {error} +
+ )} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/choose-second-factor.tsx b/auth/ui/v2/apps/login/src/components/choose-second-factor.tsx new file mode 100644 index 0000000..f18ad23 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/choose-second-factor.tsx @@ -0,0 +1,44 @@ +"use client"; + +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { EMAIL, SMS, TOTP, U2F } from "./auth-methods"; + +type Props = { + loginName?: string; + sessionId?: string; + requestId?: string; + organization?: string; + userMethods: AuthenticationMethodType[]; +}; + +export function ChooseSecondFactor({ loginName, sessionId, requestId, organization, userMethods }: Props) { + const params = new URLSearchParams({}); + + if (loginName) { + params.append("loginName", loginName); + } + if (sessionId) { + params.append("sessionId", sessionId); + } + if (requestId) { + params.append("requestId", requestId); + } + if (organization) { + params.append("organization", organization); + } + + return ( +
+ {userMethods.map((method, i) => { + return ( +
+ {method === AuthenticationMethodType.TOTP && TOTP(false, "/otp/time-based?" + params)} + {method === AuthenticationMethodType.U2F && U2F(false, "/u2f?" + params)} + {method === AuthenticationMethodType.OTP_EMAIL && EMAIL(false, "/otp/email?" + params)} + {method === AuthenticationMethodType.OTP_SMS && SMS(false, "/otp/sms?" + params)} +
+ ); + })} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/consent.test.tsx b/auth/ui/v2/apps/login/src/components/consent.test.tsx new file mode 100644 index 0000000..48c1512 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/consent.test.tsx @@ -0,0 +1,73 @@ +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { ConsentScreen } from "./consent"; + +const { push } = vi.hoisted(() => ({ push: vi.fn() })); + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/device", () => ({ + approveDeviceAuthorization: vi.fn(), + denyDeviceAuthorization: vi.fn(), +})); + +describe("ConsentScreen", () => { + let approveDeviceAuthorization: any; + let denyDeviceAuthorization: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const device = await import("@/lib/actions/device"); + approveDeviceAuthorization = vi.mocked(device.approveDeviceAuthorization); + denyDeviceAuthorization = vi.mocked(device.denyDeviceAuthorization); + + approveDeviceAuthorization.mockResolvedValue({ redirect: "/signedin?requestId=device_ABCD-1234" }); + denyDeviceAuthorization.mockResolvedValue({ details: {} }); + }); + + afterEach(cleanup); + + test("shows the user code so it can be compared with the device", () => { + const { getByTestId } = render(); + + expect(getByTestId("user-code")).toHaveTextContent("ABCD-1234"); + }); + + test("approves the device authorization and follows the returned redirect", async () => { + const { getByTestId } = render( + , + ); + + fireEvent.click(getByTestId("submit-button")); + + await waitFor(() => expect(approveDeviceAuthorization).toHaveBeenCalledTimes(1)); + expect(approveDeviceAuthorization).toHaveBeenCalledWith({ + userCode: "ABCD-1234", + sessionId: "session-1", + organization: "org-1", + }); + await waitFor(() => expect(push).toHaveBeenCalledWith("/signedin?requestId=device_ABCD-1234")); + }); + + test("denies the device authorization and returns to the code entry page", async () => { + const { getByTestId } = render(); + + fireEvent.click(getByTestId("deny-button")); + + await waitFor(() => + expect(denyDeviceAuthorization).toHaveBeenCalledWith({ + userCode: "ABCD-1234", + sessionId: "session-1", + organization: "org-1", + }), + ); + await waitFor(() => expect(push).toHaveBeenCalledWith("/device")); + expect(approveDeviceAuthorization).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/consent.tsx b/auth/ui/v2/apps/login/src/components/consent.tsx new file mode 100644 index 0000000..e72b6b7 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/consent.tsx @@ -0,0 +1,126 @@ +"use client"; + +import { approveDeviceAuthorization, denyDeviceAuthorization } from "@/lib/actions/device"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Alert } from "./alert"; +import { Button, ButtonVariants } from "./button"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +export function ConsentScreen({ + scope, + userCode, + sessionId, + organization, + appName, +}: { + scope?: string[]; + userCode: string; + sessionId: string; + organization?: string; + appName?: string; +}) { + const t = useTranslations(); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const router = useRouter(); + + async function run(action: () => Promise, onSuccess: (response: { redirect?: string }) => void) { + setLoading(true); + const response = (await action() + .catch(() => ({ error: "Could not complete the request" })) + .finally(() => { + setLoading(false); + })) as { error?: string; redirect?: string }; + + if (response?.error) { + setError(response.error); + return; + } + + onSuccess(response); + } + + const scopes = scope?.filter((s) => !!s); + + return ( +
+
    + {scopes?.length === 0 && ( + + + + )} + {scopes?.map((s) => { + const translationKey = `device.scope.${s}`; + const description = t(translationKey); + + // Check if the key itself is returned and provide a fallback + const resolvedDescription = description === translationKey ? "" : description; + + return ( +
  • + {resolvedDescription} +
  • + ); + })} +
+ + {/* RFC 8628 5.4: show the user code so the user can compare it with the one on the device */} +

+ {" "} + + {userCode} + +

+ +

+ +

+ + {error && ( +
+ {error} +
+ )} + +
+ + + + +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/copy-to-clipboard.tsx b/auth/ui/v2/apps/login/src/components/copy-to-clipboard.tsx new file mode 100644 index 0000000..3a9c35e --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/copy-to-clipboard.tsx @@ -0,0 +1,34 @@ +"use client"; + +import { ClipboardDocumentCheckIcon, ClipboardIcon } from "@heroicons/react/20/solid"; +import copy from "copy-to-clipboard"; +import { useEffect, useState } from "react"; + +type Props = { + value: string; +}; + +export function CopyToClipboard({ value }: Props) { + const [copied, setCopied] = useState(false); + + useEffect(() => { + if (copied) { + copy(value); + const to = setTimeout(setCopied, 1000, false); + return () => clearTimeout(to); + } + }, [copied, value]); + + return ( +
+ +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/default-tags.tsx b/auth/ui/v2/apps/login/src/components/default-tags.tsx new file mode 100644 index 0000000..cd3b748 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/default-tags.tsx @@ -0,0 +1,18 @@ +// Default tags we want shared across the app +export function DefaultTags() { + return ( + <> + + + + + + {/* */} + + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/device-code-form.test.tsx b/auth/ui/v2/apps/login/src/components/device-code-form.test.tsx new file mode 100644 index 0000000..9ae7f70 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/device-code-form.test.tsx @@ -0,0 +1,74 @@ +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { DeviceCodeForm } from "./device-code-form"; + +const { push } = vi.hoisted(() => ({ push: vi.fn() })); + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/oidc", () => ({ + getDeviceAuthorizationRequest: vi.fn(), +})); + +describe("DeviceCodeForm", () => { + let getDeviceAuthorizationRequest: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const oidc = await import("@/lib/actions/oidc"); + getDeviceAuthorizationRequest = vi.mocked(oidc.getDeviceAuthorizationRequest); + }); + + afterEach(cleanup); + + async function submit(getByTestId: (id: string) => HTMLElement) { + await waitFor(() => expect(getByTestId("submit-button")).not.toBeDisabled()); + fireEvent.click(getByTestId("submit-button")); + } + + test("should autofocus the code input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("code-text-input")).toHaveFocus(); + }); + + test("should continue to the url returned by the server", async () => { + getDeviceAuthorizationRequest.mockResolvedValue({ + deviceAuthorizationRequest: { id: "encrypted-device-code" }, + nextUrl: "/accounts?requestId=device_ABCD-1234", + }); + + const { getByTestId } = render(); + await submit(getByTestId); + + await waitFor(() => expect(push).toHaveBeenCalledWith("/accounts?requestId=device_ABCD-1234")); + expect(getDeviceAuthorizationRequest).toHaveBeenCalledWith("ABCD-1234"); + }); + + test("should show an error and not navigate when the server returns no next url", async () => { + getDeviceAuthorizationRequest.mockResolvedValue({ + deviceAuthorizationRequest: { id: "encrypted-device-code" }, + }); + + const { getByTestId } = render(); + await submit(getByTestId); + + await waitFor(() => expect(getByTestId("error")).toBeInTheDocument()); + expect(push).not.toHaveBeenCalled(); + }); + + test("should show an error and not navigate when the code is unknown", async () => { + getDeviceAuthorizationRequest.mockResolvedValue({ deviceAuthorizationRequest: undefined, nextUrl: undefined }); + + const { getByTestId } = render(); + await submit(getByTestId); + + await waitFor(() => expect(getByTestId("error")).toBeInTheDocument()); + expect(push).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/device-code-form.tsx b/auth/ui/v2/apps/login/src/components/device-code-form.tsx new file mode 100644 index 0000000..5a91f93 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/device-code-form.tsx @@ -0,0 +1,98 @@ +"use client"; + +import { Alert } from "@/components/alert"; +import { getDeviceAuthorizationRequest } from "@/lib/actions/oidc"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { useForm } from "react-hook-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = { + userCode: string; +}; + +export function DeviceCodeForm({ userCode }: { userCode?: string }) { + const router = useRouter(); + + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + userCode: userCode || "", + }, + }); + + const t = useTranslations("device"); + + const [error, setError] = useState(""); + + const [loading, setLoading] = useState(false); + + async function submitCodeAndContinue(value: Inputs): Promise { + setLoading(true); + + const response = await getDeviceAuthorizationRequest(value.userCode) + .catch(() => { + setError("Could not continue the request"); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (!response || !response.deviceAuthorizationRequest?.id) { + setError("Could not continue the request"); + return; + } + + // the server picks /accounts (live session in this browser) or /loginname; consent follows on /device/consent + if (!response.nextUrl) { + setError("Could not continue the request"); + return; + } + + return router.push(response.nextUrl); + } + + return ( + <> +
+
+ +
+ + {error && ( +
+ {error} +
+ )} + +
+ + + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/dynamic-theme.tsx b/auth/ui/v2/apps/login/src/components/dynamic-theme.tsx new file mode 100644 index 0000000..701d9c2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/dynamic-theme.tsx @@ -0,0 +1,134 @@ +"use client"; + +import { Logo } from "@/components/logo"; +import { useResponsiveLayout } from "@/lib/theme-hooks"; +import { BrandingSettings } from "@zitadel/proto/zitadel/settings/v2/branding_settings_pb"; +import React, { Children, ReactNode } from "react"; +import { Card } from "./card"; +import { ThemeWrapper } from "./theme-wrapper"; + +/** + * DynamicTheme component handles layout switching between traditional top-to-bottom + * and modern side-by-side layouts based on NEXT_PUBLIC_THEME_LAYOUT. + * + * For side-by-side layout: + * - First child: Goes to left side (title, description, etc.) + * - Second child: Goes to right side (forms, buttons, etc.) + * - Single child: Falls back to right side for backward compatibility + * + * For top-to-bottom layout: + * - All children rendered in traditional centered layout + */ +export function DynamicTheme({ + branding, + children, +}: { + children: ReactNode | ((isSideBySide: boolean) => ReactNode); + branding?: BrandingSettings; +}) { + const { isSideBySide } = useResponsiveLayout(); + + // Resolve children immediately to avoid passing functions through React + const actualChildren: ReactNode = React.useMemo(() => { + if (typeof children === "function") { + return (children as (isSideBySide: boolean) => ReactNode)(isSideBySide); + } + return children; + }, [children, isSideBySide]); + + return ( + + {isSideBySide + ? // Side-by-side layout: first child goes left, second child goes right + (() => { + const childArray = Children.toArray(actualChildren); + const leftContent = childArray[0] || null; + const rightContent = childArray[1] || null; + + // If there's only one child, it's likely the old format - keep it on the right side + const hasLeftRightStructure = childArray.length === 2; + + return ( +
+ +
+ {/* Left side: First child + branding */} +
+
+ {/* Logo and branding */} + {branding && ( + + )} + + {/* First child content (title, description) - only if we have left/right structure */} + {hasLeftRightStructure && ( +
+ {/* Apply larger styling to the content */} +
+ {leftContent} +
+
+ )} +
+
+ + {/* Right side: Second child (form) or single child if old format */} +
+
+
{hasLeftRightStructure ? rightContent : leftContent}
+
+
+
+
+
+ ); + })() + : // Traditional top-to-bottom layout - center title/description, left-align forms + (() => { + const childArray = Children.toArray(actualChildren); + const titleContent = childArray[0] || null; + const formContent = childArray[1] || null; + const hasMultipleChildren = childArray.length > 1; + + return ( +
+ +
+
+ {branding && ( + + )} +
+ + {hasMultipleChildren ? ( + <> + {/* Title and description - center aligned */} +
{titleContent}
+ + {/* Form content - left aligned */} +
{formContent}
+ + ) : ( + // Single child - use original behavior +
{actualChildren}
+ )} + +
+
+
+
+ ); + })()} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/external-link.tsx b/auth/ui/v2/apps/login/src/components/external-link.tsx new file mode 100644 index 0000000..90590d2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/external-link.tsx @@ -0,0 +1,15 @@ +import { ArrowRightIcon } from "@heroicons/react/24/solid"; +import { ReactNode } from "react"; + +export const ExternalLink = ({ children, href }: { children: ReactNode; href: string }) => { + return ( + +
{children}
+ + +
+ ); +}; diff --git a/auth/ui/v2/apps/login/src/components/idp-process-handler.tsx b/auth/ui/v2/apps/login/src/components/idp-process-handler.tsx new file mode 100644 index 0000000..c7f3bf9 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idp-process-handler.tsx @@ -0,0 +1,112 @@ +"use client"; + +import { processIDPCallback } from "@/lib/actions/idp-intent"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { Spinner } from "./spinner"; + +type Props = { + provider: string; + id: string; + token: string; + requestId?: string; + organization?: string; + link?: string; + sessionId?: string; + flowFingerprint?: string; + postErrorRedirectUrl?: string; +}; + +/** + * Client component that handles IDP callback processing. + * Must be client-side to allow cookie modifications via server actions. + */ +export function IdpProcessHandler({ + provider, + id, + token, + requestId, + organization, + link, + sessionId, + flowFingerprint, + postErrorRedirectUrl, +}: Props) { + const t = useTranslations("idp"); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + const executedRef = useRef(false); + const router = useRouter(); + + useEffect(() => { + // Prevent double execution in React Strict Mode + if (executedRef.current) { + return; + } + + executedRef.current = true; + + console.log("[IDP Process Handler] Starting IDP callback processing from client"); + + processIDPCallback({ + provider, + id, + token, + requestId, + organization, + sessionId, + flowFingerprint, + postErrorRedirectUrl, + }) + .then((result) => { + if (result.error) { + console.error("[IDP Process Handler] Error:", result.error); + setError(result.error); + setLoading(false); + return; + } + + if (result.redirect) { + console.log("[IDP Process Handler] Redirecting to:", result.redirect); + router.push(result.redirect); + return; + } + + if (result.samlData) { + console.log("[IDP Process Handler] Received samlData, rendering AutoSubmitForm"); + setSamlData(result.samlData); + setLoading(false); + return; + } + + setError(t("processing.noRedirect")); + setLoading(false); + }) + .catch((err) => { + console.error("[IDP Process Handler] Unexpected error:", err); + setError(err instanceof Error ? err.message : t("processing.unexpectedError")); + setLoading(false); + }); + }, [provider, id, token, requestId, organization, link, sessionId, flowFingerprint, postErrorRedirectUrl, router, t]); + + return ( +
+ {samlData && } + {loading && ( +
+ +

{t("processing.message")}

+
+ )} + {error && ( +
+ {error} +
+ )} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/idps/base-button.tsx b/auth/ui/v2/apps/login/src/components/idps/base-button.tsx new file mode 100644 index 0000000..4fb84f4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/base-button.tsx @@ -0,0 +1,49 @@ +"use client"; + +import { APPEARANCE_STYLES, getComponentRoundness, getThemeConfig } from "@/lib/theme"; +import { clsx } from "clsx"; +import { Loader2Icon } from "lucide-react"; +import { ButtonHTMLAttributes, DetailedHTMLProps, forwardRef } from "react"; +import { useFormStatus } from "react-dom"; + +export type SignInWithIdentityProviderProps = DetailedHTMLProps< + ButtonHTMLAttributes, + HTMLButtonElement +> & { + name?: string; + e2e?: string; +}; + +// Helper function to get default IDP button appearance from centralized theme system +function getDefaultIdpButtonAppearance(): string { + const themeConfig = getThemeConfig(); + const appearance = APPEARANCE_STYLES[themeConfig.appearance]; + return appearance?.["idp-button"] || "border border-divider-light dark:border-divider-dark"; // Fallback to basic border +} + +export const BaseButton = forwardRef(function BaseButton(props, ref) { + const formStatus = useFormStatus(); + const buttonRoundness = getComponentRoundness("button"); + const idpButtonAppearance = getDefaultIdpButtonAppearance(); + + return ( + + ); +}); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-apple.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-apple.tsx new file mode 100644 index 0000000..823dad2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-apple.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { forwardRef } from "react"; +import { Translated } from "../translated"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +export const SignInWithApple = forwardRef( + function SignInWithApple(props, ref) { + const { children, name, ...restProps } = props; + + return ( + +
+
+ + Apple Logo + + +
+
+ {children ? ( + children + ) : ( + {name ? name : } + )} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-azure-ad.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-azure-ad.tsx new file mode 100644 index 0000000..cb2b8dd --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-azure-ad.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { forwardRef } from "react"; +import { Translated } from "../translated"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +export const SignInWithAzureAd = forwardRef( + function SignInWithAzureAd(props, ref) { + const { children, name, ...restProps } = props; + + return ( + +
+ + + + + + +
+ {children ? ( + children + ) : ( + {name ? name : } + )} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-generic.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-generic.tsx new file mode 100644 index 0000000..9c01547 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-generic.tsx @@ -0,0 +1,15 @@ +"use client"; + +import { forwardRef } from "react"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +export const SignInWithGeneric = forwardRef( + function SignInWithGeneric(props, ref) { + const { children, name = "", className = "h-[50px]", ...restProps } = props; + return ( + + {children ? children : {name}} + + ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-github.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-github.tsx new file mode 100644 index 0000000..3cc08d1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-github.tsx @@ -0,0 +1,47 @@ +"use client"; + +import { forwardRef } from "react"; +import { Translated } from "../translated"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +function GitHubLogo() { + return ( + <> + + + + + + + + ); +} + +export const SignInWithGithub = forwardRef( + function SignInWithGithub(props, ref) { + const { children, name, ...restProps } = props; + + return ( + +
+ +
+ {children ? ( + children + ) : ( + {name ? name : } + )} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-gitlab.test.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-gitlab.test.tsx new file mode 100644 index 0000000..ab5bfda --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-gitlab.test.tsx @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { cleanup, render, screen } from "@testing-library/react"; +import { NextIntlClientProvider } from "next-intl"; + +import { SignInWithGitlab } from "./sign-in-with-gitlab"; + +afterEach(cleanup); + +describe("", async () => { + const messages = { + idp: { + signInWithGitlab: "Sign in with GitLab", + }, + }; + + test("renders without crashing", () => { + const { container } = render( + + + , + ); + expect(container.firstChild).toBeDefined(); + }); + + test("displays the default text", () => { + render( + + + , + ); + const signInText = screen.getByText(/Sign in with Gitlab/i); + expect(signInText).toBeInTheDocument(); + }); + + test("displays the given text", () => { + render( + + + , + ); + const signInText = screen.getByText(/Gitlab/i); + expect(signInText).toBeInTheDocument(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-gitlab.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-gitlab.tsx new file mode 100644 index 0000000..bd3a439 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-gitlab.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { forwardRef } from "react"; +import { Translated } from "../translated"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +export const SignInWithGitlab = forwardRef( + function SignInWithGitlab(props, ref) { + const { children, name, ...restProps } = props; + + return ( + +
+ + + + + + +
+ {children ? ( + children + ) : ( + {name ? name : } + )} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-google.test.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-google.test.tsx new file mode 100644 index 0000000..953da21 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-google.test.tsx @@ -0,0 +1,44 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { cleanup, render, screen } from "@testing-library/react"; +import { NextIntlClientProvider } from "next-intl"; +import { SignInWithGoogle } from "./sign-in-with-google"; + +afterEach(cleanup); + +describe("", async () => { + const messages = { + idp: { + signInWithGoogle: "Sign in with Google", + }, + }; + + test("renders without crashing", () => { + const { container } = render( + + + , + ); + expect(container.firstChild).toBeDefined(); + }); + + test("displays the default text", () => { + render( + + + , + ); + const signInText = screen.getByText(/Sign in with Google/i); + expect(signInText).toBeInTheDocument(); + }); + + test("displays the given text", () => { + render( + + + , + ); + const signInText = screen.getByText(/Google/i); + expect(signInText).toBeInTheDocument(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-google.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-google.tsx new file mode 100644 index 0000000..4320196 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-google.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { forwardRef } from "react"; +import { Translated } from "../translated"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +export const SignInWithGoogle = forwardRef( + function SignInWithGoogle(props, ref) { + const { children, name, ...restProps } = props; + + return ( + +
+ + + + + + + +
+ {children ? ( + children + ) : ( + {name ? name : } + )} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/idps/sign-in-with-zitadel.tsx b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-zitadel.tsx new file mode 100644 index 0000000..f5acb9b --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/idps/sign-in-with-zitadel.tsx @@ -0,0 +1,187 @@ +"use client"; + +import { forwardRef, useId } from "react"; +import { Translated } from "../translated"; +import { BaseButton, SignInWithIdentityProviderProps } from "./base-button"; + +export const SignInWithZitadel = forwardRef( + function SignInWithZitadel(props, ref) { + const { children, name, ...restProps } = props; + // Unique per component instance: multiple ZITADEL IdPs can be rendered on + // the same page, and duplicate SVG gradient ids would be invalid HTML. + const gradientId = useId().replace(/:/g, ""); + + return ( + +
+ +
+ {children ? ( + children + ) : ( + {name ? name : } + )} +
+ ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/input.test.tsx b/auth/ui/v2/apps/login/src/components/input.test.tsx new file mode 100644 index 0000000..779618d --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/input.test.tsx @@ -0,0 +1,194 @@ +import { render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { TextInput } from "./input"; + +describe("TextInput Component", () => { + const originalEnv = process.env; + + beforeEach(() => { + process.env = { ...originalEnv }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + describe("Component Rendering", () => { + it("should render input with label", () => { + render(); + expect(screen.getByText("Email")).toBeTruthy(); + }); + + it("should render input with placeholder", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input?.placeholder).toBe("Enter username"); + }); + + it("should render input with default value", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input?.defaultValue).toBe("John Doe"); + }); + + it("should show required indicator when required", () => { + render(); + expect(screen.getByText(/\*/)).toBeTruthy(); + }); + }); + + describe("Input States", () => { + it("should render disabled state", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input?.disabled).toBe(true); + // Should have disabled/pointer-events styles + expect(input?.className).toMatch(/pointer-events/); + }); + + it("should render error state with message", () => { + render(); + expect(screen.getByText("Invalid email")).toBeTruthy(); + }); + + it("should apply error styling when error is present", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input).toBeTruthy(); + // Should have border-warn or warn-related styles + expect(input?.className).toMatch(/border-warn/); + }); + + it("should render success state with message", () => { + render(); + expect(screen.getByText("Valid email")).toBeTruthy(); + }); + }); + + describe("Theme Integration", () => { + it("should apply theme-based roundness", () => { + const { container } = render(); + const input = container.querySelector("input"); + // Should have some roundness class applied + expect(input?.className).toBeTruthy(); + expect(input?.className).toMatch(/rounded/); + }); + + it("should completely override theme roundness with custom roundness prop", () => { + // Set theme to have full roundness + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "full"; + const customRoundness = "custom-input-round"; + + const { container } = render(); + const input = container.querySelector("input"); + + // Should contain the custom roundness + expect(input?.className).toContain(customRoundness); + + // The custom prop completely replaces theme roundness + expect(input).toBeTruthy(); + }); + + it("should respect theme roundness changes", () => { + // Default theme + const { container: container1 } = render(); + const input1 = container1.querySelector("input"); + const defaultClasses = input1?.className; + + // Change theme + process.env.NEXT_PUBLIC_THEME_ROUNDNESS = "full"; + const { container: container2 } = render(); + const input2 = container2.querySelector("input"); + + // Classes should be present + expect(defaultClasses).toBeTruthy(); + expect(input2?.className).toBeTruthy(); + }); + }); + + describe("Input Behavior", () => { + it("should have autocomplete off by default", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input?.autocomplete).toBe("off"); + }); + + it("should allow custom autocomplete", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input?.autocomplete).toBe("email"); + }); + + it("should pass through native input props", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input?.maxLength).toBe(10); + expect(input?.type).toBe("email"); + }); + + it("should support autoFocus", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input).toHaveFocus(); + }); + }); + + describe("Styling", () => { + it("should have consistent base styling", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input).toBeTruthy(); + expect(input?.className).toBeTruthy(); + expect(input?.className.length).toBeGreaterThan(0); + // Should have transition styles + expect(input?.className).toMatch(/transition/); + }); + + it("should apply border styles", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input).toBeTruthy(); + // Should have border-related classes + expect(input?.className).toMatch(/border/); + }); + + it("should have focus styles", () => { + const { container } = render(); + const input = container.querySelector("input"); + expect(input).toBeTruthy(); + // Should have focus-related classes + expect(input?.className).toMatch(/focus:/); + }); + }); + + describe("Label Styling", () => { + it("should apply error color to label when error exists", () => { + const { container } = render(); + const label = container.querySelector("label"); + expect(label).toBeTruthy(); + }); + + it("should have default label styling", () => { + const { container } = render(); + const label = container.querySelector("label"); + expect(label).toBeTruthy(); + expect(label?.className).toBeTruthy(); + }); + }); + + describe("Accessibility", () => { + it("should connect label to input", () => { + const { container } = render(); + const label = container.querySelector("label"); + const input = container.querySelector("input"); + expect(label).toBeTruthy(); + expect(input).toBeTruthy(); + }); + + it("should show required indicator", () => { + const { container } = render(); + const label = container.querySelector("label"); + expect(label?.textContent).toContain("*"); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/input.tsx b/auth/ui/v2/apps/login/src/components/input.tsx new file mode 100644 index 0000000..bbc30d0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/input.tsx @@ -0,0 +1,105 @@ +"use client"; + +import { getComponentRoundness } from "@/lib/theme"; +import { CheckCircleIcon } from "@heroicons/react/24/solid"; +import { clsx } from "clsx"; +import { ChangeEvent, DetailedHTMLProps, forwardRef, InputHTMLAttributes, ReactNode } from "react"; + +export type TextInputProps = DetailedHTMLProps, HTMLInputElement> & { + label: string; + suffix?: string; + placeholder?: string; + defaultValue?: string; + error?: string | ReactNode; + success?: string | ReactNode; + disabled?: boolean; + onChange?: (value: ChangeEvent) => void; + onBlur?: (value: ChangeEvent) => void; + roundness?: string; // Allow override via props +}; + +const styles = (error: boolean, disabled: boolean, roundnessClasses: string = "rounded-md") => + clsx( + { + "h-[40px] mb-[2px] p-[7px] bg-input-light-background dark:bg-input-dark-background transition-colors duration-300 grow": true, + "border border-input-light-border dark:border-input-dark-border hover:border-black hover:dark:border-white focus:border-primary-light-500 focus:dark:border-primary-dark-500": true, + "focus:outline-none focus:ring-0 text-base text-black dark:text-white placeholder:italic placeholder-gray-700 dark:placeholder-gray-700": true, + "border border-warn-light-500 dark:border-warn-dark-500 hover:border-warn-light-500 hover:dark:border-warn-dark-500 focus:border-warn-light-500 focus:dark:border-warn-dark-500": + error, + "pointer-events-none text-gray-500 dark:text-gray-800 border border-input-light-border dark:border-input-dark-border hover:border-light-hoverborder hover:dark:border-hoverborder cursor-default": + disabled, + }, + roundnessClasses, // Apply the full roundness classes directly + ); + +// Helper function to get default input roundness from theme +function getDefaultInputRoundness(): string { + return getComponentRoundness("input"); +} + +export const TextInput = forwardRef( + ( + { + label, + placeholder, + defaultValue, + suffix, + required = false, + error, + disabled, + success, + onChange, + onBlur, + roundness, + ...props + }, + ref, + ) => { + // Use theme-based roundness if not explicitly provided + const actualRoundness = roundness || getDefaultInputRoundness(); + + return ( + + ); + }, +); diff --git a/auth/ui/v2/apps/login/src/components/language-provider.tsx b/auth/ui/v2/apps/login/src/components/language-provider.tsx new file mode 100644 index 0000000..9787f1b --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/language-provider.tsx @@ -0,0 +1,9 @@ +import { NextIntlClientProvider } from "next-intl"; +import { getMessages } from "next-intl/server"; +import { ReactNode } from "react"; + +export async function LanguageProvider({ children }: { children: ReactNode }) { + const messages = await getMessages(); + + return {children}; +} diff --git a/auth/ui/v2/apps/login/src/components/language-switcher.tsx b/auth/ui/v2/apps/login/src/components/language-switcher.tsx new file mode 100644 index 0000000..4e15375 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/language-switcher.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { setLanguageCookie } from "@/lib/actions/language"; +import { Lang } from "@/lib/i18n"; +import { APPEARANCE_STYLES, getComponentRoundness, getThemeConfig } from "@/lib/theme"; +import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "@headlessui/react"; +import { CheckIcon, ChevronDownIcon } from "@heroicons/react/24/outline"; +import clsx from "clsx"; +import { useLocale } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +// Helper function to get language switcher roundness from theme +function getLanguageSwitcherRoundness(): string { + return getComponentRoundness("button"); +} + +// Helper function to get card appearance styles for the language switcher +function getLanguageSwitcherCardAppearance(): string { + const themeConfig = getThemeConfig(); + const appearance = APPEARANCE_STYLES[themeConfig.appearance]; + return appearance?.card || "bg-black/5 dark:bg-white/5"; // Fallback to current styling +} + +export function LanguageSwitcher({ languages }: { languages: Lang[] }) { + const currentLocale = useLocale(); + const switcherRoundness = getLanguageSwitcherRoundness(); + const cardAppearance = getLanguageSwitcherCardAppearance(); + + const [selected, setSelected] = useState(languages.find((l) => l.code === currentLocale) || languages[0]); + + const router = useRouter(); + + const handleChange = async (language: Lang) => { + setSelected(language); + const newLocale = language.code; + + await setLanguageCookie(newLocale); + + router.refresh(); + }; + + return ( +
+ + + {selected.name} + + + {languages.map((lang) => ( + + +
{lang.name}
+
+ ))} +
+
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/layout-providers.tsx b/auth/ui/v2/apps/login/src/components/layout-providers.tsx new file mode 100644 index 0000000..2700887 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/layout-providers.tsx @@ -0,0 +1,15 @@ +"use client"; + +import { useTheme } from "next-themes"; +import { ReactNode } from "react"; + +type Props = { + children: ReactNode; +}; + +export function LayoutProviders({ children }: Props) { + const { resolvedTheme } = useTheme(); + const isDark = resolvedTheme === "dark"; + + return
{children}
; +} diff --git a/auth/ui/v2/apps/login/src/components/ldap-username-password-form.test.tsx b/auth/ui/v2/apps/login/src/components/ldap-username-password-form.test.tsx new file mode 100644 index 0000000..71b68c3 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/ldap-username-password-form.test.tsx @@ -0,0 +1,24 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { LDAPUsernamePasswordForm } from "./ldap-username-password-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/idp", () => ({ + createNewSessionForLDAP: vi.fn(), +})); + +describe("LDAPUsernamePasswordForm", () => { + afterEach(cleanup); + + test("should autofocus the username input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("username-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/ldap-username-password-form.tsx b/auth/ui/v2/apps/login/src/components/ldap-username-password-form.tsx new file mode 100644 index 0000000..a5f3209 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/ldap-username-password-form.tsx @@ -0,0 +1,128 @@ +"use client"; + +import { createNewSessionForLDAP } from "@/lib/actions/idp"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = { + loginName: string; + password: string; +}; + +type Props = { + idpId: string; + link: boolean; + requestId?: string; + organization?: string; + postErrorRedirectUrl?: string; + linkToSessionId?: string; +}; + +export function LDAPUsernamePasswordForm({ + idpId, + link, + requestId, + organization, + postErrorRedirectUrl, + linkToSessionId, +}: Props) { + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + }); + + const t = useTranslations("ldap"); + + const [error, setError] = useState(""); + + const [loading, setLoading] = useState(false); + + const router = useRouter(); + + async function submitUsernamePassword(values: Inputs) { + setError(""); + setLoading(true); + + const response = await createNewSessionForLDAP({ + idpId: idpId, + username: values.loginName, + password: values.password, + link: link, + requestId, + organization, + postErrorRedirectUrl, + linkToSessionId, + }) + .catch(() => { + setError("Could not start LDAP flow"); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response && response.error) { + setError(response.error); + return; + } + + if (response && "redirect" in response && response.redirect) { + return router.push(response.redirect); + } + } + + return ( +
+ + +
+ +
+ + {error && ( +
+ {error} +
+ )} + +
+ + + +
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/login-otp.test.tsx b/auth/ui/v2/apps/login/src/components/login-otp.test.tsx new file mode 100644 index 0000000..ae1da9b --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/login-otp.test.tsx @@ -0,0 +1,146 @@ +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { LoginOTP } from "./login-otp"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string, data?: Record) => (data ? `${key} ${JSON.stringify(data)}` : key), +})); + +vi.mock("@/lib/actions/session", () => ({ + updateOrCreateSession: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), + completeFlowOrGetUrl: vi.fn(), +})); + +describe("LoginOTP", () => { + let mockUpdateOrCreateSession: ReturnType; + + beforeEach(async () => { + vi.clearAllMocks(); + const { updateOrCreateSession } = await import("@/lib/actions/session"); + mockUpdateOrCreateSession = vi.mocked(updateOrCreateSession); + }); + + afterEach(cleanup); + + test("should autofocus the code input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("code-text-input")).toHaveFocus(); + }); + + test("should display translated fallback error when OTP verification request rejects", async () => { + mockUpdateOrCreateSession.mockRejectedValueOnce(new Error("network down")); + + render(); + + const input = screen.getByTestId("code-text-input"); + fireEvent.change(input, { target: { value: "123456" } }); + + const submitButton = screen.getByTestId("submit-button"); + await waitFor(() => { + expect(submitButton).not.toBeDisabled(); + }); + + fireEvent.click(submitButton); + + await waitFor(() => { + expect(screen.getByText("errors.couldNotVerifyCode")).toBeInTheDocument(); + }); + }); + + test("should display translated fallback error when OTP challenge request rejects", async () => { + mockUpdateOrCreateSession.mockRejectedValueOnce(new Error("challenge request failed")); + + render(); + + expect(screen.getByRole("button", { name: "verify.resendCode" })).toBeInTheDocument(); + + await waitFor(() => { + expect(screen.getByText("errors.couldNotRequestChallenge")).toBeInTheDocument(); + }); + }); + + describe("SMS resend cooldown", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + test("disables resend and counts down after the code was sent", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + mockUpdateOrCreateSession.mockResolvedValue({ sessionId: "session-1", retryAfterSeconds: 2 }); + + render(); + + const resendButton = screen.getByTestId("resend-button"); + await waitFor(() => expect(resendButton).toHaveTextContent('verify.resendCodeIn {"seconds":2}')); + expect(resendButton).toBeDisabled(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(1000); + }); + expect(resendButton).toHaveTextContent('verify.resendCodeIn {"seconds":1}'); + + await act(async () => { + await vi.advanceTimersByTimeAsync(1000); + }); + expect(resendButton).toHaveTextContent(/^verify\.resendCode$/); + expect(resendButton).not.toBeDisabled(); + }); + + test("catches up with the time that passed while the timer was suspended", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + mockUpdateOrCreateSession.mockResolvedValue({ sessionId: "session-1", retryAfterSeconds: 30 }); + + render(); + + const resendButton = screen.getByTestId("resend-button"); + await waitFor(() => expect(resendButton).toHaveTextContent('verify.resendCodeIn {"seconds":30}')); + + // the clock moves on while no timer fires, like in a suspended tab + vi.setSystemTime(Date.now() + 60_000); + await act(async () => { + await vi.advanceTimersByTimeAsync(1000); + }); + + expect(resendButton).toHaveTextContent(/^verify\.resendCode$/); + expect(resendButton).not.toBeDisabled(); + }); + + test("exposes the countdown in the button's accessible name", async () => { + mockUpdateOrCreateSession.mockResolvedValue({ sessionId: "session-1", retryAfterSeconds: 25 }); + + render(); + + expect(await screen.findByRole("button", { name: 'verify.resendCodeIn {"seconds":25}' })).toBeDisabled(); + }); + + test("shows the countdown instead of an error when the server refuses within the cooldown", async () => { + mockUpdateOrCreateSession.mockResolvedValue({ retryAfterSeconds: 25 }); + + render(); + + const resendButton = screen.getByTestId("resend-button"); + await waitFor(() => expect(resendButton).toHaveTextContent('verify.resendCodeIn {"seconds":25}')); + expect(resendButton).toBeDisabled(); + expect(screen.queryByTestId("error")).not.toBeInTheDocument(); + }); + + test("does not start a countdown for email codes", async () => { + mockUpdateOrCreateSession.mockResolvedValue({ sessionId: "session-1" }); + + render(); + + await waitFor(() => expect(mockUpdateOrCreateSession).toHaveBeenCalledTimes(1)); + const resendButton = screen.getByTestId("resend-button"); + await waitFor(() => expect(resendButton).not.toBeDisabled()); + expect(resendButton).toHaveTextContent(/^verify\.resendCode$/); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/login-otp.tsx b/auth/ui/v2/apps/login/src/components/login-otp.tsx new file mode 100644 index 0000000..bcd996b --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/login-otp.tsx @@ -0,0 +1,284 @@ +"use client"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { updateOrCreateSession } from "@/lib/actions/session"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { create } from "@zitadel/client"; +import { RequestChallengesSchema } from "@zitadel/proto/zitadel/session/v2/challenge_pb"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { useForm } from "react-hook-form"; +import { Alert, AlertType } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +// either loginName or sessionId must be provided +type Props = { + loginName?: string; + sessionId?: string; + requestId?: string; + organization?: string; + method: string; + code?: string; + loginSettings?: LoginSettings; +}; + +type Inputs = { + code: string; +}; + +export function LoginOTP({ loginName, sessionId, requestId, organization, method, code, loginSettings }: Props) { + const t = useTranslations("otp"); + + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + // seconds until the server accepts another OTP SMS request + const [resendCooldown, setResendCooldown] = useState(0); + const resendAvailableAt = useRef(0); + + const router = useRouter(); + + const initialized = useRef(false); + + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + code: code ? code : "", + }, + }); + + // resolves to the error to show to the user, if any + const updateSessionForOTPChallenge = useCallback(async (): Promise => { + let challenges; + + if (method === "email") { + // the link in the email is built on the server + challenges = create(RequestChallengesSchema, { + otpEmail: {}, + }); + } + + if (method === "sms") { + challenges = create(RequestChallengesSchema, { + otpSms: {}, + }); + } + + let response; + try { + response = await updateOrCreateSession({ + loginName, + sessionId, + organization, + challenges, + requestId, + }); + } catch { + return t("errors.couldNotRequestChallenge"); + } + + if (response && "retryAfterSeconds" in response && response.retryAfterSeconds) { + // the code was either just sent or, if the server refused, sent moments ago (e.g. before a reload): the countdown covers both + resendAvailableAt.current = Date.now() + response.retryAfterSeconds * 1000; + setResendCooldown(response.retryAfterSeconds); + return; + } + + if (response && "error" in response) { + return response.error; + } + }, [method, requestId, loginName, sessionId, organization, t]); + + useEffect(() => { + if (resendCooldown <= 0) { + return; + } + const timer = setTimeout(() => { + // timers are throttled or suspended in background tabs, so catch up with the time that actually passed + const remainingSeconds = Math.ceil((resendAvailableAt.current - Date.now()) / 1000); + setResendCooldown(Math.max(Math.min(resendCooldown - 1, remainingSeconds), 0)); + }, 1000); + return () => clearTimeout(timer); + }, [resendCooldown]); + + useEffect(() => { + if (!initialized.current && ["email", "sms"].includes(method) && !code) { + initialized.current = true; + setLoading(true); + updateSessionForOTPChallenge() + .then((challengeError) => { + if (challengeError) { + setError(challengeError); + } + }) + .finally(() => { + setLoading(false); + }); + } + }, [updateSessionForOTPChallenge, method, code]); + + async function submitCode(values: Inputs, organization?: string) { + setLoading(true); + + let body: any = { + code: values.code, + method, + }; + + if (organization) { + body.organization = organization; + } + + if (requestId) { + body.requestId = requestId; + } + + let checks; + + if (method === "sms") { + checks = create(ChecksSchema, { + otpSms: { code: values.code }, + }); + } + if (method === "email") { + checks = create(ChecksSchema, { + otpEmail: { code: values.code }, + }); + } + if (method === "time-based") { + checks = create(ChecksSchema, { + totp: { code: values.code }, + }); + } + + const response = await updateOrCreateSession({ + loginName, + sessionId, + organization, + checks, + requestId, + }) + .catch(() => { + setError(t("errors.couldNotVerifyCode")); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response && response.error) { + setError(response.error); + return; + } + + return response; + } + + function setCodeAndContinue(values: Inputs) { + return submitCode(values, organization).then(async (response) => { + if (response && "sessionId" in response) { + setLoading(true); + // Wait for 2 seconds to avoid eventual consistency issues with an OTP code being verified in the /login endpoint + await new Promise((resolve) => setTimeout(resolve, 2000)); + + // Use unified approach that handles both OIDC/SAML and regular flows + if (response.factors?.user) { + const callbackResponse = await completeFlowOrGetUrl( + requestId && response.sessionId + ? { + sessionId: response.sessionId, + requestId: requestId, + organization: response.factors?.user?.organizationId, + } + : { + loginName: response.factors.user.loginName, + organization: response.factors?.user?.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); + setLoading(false); + + handleServerActionResponse(callbackResponse, router, setSamlData, setError); + } else { + setLoading(false); + } + } + }); + } + + return ( + <> + {samlData && } +
+ {["email", "sms"].includes(method) && ( + +
+ + + + +
+
+ )} +
+ +
+ + {error && ( +
+ {error} +
+ )} + +
+ + + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/login-passkey.test.tsx b/auth/ui/v2/apps/login/src/components/login-passkey.test.tsx new file mode 100644 index 0000000..25e6b29 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/login-passkey.test.tsx @@ -0,0 +1,441 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import { NextIntlClientProvider } from "next-intl"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { LoginPasskey } from "./login-passkey"; + +// Mock next/navigation +const mockPush = vi.fn(); +vi.mock("next/navigation", () => ({ + useRouter: () => ({ + push: mockPush, + }), +})); + +// Mock server actions +vi.mock("@/lib/actions/passkeys", () => ({ + sendPasskey: vi.fn(), +})); + +vi.mock("@/lib/actions/session", () => ({ + updateOrCreateSession: vi.fn(), +})); + +// Mock navigator.credentials +const mockCredentialsGet = vi.fn(); +Object.defineProperty(global.navigator, "credentials", { + value: { + get: mockCredentialsGet, + }, + writable: true, +}); + +describe("LoginPasskey Component", () => { + let mockSendPasskey: any; + let mockUpdateSession: any; + + const messages = { + passkey: { + verify: { + title: "Authenticate with a passkey", + description: "Your device will ask for your fingerprint", + usePassword: "Use password", + submit: "Continue", + errors: { + couldNotRequestChallenge: "Could not request passkey challenge", + couldNotVerifyPasskey: "Could not verify passkey", + noResponseReceived: "Passkey verification failed - no response received", + noRedirectProvided: "Passkey verification completed but no redirect was provided", + couldNotRetrievePasskey: "An error occurred while retrieving passkey", + verificationCancelled: "Passkey verification was cancelled", + verificationFailed: "An error occurred during passkey verification", + }, + }, + }, + }; + + const renderWithIntl = (component: React.ReactElement) => { + return render( + + {component} + , + ); + }; + + beforeEach(async () => { + vi.clearAllMocks(); + mockPush.mockClear(); + mockCredentialsGet.mockClear(); + + const { sendPasskey } = await import("@/lib/actions/passkeys"); + const { updateOrCreateSession } = await import("@/lib/actions/session"); + + mockSendPasskey = vi.mocked(sendPasskey); + mockUpdateSession = vi.mocked(updateOrCreateSession); + }); + + describe("Initialization and Challenge Request", () => { + test("should display error when challenge request fails", async () => { + mockUpdateSession.mockResolvedValue({ + error: "Challenge failed", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("Could not request passkey challenge")).toBeInTheDocument(); + }); + }); + + test("should display translated error when no public key is returned", async () => { + mockUpdateSession.mockResolvedValue({ + challenges: { + webAuthN: { + publicKeyCredentialRequestOptions: {}, + }, + }, + }); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("Could not request passkey challenge")).toBeInTheDocument(); + }); + }); + + test("should trigger passkey prompt when public key is available", async () => { + const mockPublicKey = { + challenge: new Uint8Array([1, 2, 3]), + allowCredentials: [ + { + id: new Uint8Array([4, 5, 6]), + type: "public-key", + }, + ], + }; + + mockUpdateSession.mockResolvedValue({ + challenges: { + webAuthN: { + publicKeyCredentialRequestOptions: { + publicKey: mockPublicKey, + }, + }, + }, + }); + + mockCredentialsGet.mockResolvedValue({ + id: "credential-id", + rawId: new ArrayBuffer(8), + type: "public-key", + response: { + authenticatorData: new ArrayBuffer(8), + clientDataJSON: new ArrayBuffer(8), + signature: new ArrayBuffer(8), + userHandle: new ArrayBuffer(8), + }, + }); + + mockSendPasskey.mockResolvedValue({ + redirect: "/success", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(mockCredentialsGet).toHaveBeenCalled(); + }); + }); + }); + + describe("Passkey Verification", () => { + const setupSuccessfulChallenge = () => { + const mockPublicKey = { + challenge: new Uint8Array([1, 2, 3]), + allowCredentials: [ + { + id: new Uint8Array([4, 5, 6]), + type: "public-key", + }, + ], + }; + + mockUpdateSession.mockResolvedValue({ + challenges: { + webAuthN: { + publicKeyCredentialRequestOptions: { + publicKey: mockPublicKey, + }, + }, + }, + }); + + return mockPublicKey; + }; + + test("should redirect on successful verification", async () => { + setupSuccessfulChallenge(); + + mockCredentialsGet.mockResolvedValue({ + id: "credential-id", + rawId: new ArrayBuffer(8), + type: "public-key", + response: { + authenticatorData: new ArrayBuffer(8), + clientDataJSON: new ArrayBuffer(8), + signature: new ArrayBuffer(8), + userHandle: new ArrayBuffer(8), + }, + }); + + mockSendPasskey.mockResolvedValue({ + redirect: "/success", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(mockPush).toHaveBeenCalledWith("/success"); + }); + }); + + test("should display error when sendPasskey returns error", async () => { + setupSuccessfulChallenge(); + + mockCredentialsGet.mockResolvedValue({ + id: "credential-id", + rawId: new ArrayBuffer(8), + type: "public-key", + response: { + authenticatorData: new ArrayBuffer(8), + clientDataJSON: new ArrayBuffer(8), + signature: new ArrayBuffer(8), + userHandle: new ArrayBuffer(8), + }, + }); + + mockSendPasskey.mockResolvedValue({ + error: "Verification failed", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("Verification failed")).toBeInTheDocument(); + }); + }); + + test("should display error when sendPasskey returns undefined", async () => { + setupSuccessfulChallenge(); + + mockCredentialsGet.mockResolvedValue({ + id: "credential-id", + rawId: new ArrayBuffer(8), + type: "public-key", + response: { + authenticatorData: new ArrayBuffer(8), + clientDataJSON: new ArrayBuffer(8), + signature: new ArrayBuffer(8), + userHandle: new ArrayBuffer(8), + }, + }); + + mockSendPasskey.mockResolvedValue(undefined); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("Passkey verification failed - no response received")).toBeInTheDocument(); + }); + }); + + test("should display error when sendPasskey returns object without redirect", async () => { + setupSuccessfulChallenge(); + + mockCredentialsGet.mockResolvedValue({ + id: "credential-id", + rawId: new ArrayBuffer(8), + type: "public-key", + response: { + authenticatorData: new ArrayBuffer(8), + clientDataJSON: new ArrayBuffer(8), + signature: new ArrayBuffer(8), + userHandle: new ArrayBuffer(8), + }, + }); + + mockSendPasskey.mockResolvedValue({}); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("Passkey verification completed but no redirect was provided")).toBeInTheDocument(); + }); + }); + + test("should display error when credential retrieval returns null", async () => { + setupSuccessfulChallenge(); + mockCredentialsGet.mockResolvedValue(null); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("An error occurred while retrieving passkey")).toBeInTheDocument(); + }); + }); + }); + + describe("Error Handling for Passkey Cancellation", () => { + test("should display cancellation message when user cancels passkey", async () => { + const mockPublicKey = { + challenge: new Uint8Array([1, 2, 3]), + allowCredentials: [ + { + id: new Uint8Array([4, 5, 6]), + type: "public-key", + }, + ], + }; + + mockUpdateSession.mockResolvedValue({ + challenges: { + webAuthN: { + publicKeyCredentialRequestOptions: { + publicKey: mockPublicKey, + }, + }, + }, + }); + + const notAllowedError = new Error("User cancelled"); + (notAllowedError as any).name = "NotAllowedError"; + mockCredentialsGet.mockRejectedValue(notAllowedError); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("Passkey verification was cancelled")).toBeInTheDocument(); + }); + }); + + test("should display generic error for other credential errors", async () => { + const mockPublicKey = { + challenge: new Uint8Array([1, 2, 3]), + allowCredentials: [ + { + id: new Uint8Array([4, 5, 6]), + type: "public-key", + }, + ], + }; + + mockUpdateSession.mockResolvedValue({ + challenges: { + webAuthN: { + publicKeyCredentialRequestOptions: { + publicKey: mockPublicKey, + }, + }, + }, + }); + + const genericError = new Error("Unknown error"); + mockCredentialsGet.mockRejectedValue(genericError); + + renderWithIntl(); + + await waitFor(() => { + expect(screen.getByText("An error occurred during passkey verification")).toBeInTheDocument(); + }); + }); + }); + + describe("Props Handling", () => { + test("should pass sessionId to server actions when provided", async () => { + mockUpdateSession.mockResolvedValue({ + error: "Test error", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(mockUpdateSession).toHaveBeenCalledWith( + expect.objectContaining({ + sessionId: "session-123", + }), + ); + }); + }); + + test("should pass loginName to server actions when provided", async () => { + mockUpdateSession.mockResolvedValue({ + error: "Test error", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(mockUpdateSession).toHaveBeenCalledWith( + expect.objectContaining({ + loginName: "test@example.com", + }), + ); + }); + }); + + test("should pass organization to server actions when provided", async () => { + mockUpdateSession.mockResolvedValue({ + error: "Test error", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(mockUpdateSession).toHaveBeenCalledWith( + expect.objectContaining({ + organization: "org-123", + }), + ); + }); + }); + + test("should pass requestId to server actions when provided", async () => { + mockUpdateSession.mockResolvedValue({ + error: "Test error", + }); + + renderWithIntl(); + + await waitFor(() => { + expect(mockUpdateSession).toHaveBeenCalledWith( + expect.objectContaining({ + requestId: "request-123", + }), + ); + }); + }); + }); + + describe("useEffect Initialization Guard", () => { + test("should only initialize once even if component re-renders", async () => { + mockUpdateSession.mockResolvedValue({ + error: "Test error", + }); + + const { rerender } = renderWithIntl(); + + await waitFor(() => { + expect(mockUpdateSession).toHaveBeenCalledTimes(1); + }); + + // Rerender the component + rerender( + + + , + ); + + // Should still only be called once + expect(mockUpdateSession).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/login-passkey.tsx b/auth/ui/v2/apps/login/src/components/login-passkey.tsx new file mode 100644 index 0000000..6ce40a9 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/login-passkey.tsx @@ -0,0 +1,268 @@ +"use client"; + +import { coerceToArrayBuffer, coerceToBase64Url } from "@/helpers/base64"; +import { sendPasskey } from "@/lib/actions/passkeys"; +import { updateOrCreateSession } from "@/lib/actions/session"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { create, JsonObject } from "@zitadel/client"; +import { RequestChallengesSchema, UserVerificationRequirement } from "@zitadel/proto/zitadel/session/v2/challenge_pb"; +import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +// either loginName or sessionId must be provided +type Props = { + loginName?: string; + sessionId?: string; + requestId?: string; + altPassword: boolean; + login?: boolean; + organization?: string; +}; + +export function LoginPasskey({ loginName, sessionId, requestId, altPassword, organization, login = true }: Props) { + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const t = useTranslations("passkey"); + const router = useRouter(); + + const initialized = useRef(false); + + useEffect(() => { + if (!initialized.current) { + initialized.current = true; + setLoading(true); + updateOrCreateSessionForChallenge() + .then((response) => { + const pK = response?.challenges?.webAuthN?.publicKeyCredentialRequestOptions?.publicKey; + + if (!pK) { + setError(t("verify.errors.couldNotRequestChallenge")); + setLoading(false); + return; + } + + return submitLoginAndContinue(pK) + .catch((error) => { + setError(error instanceof Error ? error.message : String(error)); + return; + }) + .finally(() => { + setLoading(false); + }); + }) + .catch((error) => { + setError(error instanceof Error ? error.message : String(error)); + return; + }) + .finally(() => { + setLoading(false); + }); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + async function updateOrCreateSessionForChallenge( + userVerificationRequirement: number = login + ? UserVerificationRequirement.REQUIRED + : UserVerificationRequirement.DISCOURAGED, + ) { + setError(""); + setLoading(true); + const sessionResponse = await updateOrCreateSession({ + loginName, + sessionId, + organization, + challenges: create(RequestChallengesSchema, { + webAuthN: { + domain: "", + userVerificationRequirement, + }, + }), + requestId, + }) + .catch((error) => { + console.error(error); + setError(t("verify.errors.couldNotRequestChallenge")); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (sessionResponse && "error" in sessionResponse && sessionResponse.error) { + setError(sessionResponse.error); + return; + } + + return sessionResponse; + } + + async function submitLogin(data: JsonObject) { + setLoading(true); + try { + const response = await sendPasskey({ + loginName, + sessionId, + organization, + checks: { + webAuthN: { credentialAssertionData: data }, + } as Checks, + requestId, + }); + + const handled = handleServerActionResponse(response, router, setSamlData, setError); + + if (!handled) { + if (!response) { + setError(t("verify.errors.noResponseReceived")); + } else { + setError(t("verify.errors.noRedirectProvided")); + } + } + } catch { + setError(t("verify.errors.couldNotVerifyPasskey")); + } finally { + setLoading(false); + } + } + + async function submitLoginAndContinue(publicKey: any): Promise { + publicKey.challenge = coerceToArrayBuffer(publicKey.challenge, "publicKey.challenge"); + publicKey.allowCredentials.map((listItem: any) => { + listItem.id = coerceToArrayBuffer(listItem.id, "publicKey.allowCredentials.id"); + }); + + return navigator.credentials + .get({ + publicKey, + }) + .then((assertedCredential: any) => { + if (!assertedCredential) { + setError(t("verify.errors.couldNotRetrievePasskey")); + return; + } + + const authData = new Uint8Array(assertedCredential.response.authenticatorData); + const clientDataJSON = new Uint8Array(assertedCredential.response.clientDataJSON); + const rawId = new Uint8Array(assertedCredential.rawId); + const sig = new Uint8Array(assertedCredential.response.signature); + const userHandle = new Uint8Array(assertedCredential.response.userHandle); + const data = { + id: assertedCredential.id, + rawId: coerceToBase64Url(rawId, "rawId"), + type: assertedCredential.type, + response: { + authenticatorData: coerceToBase64Url(authData, "authData"), + clientDataJSON: coerceToBase64Url(clientDataJSON, "clientDataJSON"), + signature: coerceToBase64Url(sig, "sig"), + userHandle: coerceToBase64Url(userHandle, "userHandle"), + }, + }; + + return submitLogin(data); + }) + .catch((error) => { + // Handle passkey cancellation or errors + if (error?.name === "NotAllowedError") { + setError(t("verify.errors.verificationCancelled")); + } else { + setError(t("verify.errors.verificationFailed")); + } + console.error("Passkey verification error:", error); + }) + .finally(() => { + setLoading(false); + }); + } + + return ( +
+ {samlData && } + {error && ( +
+ {error} +
+ )} +
+ {altPassword ? ( + + ) : ( + + )} + + + +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/logo.tsx b/auth/ui/v2/apps/login/src/components/logo.tsx new file mode 100644 index 0000000..b56d7a0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/logo.tsx @@ -0,0 +1,23 @@ +type Props = { + darkSrc?: string; + lightSrc?: string; + height?: number; + width?: number; +}; + +export function Logo({ lightSrc, darkSrc, height = 40, width = 147.5 }: Props) { + return ( + <> + {darkSrc && ( +
+ logo +
+ )} + {lightSrc && ( +
+ logo +
+ )} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/otp-add-form.test.tsx b/auth/ui/v2/apps/login/src/components/otp-add-form.test.tsx new file mode 100644 index 0000000..79998b3 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/otp-add-form.test.tsx @@ -0,0 +1,84 @@ +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { OTPAddForm } from "./otp-add-form"; + +const push = vi.fn(); + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push, back: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/otp", () => ({ + addOTP: vi.fn(), +})); + +describe("OTPAddForm", () => { + let addOTP: any; + + beforeEach(async () => { + vi.clearAllMocks(); + addOTP = vi.mocked((await import("@/lib/actions/otp")).addOTP); + }); + + afterEach(cleanup); + + test("does not add the factor until the user confirms", () => { + render(); + + expect(addOTP).not.toHaveBeenCalled(); + }); + + test("shows the success message and continue link after adding", async () => { + addOTP.mockResolvedValue({ success: true }); + const { getByTestId, findByText } = render( + , + ); + + fireEvent.click(getByTestId("add-button")); + + expect(await findByText("set.emailAdded")).toBeTruthy(); + expect(addOTP).toHaveBeenCalledWith({ method: "email", sessionId: "session-1" }); + expect(getByTestId("submit-button").closest("a")?.getAttribute("href")).toBe("/signedin?loginName=user"); + expect(push).not.toHaveBeenCalled(); + }); + + test("continues to the code check directly with checkAfter", async () => { + addOTP.mockResolvedValue({ success: true }); + const { getByTestId } = render( + , + ); + + fireEvent.click(getByTestId("add-button")); + + await waitFor(() => expect(push).toHaveBeenCalledWith("/otp/sms?loginName=user")); + }); + + test("shows the error and no success message when adding fails", async () => { + addOTP.mockResolvedValue({ error: "errors.couldNotAddSms" }); + const { getByTestId, findByText, queryByText } = render( + , + ); + + fireEvent.click(getByTestId("add-button")); + + expect(await findByText("errors.couldNotAddSms")).toBeTruthy(); + expect(queryByText("set.smsAdded")).toBeNull(); + expect(push).not.toHaveBeenCalled(); + }); + + test("shows a translated error when the action fails unexpectedly", async () => { + addOTP.mockRejectedValue(new Error("network")); + const { getByTestId, findByText } = render( + , + ); + + fireEvent.click(getByTestId("add-button")); + + expect(await findByText("errors.couldNotAddEmail")).toBeTruthy(); + expect(push).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/otp-add-form.tsx b/auth/ui/v2/apps/login/src/components/otp-add-form.tsx new file mode 100644 index 0000000..39239db --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/otp-add-form.tsx @@ -0,0 +1,92 @@ +"use client"; + +import { addOTP } from "@/lib/actions/otp"; +import { useTranslations } from "next-intl"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Alert, AlertType } from "./alert"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Props = { + method: "email" | "sms"; + sessionId: string; + urlToContinue: string; + checkAfter?: boolean; +}; + +export function OTPAddForm({ method, sessionId, urlToContinue, checkAfter }: Props) { + const router = useRouter(); + const t = useTranslations("otp"); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + const [added, setAdded] = useState(false); + + async function submit() { + setLoading(true); + setError(""); + + const response = await addOTP({ method, sessionId }) + .catch(() => ({ error: t(method === "email" ? "errors.couldNotAddEmail" : "errors.couldNotAddSms") })) + .finally(() => setLoading(false)); + + if ("error" in response) { + setError(response.error); + return; + } + + // if attribute is set, validate MFA after it is set up + if (checkAfter) { + router.push(urlToContinue); + return; + } + + setAdded(true); + } + + if (added) { + return ( +
+ + + +
+ + + + +
+
+ ); + } + + return ( +
+ {error && ( +
+ {error} +
+ )} +
+ + + +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/password-complexity.test.tsx b/auth/ui/v2/apps/login/src/components/password-complexity.test.tsx new file mode 100644 index 0000000..cfbf568 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/password-complexity.test.tsx @@ -0,0 +1,281 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { NextIntlClientProvider } from "next-intl"; +import { afterEach, describe, expect, test } from "vitest"; +import { PasswordComplexity } from "./password-complexity"; + +describe("", () => { + const messages = { + password: { + complexity: { + length: "Must be at least {minLength} characters long.", + hasSymbol: "Must include a symbol.", + hasNumber: "Must include a number.", + hasUppercase: "Must include an uppercase letter.", + hasLowercase: "Must include a lowercase letter.", + equals: "Password confirmation matched.", + matches: "Matches", + doesNotMatch: "Doesn't match", + }, + }, + }; + + afterEach(cleanup); + + test("should render length check when minLength is defined", () => { + render( + + + , + ); + + const lengthCheck = screen.getByTestId("length-check"); + expect(lengthCheck).toBeInTheDocument(); + expect(lengthCheck.querySelector("svg")).toBeInTheDocument(); + }); + + test("should not render length check when minLength is undefined", () => { + render( + + + , + ); + + expect(screen.queryByTestId("length-check")).toBeInTheDocument(); + }); + + test("should render check icon when password meets length requirement", () => { + render( + + + , + ); + + const lengthCheck = screen.getByTestId("length-check"); + const svg = lengthCheck.querySelector("svg"); + expect(svg).toHaveClass("text-green-500"); + }); + + test("should render cross icon when password does not meet length requirement", () => { + render( + + + , + ); + + const lengthCheck = screen.getByTestId("length-check"); + const svg = lengthCheck.querySelector("svg"); + expect(svg).toHaveClass("text-warn-light-500"); + }); + + test("should render all complexity checks when all requirements are enabled", () => { + render( + + + , + ); + + expect(screen.getByTestId("length-check")).toBeInTheDocument(); + expect(screen.getByTestId("symbol-check")).toBeInTheDocument(); + expect(screen.getByTestId("number-check")).toBeInTheDocument(); + expect(screen.getByTestId("uppercase-check")).toBeInTheDocument(); + expect(screen.getByTestId("lowercase-check")).toBeInTheDocument(); + expect(screen.getByTestId("equal-check")).toBeInTheDocument(); + }); + + test("should not render symbol check when requiresSymbol is false", () => { + render( + + + , + ); + + expect(screen.queryByTestId("symbol-check")).not.toBeInTheDocument(); + expect(screen.getByTestId("number-check")).toBeInTheDocument(); + expect(screen.getByTestId("uppercase-check")).toBeInTheDocument(); + expect(screen.getByTestId("lowercase-check")).toBeInTheDocument(); + }); + + test("should not render number check when requiresNumber is false", () => { + render( + + + , + ); + + expect(screen.getByTestId("symbol-check")).toBeInTheDocument(); + expect(screen.queryByTestId("number-check")).not.toBeInTheDocument(); + expect(screen.getByTestId("uppercase-check")).toBeInTheDocument(); + expect(screen.getByTestId("lowercase-check")).toBeInTheDocument(); + }); + + test("should not render uppercase check when requiresUppercase is false", () => { + render( + + + , + ); + + expect(screen.getByTestId("symbol-check")).toBeInTheDocument(); + expect(screen.getByTestId("number-check")).toBeInTheDocument(); + expect(screen.queryByTestId("uppercase-check")).not.toBeInTheDocument(); + expect(screen.getByTestId("lowercase-check")).toBeInTheDocument(); + }); + + test("should not render lowercase check when requiresLowercase is false", () => { + render( + + + , + ); + + expect(screen.getByTestId("symbol-check")).toBeInTheDocument(); + expect(screen.getByTestId("number-check")).toBeInTheDocument(); + expect(screen.getByTestId("uppercase-check")).toBeInTheDocument(); + expect(screen.queryByTestId("lowercase-check")).not.toBeInTheDocument(); + }); + + test("should only render length and equals checks when all other requirements are disabled", () => { + render( + + + , + ); + + expect(screen.getByTestId("length-check")).toBeInTheDocument(); + expect(screen.getByTestId("equal-check")).toBeInTheDocument(); + expect(screen.queryByTestId("symbol-check")).not.toBeInTheDocument(); + expect(screen.queryByTestId("number-check")).not.toBeInTheDocument(); + expect(screen.queryByTestId("uppercase-check")).not.toBeInTheDocument(); + expect(screen.queryByTestId("lowercase-check")).not.toBeInTheDocument(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/password-complexity.tsx b/auth/ui/v2/apps/login/src/components/password-complexity.tsx new file mode 100644 index 0000000..988f815 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/password-complexity.tsx @@ -0,0 +1,113 @@ +import { Translated } from "@/components/translated"; +import { lowerCaseValidator, numberValidator, symbolValidator, upperCaseValidator } from "@/helpers/validators"; +import { PasswordComplexitySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { useTranslations } from "next-intl"; + +type Props = { + passwordComplexitySettings: PasswordComplexitySettings; + password: string; + equals: boolean; +}; + +function CheckIcon({ title }: { title: string }) { + return ( + + {title} + + + ); +} + +function CrossIcon({ title }: { title: string }) { + return ( + + {title} + + + ); +} + +function renderIcon(matched: boolean, t: ReturnType) { + return matched ? : ; +} +const desc = "text-14px leading-4 text-input-light-label dark:text-input-dark-label"; + +export function PasswordComplexity({ passwordComplexitySettings, password, equals }: Props) { + const t = useTranslations("password"); + const hasMinLength = password?.length >= passwordComplexitySettings.minLength; + const hasSymbol = symbolValidator(password); + const hasNumber = numberValidator(password); + const hasUppercase = upperCaseValidator(password); + const hasLowercase = lowerCaseValidator(password); + + return ( +
+ {passwordComplexitySettings.minLength != undefined ? ( +
+ {renderIcon(hasMinLength, t)} + + + +
+ ) : null} + {passwordComplexitySettings.requiresSymbol && ( +
+ {renderIcon(hasSymbol, t)} + + + +
+ )} + {passwordComplexitySettings.requiresNumber && ( +
+ {renderIcon(hasNumber, t)} + + + +
+ )} + {passwordComplexitySettings.requiresUppercase && ( +
+ {renderIcon(hasUppercase, t)} + + + +
+ )} + {passwordComplexitySettings.requiresLowercase && ( +
+ {renderIcon(hasLowercase, t)} + + + +
+ )} +
+ {renderIcon(equals, t)} + + + +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/password-form.test.tsx b/auth/ui/v2/apps/login/src/components/password-form.test.tsx new file mode 100644 index 0000000..17f3cb6 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/password-form.test.tsx @@ -0,0 +1,25 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { PasswordForm } from "./password-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/password", () => ({ + sendPassword: vi.fn(), + resetPassword: vi.fn(), +})); + +describe("PasswordForm", () => { + afterEach(cleanup); + + test("should autofocus the password input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("password-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/password-form.tsx b/auth/ui/v2/apps/login/src/components/password-form.tsx new file mode 100644 index 0000000..f1a8fe0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/password-form.tsx @@ -0,0 +1,168 @@ +"use client"; + +import { resetPassword, sendPassword } from "@/lib/actions/password"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { create } from "@zitadel/client"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { useForm } from "react-hook-form"; +import { Alert, AlertType } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = { + password: string; +}; + +type Props = { + loginSettings: LoginSettings | undefined; + loginName: string; + organization?: string; + defaultOrganization?: string; + requestId?: string; +}; + +export function PasswordForm({ loginSettings, loginName, organization, defaultOrganization, requestId }: Props) { + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + }); + + const t = useTranslations("password"); + + const [info, setInfo] = useState(""); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const [loading, setLoading] = useState(false); + + const router = useRouter(); + + async function submitPassword(values: Inputs) { + setError(""); + setLoading(true); + + try { + const response = await sendPassword({ + loginName, + organization, + defaultOrganization, + checks: create(ChecksSchema, { + password: { password: values.password }, + }), + requestId, + }); + + handleServerActionResponse(response, router, setSamlData, setError); + } catch { + setError(t("verify.errors.couldNotVerifyPassword")); + } finally { + setLoading(false); + } + } + + async function resetPasswordAndContinue() { + setError(""); + setInfo(""); + setLoading(true); + + const response = await resetPassword({ + loginName, + organization, + defaultOrganization, + requestId, + }) + .catch(() => { + setError(t("errors.couldNotSendResetLink")); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response) { + setError(response.error as string); + return; + } + + setInfo(t("verify.info.passwordResetSent")); + + const params = new URLSearchParams({ + loginName: loginName, + }); + + if (organization) { + params.append("organization", organization); + } + + if (requestId) { + params.append("requestId", requestId); + } + + return router.push("/password/set?" + params); + } + + return ( + <> + {samlData && } +
+
+ + {!loginSettings?.hidePasswordReset && ( + + )} + + {loginName && } +
+ + {info && ( +
+ {info} +
+ )} + + {error && ( +
+ {error} +
+ )} + +
+ + + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/privacy-policy-checkboxes.test.tsx b/auth/ui/v2/apps/login/src/components/privacy-policy-checkboxes.test.tsx new file mode 100644 index 0000000..ab73e3c --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/privacy-policy-checkboxes.test.tsx @@ -0,0 +1,37 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { create } from "@zitadel/client"; +import { LegalAndSupportSettingsSchema } from "@zitadel/proto/zitadel/settings/v2/legal_settings_pb"; +import type { AnchorHTMLAttributes } from "react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { PrivacyPolicyCheckboxes } from "./privacy-policy-checkboxes"; + +vi.mock("next-intl", () => ({ + useLocale: () => "fr", + useTranslations: () => (key: string) => key, +})); + +vi.mock("next/link", () => ({ + default: ({ href, children, ...props }: AnchorHTMLAttributes & { href: string }) => ( + + {children} + + ), +})); + +describe("PrivacyPolicyCheckboxes", () => { + afterEach(cleanup); + + test("resolves language placeholders in legal links with the active locale", () => { + const legal = create(LegalAndSupportSettingsSchema, { + tosLink: "https://demo.com/tos-{{.Lang}}", + privacyPolicyLink: "https://demo.com/privacy-{{.Lang}}", + helpLink: "https://demo.com/help-{{.Lang}}", + }); + + render(); + + expect(screen.getByTestId("tos-link")).toHaveAttribute("href", "https://demo.com/tos-fr"); + expect(screen.getByTestId("privacy-policy-link")).toHaveAttribute("href", "https://demo.com/privacy-fr"); + expect(screen.getByTestId("help-link")).toHaveAttribute("href", "https://demo.com/help-fr"); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/privacy-policy-checkboxes.tsx b/auth/ui/v2/apps/login/src/components/privacy-policy-checkboxes.tsx new file mode 100644 index 0000000..0998ad5 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/privacy-policy-checkboxes.tsx @@ -0,0 +1,118 @@ +"use client"; +import { resolveLocalizedLegalLink } from "@/lib/legal-links"; +import { LegalAndSupportSettings } from "@zitadel/proto/zitadel/settings/v2/legal_settings_pb"; +import { useLocale } from "next-intl"; +import Link from "next/link"; +import { useState } from "react"; +import { Checkbox } from "./checkbox"; +import { Translated } from "./translated"; + +type Props = { + legal: LegalAndSupportSettings; + onChange: (allAccepted: boolean) => void; +}; + +type AcceptanceState = { + tosAccepted: boolean; + privacyPolicyAccepted: boolean; +}; + +export function PrivacyPolicyCheckboxes({ legal, onChange }: Props) { + const locale = useLocale(); + const [acceptanceState, setAcceptanceState] = useState({ + tosAccepted: false, + privacyPolicyAccepted: false, + }); + const helpLink = resolveLocalizedLegalLink(legal?.helpLink, locale); + const tosLink = resolveLocalizedLegalLink(legal?.tosLink, locale); + const privacyPolicyLink = resolveLocalizedLegalLink(legal?.privacyPolicyLink, locale); + + // Helper function to check if all required checkboxes are accepted + const checkAllAccepted = (newState: AcceptanceState) => { + const hasTosLink = !!tosLink; + const hasPrivacyLink = !!privacyPolicyLink; + + // Check that all required checkboxes are accepted + return (!hasTosLink || newState.tosAccepted) && (!hasPrivacyLink || newState.privacyPolicyAccepted); + }; + + return ( + <> +

+ + {helpLink && ( + + + + + + + + )} +

+ {tosLink && ( +
+ { + const newState = { + ...acceptanceState, + tosAccepted: checked, + }; + setAcceptanceState(newState); + onChange(checkAllAccepted(newState)); + }} + data-testid="tos-checkbox" + /> + +
+

+ + + +

+
+
+ )} + {privacyPolicyLink && ( +
+ { + const newState = { + ...acceptanceState, + privacyPolicyAccepted: checked, + }; + setAcceptanceState(newState); + onChange(checkAllAccepted(newState)); + }} + data-testid="privacy-policy-checkbox" + /> + +
+

+ + + +

+
+
+ )} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/register-form-idp-incomplete.test.tsx b/auth/ui/v2/apps/login/src/components/register-form-idp-incomplete.test.tsx new file mode 100644 index 0000000..d8e0eed --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/register-form-idp-incomplete.test.tsx @@ -0,0 +1,38 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { RegisterFormIDPIncomplete } from "./register-form-idp-incomplete"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/register", () => ({ + registerUserAndLinkToIDP: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), +})); + +const defaultProps = { + organization: "org-1", + idpIntent: { idpIntentId: "intent-1", idpIntentToken: "token-1" }, +}; + +describe("RegisterFormIDPIncomplete", () => { + afterEach(cleanup); + + test("should autofocus the username input when idpUserName is not provided", () => { + const { getByTestId } = render(); + expect(getByTestId("username-text-input")).toHaveFocus(); + }); + + test("should autofocus the firstname input when idpUserName is provided", () => { + const { getByTestId } = render(); + expect(getByTestId("firstname-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/register-form-idp-incomplete.tsx b/auth/ui/v2/apps/login/src/components/register-form-idp-incomplete.tsx new file mode 100644 index 0000000..ed44295 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/register-form-idp-incomplete.tsx @@ -0,0 +1,168 @@ +"use client"; + +import { registerUserAndLinkToIDP } from "@/lib/actions/register"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { FieldValues, useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = + | { + firstname: string; + lastname: string; + email: string; + username?: string; + } + | FieldValues; + +type Props = { + organization: string; + requestId?: string; + idpIntent: { + idpIntentId: string; + idpIntentToken: string; + }; + defaultValues?: { + firstname?: string; + lastname?: string; + email?: string; + }; + idpUserName?: string; + flowFingerprint?: string; +}; + +export function RegisterFormIDPIncomplete({ + organization, + requestId, + idpIntent, + defaultValues, + idpUserName, + flowFingerprint, +}: Props) { + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + email: defaultValues?.email ?? "", + firstname: defaultValues?.firstname ?? "", + lastname: defaultValues?.lastname ?? "", + }, + }); + + const t = useTranslations("register"); + const router = useRouter(); + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + async function submitAndRegister(values: Inputs) { + setLoading(true); + try { + const response = await registerUserAndLinkToIDP({ + idpUserName: idpUserName ? idpUserName : values.username, + email: values.email, + firstName: values.firstname, + lastName: values.lastname, + organization: organization, + requestId: requestId, + idpIntent: idpIntent, + flowFingerprint: flowFingerprint, + }); + + handleServerActionResponse(response, router, setSamlData, setError); + } catch { + setError("Could not register user"); + } finally { + setLoading(false); + } + } + + const { errors } = formState; + + return ( + <> + {samlData && } +
+
+ {!idpUserName && ( +
+ +
+ )} +
+
+ +
+
+ +
+
+
+ +
+
+ + {error && ( +
+ {error} +
+ )} + +
+ + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/register-form.test.tsx b/auth/ui/v2/apps/login/src/components/register-form.test.tsx new file mode 100644 index 0000000..7fdd1f2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/register-form.test.tsx @@ -0,0 +1,32 @@ +import { cleanup, render } from "@testing-library/react"; +import { create } from "@zitadel/client"; +import { LegalAndSupportSettingsSchema } from "@zitadel/proto/zitadel/settings/v2/legal_settings_pb"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { RegisterForm } from "./register-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/register", () => ({ + registerUser: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), +})); + +const defaultLegal = create(LegalAndSupportSettingsSchema, {}); + +describe("RegisterForm", () => { + afterEach(cleanup); + + test("should autofocus the firstname input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("firstname-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/register-form.tsx b/auth/ui/v2/apps/login/src/components/register-form.tsx new file mode 100644 index 0000000..d1ad9ac --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/register-form.tsx @@ -0,0 +1,210 @@ +"use client"; + +import { registerUser } from "@/lib/actions/register"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { LegalAndSupportSettings } from "@zitadel/proto/zitadel/settings/v2/legal_settings_pb"; +import { LoginSettings, PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { FieldValues, useForm } from "react-hook-form"; +import { Alert, AlertType } from "./alert"; +import { AuthenticationMethod, AuthenticationMethodRadio, methods } from "./authentication-method-radio"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { PrivacyPolicyCheckboxes } from "./privacy-policy-checkboxes"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = + | { + firstname: string; + lastname: string; + email: string; + } + | FieldValues; + +type Props = { + legal: LegalAndSupportSettings; + firstname?: string; + lastname?: string; + email?: string; + organization: string; + requestId?: string; + loginSettings?: LoginSettings; + idpCount: number; +}; + +export function RegisterForm({ + legal, + email, + firstname, + lastname, + organization, + requestId, + loginSettings, + idpCount = 0, +}: Props) { + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + email: email ?? "", + firstname: firstname ?? "", + lastname: lastname ?? "", + }, + }); + + const t = useTranslations("register"); + + const [loading, setLoading] = useState(false); + const [selected, setSelected] = useState(methods[0]); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const router = useRouter(); + + async function submitAndRegister(values: Inputs) { + setLoading(true); + try { + const response = await registerUser({ + email: values.email, + firstName: values.firstname, + lastName: values.lastname, + organization: organization, + requestId: requestId, + }); + + handleServerActionResponse(response, router, setSamlData, setError); + + return response; + } catch { + setError(t("errors.couldNotRegisterUser")); + } finally { + setLoading(false); + } + } + + async function submitAndContinue(value: Inputs, withPassword: boolean = false) { + const registerParams: any = value; + + if (organization) { + registerParams.organization = organization; + } + + if (requestId) { + registerParams.requestId = requestId; + } + + // redirect user to /register/password if password is chosen + if (withPassword) { + return router.push(`/register/password?` + new URLSearchParams(registerParams)); + } else { + return submitAndRegister(value); + } + } + + const { errors } = formState; + + const [tosAndPolicyAccepted, setTosAndPolicyAccepted] = useState(false); + + // Check if legal acceptance is required + const isLegalAcceptanceRequired = !!(legal?.tosLink || legal?.privacyPolicyLink); + const canSubmit = formState.isValid && (!isLegalAcceptanceRequired || tosAndPolicyAccepted); + + return ( + <> + {samlData && } +
+
+
+ +
+
+ +
+
+ +
+
+ {(legal?.tosLink || legal?.privacyPolicyLink) && ( + + )} + {/* show chooser if both methods are allowed */} + {loginSettings && loginSettings.allowLocalAuthentication && loginSettings.passkeysType == PasskeysType.ALLOWED && ( + <> +

+ +

+ +
+ +
+ + )} + {!loginSettings?.allowLocalAuthentication && + loginSettings?.passkeysType !== PasskeysType.ALLOWED && + (!loginSettings?.allowExternalIdp || !idpCount) && ( +
+ + + +
+ )} + + {error && ( +
+ {error} +
+ )} + +
+ + +
+ + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/register-passkey.tsx b/auth/ui/v2/apps/login/src/components/register-passkey.tsx new file mode 100644 index 0000000..6d92a68 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/register-passkey.tsx @@ -0,0 +1,244 @@ +"use client"; + +import { coerceToArrayBuffer, coerceToBase64Url } from "@/helpers/base64"; +import { registerPasskeyLink, verifyPasskeyRegistration } from "@/lib/actions/passkeys"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = Record; + +type Props = { + sessionId?: string; + userId?: string; + isPrompt: boolean; + requestId?: string; + organization?: string; + code?: string; + codeId?: string; + loginName?: string; +}; + +export function RegisterPasskey({ + sessionId, + userId, + isPrompt, + organization, + requestId, + code, + codeId, + loginName: initialLoginName, +}: Props) { + const { handleSubmit, formState } = useForm({ + mode: "onChange", + }); + + const [error, setError] = useState(""); + + const [loading, setLoading] = useState(false); + + const router = useRouter(); + + const continueAndLogin = useCallback( + (loginName?: string) => { + const params = new URLSearchParams(); + + if (organization) { + params.set("organization", organization); + } + + if (requestId) { + params.set("requestId", requestId); + } + + if (sessionId) { + params.set("sessionId", sessionId); + } + + if (userId) { + params.set("userId", userId); + } + + if (loginName ?? initialLoginName) { + params.set("loginName", loginName ?? initialLoginName ?? ""); + } + + router.push("/passkey?" + params); + }, + [organization, requestId, sessionId, userId, initialLoginName, router], + ); + + async function submitVerify( + passkeyId: string, + passkeyName: string, + publicKeyCredential: any, + currentSessionId?: string, + currentUserId?: string, + ) { + setLoading(true); + const response = await verifyPasskeyRegistration({ + passkeyId, + passkeyName, + publicKeyCredential, + sessionId: currentSessionId, + userId: currentUserId, + }) + .catch(() => { + setError("Could not verify Passkey"); + return; + }) + .finally(() => { + setLoading(false); + }); + + return response; + } + + const submitRegisterAndContinue = useCallback(async (): Promise => { + // Require either sessionId or userId + if (!sessionId && !userId) { + setError("Missing session or user information"); + return; + } + + setLoading(true); + + let regReq; + + if (sessionId) { + regReq = { sessionId }; + } else if (userId && code && codeId) { + regReq = { userId, code, codeId }; + } else { + setError("Missing code for user-based registration"); + setLoading(false); + return; + } + + const resp = await registerPasskeyLink(regReq) + .catch(() => { + setError("Could not register passkey"); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (!resp) { + setError("An error on registering passkey"); + return; + } + + if ("error" in resp && resp.error) { + setError(resp.error); + return; + } + + if (!("passkeyId" in resp)) { + setError("An error on registering passkey"); + return; + } + + const passkeyId = resp.passkeyId; + const options: CredentialCreationOptions = (resp.publicKeyCredentialCreationOptions as CredentialCreationOptions) ?? {}; + + if (!options.publicKey) { + setError("An error on registering passkey"); + return; + } + + options.publicKey.challenge = coerceToArrayBuffer(options.publicKey.challenge, "challenge"); + options.publicKey.user.id = coerceToArrayBuffer(options.publicKey.user.id, "userid"); + if (options.publicKey.excludeCredentials) { + options.publicKey.excludeCredentials.map((cred: any) => { + cred.id = coerceToArrayBuffer(cred.id as string, "excludeCredentials.id"); + return cred; + }); + } + + const credentials = await navigator.credentials.create(options); + + if ( + !credentials || + !(credentials as any).response?.attestationObject || + !(credentials as any).response?.clientDataJSON || + !(credentials as any).rawId + ) { + setError("An error on registering passkey"); + return; + } + + const attestationObject = (credentials as any).response.attestationObject; + const clientDataJSON = (credentials as any).response.clientDataJSON; + const rawId = (credentials as any).rawId; + + const data = { + id: credentials.id, + rawId: coerceToBase64Url(rawId, "rawId"), + type: credentials.type, + response: { + attestationObject: coerceToBase64Url(attestationObject, "attestationObject"), + clientDataJSON: coerceToBase64Url(clientDataJSON, "clientDataJSON"), + }, + }; + + const verificationResponse = await submitVerify(passkeyId, "", data, sessionId, userId); + + if (!verificationResponse) { + setError("Could not verify Passkey!"); + return; + } + + continueAndLogin(verificationResponse.loginName); + }, [sessionId, userId, code, codeId, continueAndLogin]); + + // Auto-submit when code is provided (similar to VerifyForm) + useEffect(() => { + if (code) { + submitRegisterAndContinue(); + } + }, [code, submitRegisterAndContinue]); + + return ( +
+ {error && ( +
+ {error} +
+ )} + +
+ {isPrompt ? ( + + ) : ( + + )} + + + +
+
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/register-u2f.tsx b/auth/ui/v2/apps/login/src/components/register-u2f.tsx new file mode 100644 index 0000000..96b6686 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/register-u2f.tsx @@ -0,0 +1,205 @@ +"use client"; + +import { coerceToArrayBuffer, coerceToBase64Url } from "@/helpers/base64"; +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { addU2F, verifyU2F } from "@/lib/actions/u2f"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { RegisterU2FResponse } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Props = { + loginName?: string; + sessionId: string; + requestId?: string; + organization?: string; + checkAfter: boolean; + loginSettings?: LoginSettings; +}; + +export function RegisterU2f({ loginName, sessionId, organization, requestId, checkAfter, loginSettings }: Props) { + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const [loading, setLoading] = useState(false); + + const router = useRouter(); + + async function submitVerify(u2fId: string, passkeyName: string, publicKeyCredential: any, sessionId: string) { + setError(""); + setLoading(true); + const response = await verifyU2F({ + u2fId, + passkeyName, + publicKeyCredential, + sessionId, + }) + .catch(() => { + setError("An error on verifying passkey occurred"); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response && response?.error) { + setError(response?.error); + return; + } + + return response; + } + + async function submitRegisterAndContinue(): Promise { + setError(""); + setLoading(true); + const response = await addU2F({ + sessionId, + }) + .catch(() => { + setError("An error on registering passkey"); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response && response?.error) { + setError(response?.error); + return; + } + + if (!response || !("u2fId" in response)) { + setError("An error on registering passkey"); + return; + } + + const u2fResponse = response as unknown as RegisterU2FResponse; + + const u2fId = u2fResponse.u2fId; + const options: CredentialCreationOptions = + (u2fResponse?.publicKeyCredentialCreationOptions as CredentialCreationOptions) ?? {}; + + if (options.publicKey) { + options.publicKey.challenge = coerceToArrayBuffer(options.publicKey.challenge, "challenge"); + options.publicKey.user.id = coerceToArrayBuffer(options.publicKey.user.id, "userid"); + if (options.publicKey.excludeCredentials) { + options.publicKey.excludeCredentials.map((cred: any) => { + cred.id = coerceToArrayBuffer(cred.id as string, "excludeCredentials.id"); + return cred; + }); + } + + const resp = await navigator.credentials.create(options); + + if ( + !resp || + !(resp as any).response.attestationObject || + !(resp as any).response.clientDataJSON || + !(resp as any).rawId + ) { + setError("An error on registering passkey"); + return; + } + + const attestationObject = (resp as any).response.attestationObject; + const clientDataJSON = (resp as any).response.clientDataJSON; + const rawId = (resp as any).rawId; + + const data = { + id: resp.id, + rawId: coerceToBase64Url(rawId, "rawId"), + type: resp.type, + response: { + attestationObject: coerceToBase64Url(attestationObject, "attestationObject"), + clientDataJSON: coerceToBase64Url(clientDataJSON, "clientDataJSON"), + }, + }; + + const submitResponse = await submitVerify(u2fId, "", data, sessionId); + + if (!submitResponse) { + setError("An error on verifying passkey"); + return; + } + + if (checkAfter) { + const paramsToContinue = new URLSearchParams({}); + + if (sessionId) { + paramsToContinue.append("sessionId", sessionId); + } + if (loginName) { + paramsToContinue.append("loginName", loginName); + } + if (organization) { + paramsToContinue.append("organization", organization); + } + if (requestId) { + paramsToContinue.append("requestId", requestId); + } + + return router.push(`/u2f?` + paramsToContinue); + } else { + if (requestId && sessionId) { + const callbackResponse = await completeFlowOrGetUrl( + { + sessionId: sessionId, + requestId: requestId, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + + handleServerActionResponse(callbackResponse, router, setSamlData, setError); + } else if (loginName) { + const callbackResponse = await completeFlowOrGetUrl( + { + loginName: loginName, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + + handleServerActionResponse(callbackResponse, router, setSamlData, setError); + } + } + } + } + + return ( + <> + {samlData && } +
+ {error && ( +
+ {error} +
+ )} + +
+ + + + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/self-service-menu.tsx b/auth/ui/v2/apps/login/src/components/self-service-menu.tsx new file mode 100644 index 0000000..63b9e79 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/self-service-menu.tsx @@ -0,0 +1,36 @@ +import Link from "next/link"; + +export function SelfServiceMenu() { + const list: any[] = []; + + // if (!!config.selfservice.change_password.enabled) { + // list.push({ + // link: + // `/me/change-password?` + + // new URLSearchParams({ + // sessionId: sessionId, + // }), + // name: "Change password", + // }); + // } + + return ( +
+ {list.map((menuitem, index) => { + return ; + })} +
+ ); +} + +const SelfServiceItem = ({ name, link }: { name: string; link: string }) => { + return ( + + {name} + + ); +}; diff --git a/auth/ui/v2/apps/login/src/components/session-clear-item.tsx b/auth/ui/v2/apps/login/src/components/session-clear-item.tsx new file mode 100644 index 0000000..d35f5c0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/session-clear-item.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { clearSession } from "@/lib/actions/session"; +import { timestampDate } from "@zitadel/client"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import moment from "moment"; +import { useLocale, useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Alert } from "./alert"; +import { Avatar } from "./avatar"; +import { isSessionPrimaryFactorAndLifetimeValid } from "./session-item"; +import { Translated } from "./translated"; + +export function SessionClearItem({ session, reload }: { session: Session; reload: () => void }) { + const currentLocale = useLocale(); + moment.locale(currentLocale === "zh" ? "zh-cn" : currentLocale); + const t = useTranslations("error"); + + const [_loading, setLoading] = useState(false); + + /** + * Returns true when the session was removed (server-side and from the cookie). + * On failure the error is shown and the card must stay in the list. + */ + async function clearSessionId(id: string): Promise { + setLoading(true); + setError(null); + try { + const response = await clearSession({ sessionId: id }); + if (response && "error" in response && response.error) { + setError(response.error); + return false; + } + return true; + } catch { + setError(t("couldNotClearSession")); + return false; + } finally { + setLoading(false); + } + } + + const { valid, verifiedAt } = isSessionPrimaryFactorAndLifetimeValid(session); + + const [error, setError] = useState(null); + + // TODO: To we have to call this? + useRouter(); + + return ( + <> + + {error && {error}} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/session-item.tsx b/auth/ui/v2/apps/login/src/components/session-item.tsx new file mode 100644 index 0000000..aec3275 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/session-item.tsx @@ -0,0 +1,165 @@ +"use client"; + +import { sendLoginname } from "@/lib/actions/loginname"; +import { clearSession, continueWithSession, ContinueWithSessionCommand } from "@/lib/actions/session"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { XCircleIcon } from "@heroicons/react/24/outline"; +import * as Tooltip from "@radix-ui/react-tooltip"; +import { Timestamp, timestampDate } from "@zitadel/client"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import moment from "moment"; +import { useLocale, useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import React, { useState } from "react"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { Avatar } from "./avatar"; +import { Translated } from "./translated"; + +export function isSessionPrimaryFactorAndLifetimeValid(session: Partial): { + valid: boolean; + verifiedAt?: Timestamp; +} { + const validPassword = session?.factors?.password?.verifiedAt; + const validPasskey = session?.factors?.webAuthN?.verifiedAt; + const validIDP = session?.factors?.intent?.verifiedAt; + + const stillValid = session.expirationDate ? timestampDate(session.expirationDate) > new Date() : true; + + const verifiedAt = validPassword || validPasskey || validIDP; + const valid = !!((validPassword || validPasskey || validIDP) && stillValid); + + return { valid, verifiedAt }; +} + +export function SessionItem({ session, reload, requestId }: { session: Session; reload: () => void; requestId?: string }) { + const currentLocale = useLocale(); + moment.locale(currentLocale === "zh" ? "zh-cn" : currentLocale); + const t = useTranslations("error"); + + const [_loading, setLoading] = useState(false); + + /** + * Returns true when the session was removed (server-side and from the cookie). + * On failure the error is shown and the card must stay in the list. + */ + async function clearSessionId(id: string): Promise { + setLoading(true); + setError(null); + try { + const response = await clearSession({ sessionId: id }); + if (response && "error" in response && response.error) { + setError(response.error); + return false; + } + return true; + } catch { + setError(t("couldNotClearSession")); + return false; + } finally { + setLoading(false); + } + } + + const { valid, verifiedAt } = isSessionPrimaryFactorAndLifetimeValid(session); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const [error, setError] = useState(null); + + const router = useRouter(); + + return ( + <> + + {samlData && } + + + + {valid && session.expirationDate && ( + + + Expires {moment(timestampDate(session.expirationDate)).fromNow()} + + + + )} + + {error && {error}} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/sessions-clear-list.tsx b/auth/ui/v2/apps/login/src/components/sessions-clear-list.tsx new file mode 100644 index 0000000..76e45de --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/sessions-clear-list.tsx @@ -0,0 +1,111 @@ +"use client"; + +import { clearSession } from "@/lib/actions/session"; +import { timestampDate } from "@zitadel/client"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { useTranslations } from "next-intl"; +import { redirect, useRouter } from "next/navigation"; +import { useCallback, useEffect, useState } from "react"; +import { Alert, AlertType } from "./alert"; +import { SessionClearItem } from "./session-clear-item"; +import { Translated } from "./translated"; + +type Props = { + sessions: Session[]; + postLogoutRedirectUri?: string; + logoutHint?: string; + organization?: string; +}; + +export function SessionsClearList({ sessions, logoutHint, postLogoutRedirectUri, organization }: Props) { + const [list, setList] = useState(sessions); + const [error, setError] = useState(null); + const router = useRouter(); + const t = useTranslations("error"); + + const clearHintedSession = useCallback(async () => { + console.log("Clearing session for login hint:", logoutHint); + // If a login hint is provided, we logout that specific session + const sessionIdToBeCleared = sessions.find((session) => { + return session.factors?.user?.loginName === logoutHint; + })?.id; + + if (sessionIdToBeCleared) { + let clearError: string | undefined; + try { + const clearSessionResponse = await clearSession({ sessionId: sessionIdToBeCleared }); + if (clearSessionResponse && "error" in clearSessionResponse) { + clearError = clearSessionResponse.error; + } + } catch (error) { + console.error("Error clearing session:", error); + clearError = t("couldNotClearSession"); + } + + // Do not tell the RP the logout completed when the session was kept: + // show the error and leave the card so the user can retry. + if (clearError) { + setError(clearError); + return; + } + + if (postLogoutRedirectUri) { + return redirect(postLogoutRedirectUri); + } + + const params = new URLSearchParams(); + + if (organization) { + params.set("organization", organization); + } + + return router.push("/logout/done?" + params); + } else { + console.warn(`No session found for login hint: ${logoutHint}`); + } + }, [logoutHint, sessions, postLogoutRedirectUri, organization, router, t]); + + useEffect(() => { + if (logoutHint) { + clearHintedSession(); + } + }, [logoutHint, clearHintedSession]); + + return sessions ? ( +
+ {list + .filter((session) => session?.factors?.user?.loginName) + // sort by change date descending + .sort((a, b) => { + const dateA = a.changeDate ? timestampDate(a.changeDate).getTime() : 0; + const dateB = b.changeDate ? timestampDate(b.changeDate).getTime() : 0; + return dateB - dateA; + }) + // TODO: add sorting to move invalid sessions to the bottom + .map((session, index) => { + return ( + { + setList(list.filter((s) => s.id !== session.id)); + if (postLogoutRedirectUri) { + router.push(postLogoutRedirectUri); + } + }} + key={"session-" + index} + /> + ); + })} + {error && {error}} + {list.length === 0 && ( + + + + )} +
+ ) : ( + + + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/sessions-list.tsx b/auth/ui/v2/apps/login/src/components/sessions-list.tsx new file mode 100644 index 0000000..b7fd0e4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/sessions-list.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { timestampDate } from "@zitadel/client"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { useState } from "react"; +import { Alert } from "./alert"; +import { SessionItem } from "./session-item"; +import { Translated } from "./translated"; + +type Props = { + sessions: Session[]; + requestId?: string; +}; + +export function SessionsList({ sessions, requestId }: Props) { + const [list, setList] = useState(sessions); + return sessions ? ( +
+ {list + .filter((session) => session?.factors?.user?.loginName) + // sort by change date descending + .sort((a, b) => { + const dateA = a.changeDate ? timestampDate(a.changeDate).getTime() : 0; + const dateB = b.changeDate ? timestampDate(b.changeDate).getTime() : 0; + return dateB - dateA; + }) + // TODO: add sorting to move invalid sessions to the bottom + .map((session, index) => { + return ( + { + setList(list.filter((s) => s.id !== session.id)); + }} + key={"session-" + index} + /> + ); + })} +
+ ) : ( + + + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/set-password-form.test.tsx b/auth/ui/v2/apps/login/src/components/set-password-form.test.tsx new file mode 100644 index 0000000..01d7dbb --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/set-password-form.test.tsx @@ -0,0 +1,72 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { create } from "@zitadel/client"; +import { PasswordComplexitySettingsSchema } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { SetPasswordForm } from "./set-password-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/password", () => ({ + changePassword: vi.fn(), + resetPassword: vi.fn(), + sendPassword: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), +})); + +const defaultComplexitySettings = create(PasswordComplexitySettingsSchema, { + minLength: 8n, + requiresUppercase: false, + requiresLowercase: false, + requiresNumber: false, + requiresSymbol: false, +}); + +describe("SetPasswordForm", () => { + afterEach(cleanup); + + test("should autofocus the code input when codeRequired is true", () => { + const { getByTestId } = render( + , + ); + expect(getByTestId("code-text-input")).toHaveFocus(); + }); + + test("should use translated resend accessible name when codeRequired is true", () => { + render( + , + ); + + expect(screen.getByRole("button", { name: "set.resend" })).toBeInTheDocument(); + }); + + test("should autofocus the password input when codeRequired is false", () => { + const { getByTestId } = render( + , + ); + expect(getByTestId("password-set-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/set-password-form.tsx b/auth/ui/v2/apps/login/src/components/set-password-form.tsx new file mode 100644 index 0000000..eceeaa6 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/set-password-form.tsx @@ -0,0 +1,277 @@ +"use client"; + +import { lowerCaseValidator, numberValidator, symbolValidator, upperCaseValidator } from "@/helpers/validators"; +import { changePassword, resetPassword, sendPassword } from "@/lib/actions/password"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { create } from "@zitadel/client"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { PasswordComplexitySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { FieldValues, useForm } from "react-hook-form"; +import { Alert, AlertType } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { PasswordComplexity } from "./password-complexity"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = + | { + code: string; + password: string; + confirmPassword: string; + } + | FieldValues; + +type Props = { + code?: string; + passwordComplexitySettings: PasswordComplexitySettings; + loginName: string; + userId: string; + organization?: string; + defaultOrganization?: string; + requestId?: string; + codeRequired: boolean; +}; + +export function SetPasswordForm({ + passwordComplexitySettings, + organization, + defaultOrganization, + requestId, + loginName, + userId, + code, + codeRequired, +}: Props) { + const { register, handleSubmit, watch, formState } = useForm({ + mode: "onChange", + defaultValues: { + code: code ?? "", + }, + }); + + const t = useTranslations("password"); + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const router = useRouter(); + + async function resendCode() { + setError(""); + setLoading(true); + + const response = await resetPassword({ + loginName, + organization, + defaultOrganization, + requestId, + }) + .catch(() => { + setError(t("set.errors.couldNotResetPassword")); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response && typeof response.error === "string") { + setError(response.error); + return; + } + } + + async function submitPassword(values: Inputs) { + setLoading(true); + + let payload: { userId: string; password: string; code?: string; organization?: string } = { + userId: userId, + password: values.password, + organization, + }; + + // this is not required for initial password setup + if (codeRequired) { + payload = { ...payload, code: values.code }; + } + + const changeResponse = await changePassword(payload).catch(() => { + setError(t("set.errors.couldNotSetPassword")); + setLoading(false); + return; + }); + + if (changeResponse && "error" in changeResponse) { + setLoading(false); + setError(changeResponse.error); + return; + } + + if (!changeResponse) { + setLoading(false); + setError(t("set.errors.couldNotSetPassword")); + return; + } + + const params = new URLSearchParams({}); + + if (loginName) { + params.append("loginName", loginName); + } + if (organization) { + params.append("organization", organization); + } + + await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait for a second to avoid eventual consistency issues with an initial password being set + + const passwordResponse = await sendPassword({ + loginName, + organization, + checks: create(ChecksSchema, { + password: { password: values.password }, + }), + requestId, + }).catch(() => { + setError(t("set.errors.couldNotVerifyPassword")); + setLoading(false); + return; + }); + + setLoading(false); + handleServerActionResponse(passwordResponse as any, router, setSamlData, setError); + + return; + } + + const { errors } = formState; + + const watchPassword = watch("password", ""); + const watchConfirmPassword = watch("confirmPassword", ""); + + const hasMinLength = passwordComplexitySettings && watchPassword?.length >= passwordComplexitySettings.minLength; + const hasSymbol = symbolValidator(watchPassword); + const hasNumber = numberValidator(watchPassword); + const hasUppercase = upperCaseValidator(watchPassword); + const hasLowercase = lowerCaseValidator(watchPassword); + + const policyIsValid = + passwordComplexitySettings && + (passwordComplexitySettings.requiresLowercase ? hasLowercase : true) && + (passwordComplexitySettings.requiresNumber ? hasNumber : true) && + (passwordComplexitySettings.requiresUppercase ? hasUppercase : true) && + (passwordComplexitySettings.requiresSymbol ? hasSymbol : true) && + hasMinLength; + + return ( + <> + {samlData && } +
+
+ + {codeRequired && ( + +
+ + + + +
+
+ )} + {codeRequired && ( +
+ +
+ )} +
+ +
+
+ +
+
+ + {passwordComplexitySettings && ( + + )} + + {error && {error}} + +
+ + +
+ + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/set-register-password-form.test.tsx b/auth/ui/v2/apps/login/src/components/set-register-password-form.test.tsx new file mode 100644 index 0000000..9f57937 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/set-register-password-form.test.tsx @@ -0,0 +1,46 @@ +import { cleanup, render } from "@testing-library/react"; +import { create } from "@zitadel/client"; +import { PasswordComplexitySettingsSchema } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { SetRegisterPasswordForm } from "./set-register-password-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/register", () => ({ + registerUser: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), +})); + +const defaultComplexitySettings = create(PasswordComplexitySettingsSchema, { + minLength: 8n, + requiresUppercase: false, + requiresLowercase: false, + requiresNumber: false, + requiresSymbol: false, +}); + +describe("SetRegisterPasswordForm", () => { + afterEach(cleanup); + + test("should autofocus the password input on mount", () => { + const { getByTestId } = render( + , + ); + expect(getByTestId("password-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/set-register-password-form.tsx b/auth/ui/v2/apps/login/src/components/set-register-password-form.tsx new file mode 100644 index 0000000..dec9e71 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/set-register-password-form.tsx @@ -0,0 +1,169 @@ +"use client"; + +import { lowerCaseValidator, numberValidator, symbolValidator, upperCaseValidator } from "@/helpers/validators"; +import { registerUser } from "@/lib/actions/register"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { PasswordComplexitySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { FieldValues, useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { PasswordComplexity } from "./password-complexity"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = + | { + password: string; + confirmPassword: string; + } + | FieldValues; + +type Props = { + passwordComplexitySettings: PasswordComplexitySettings; + email: string; + firstname: string; + lastname: string; + organization: string; + requestId?: string; +}; + +export function SetRegisterPasswordForm({ + passwordComplexitySettings, + email, + firstname, + lastname, + organization, + requestId, +}: Props) { + const { register, handleSubmit, watch, formState } = useForm({ + mode: "onChange", + defaultValues: { + email: email ?? "", + firstname: firstname ?? "", + lastname: lastname ?? "", + }, + }); + + const t = useTranslations("register"); + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const router = useRouter(); + + async function submitRegister(values: Inputs) { + setLoading(true); + try { + const response = await registerUser({ + email: email, + firstName: firstname, + lastName: lastname, + organization: organization, + requestId: requestId, + password: values.password, + }); + + handleServerActionResponse(response, router, setSamlData, setError); + } catch { + setError(t("errors.couldNotRegisterUser")); + } finally { + setLoading(false); + } + } + + const { errors } = formState; + + const watchPassword = watch("password", ""); + const watchConfirmPassword = watch("confirmPassword", ""); + + const hasMinLength = passwordComplexitySettings && watchPassword?.length >= passwordComplexitySettings.minLength; + const hasSymbol = symbolValidator(watchPassword); + const hasNumber = numberValidator(watchPassword); + const hasUppercase = upperCaseValidator(watchPassword); + const hasLowercase = lowerCaseValidator(watchPassword); + + const policyIsValid = + passwordComplexitySettings && + (passwordComplexitySettings.requiresLowercase ? hasLowercase : true) && + (passwordComplexitySettings.requiresNumber ? hasNumber : true) && + (passwordComplexitySettings.requiresUppercase ? hasUppercase : true) && + (passwordComplexitySettings.requiresSymbol ? hasSymbol : true) && + hasMinLength; + + return ( + <> + {samlData && } +
+
+ +
+ +
+
+ +
+
+ + {passwordComplexitySettings && ( + + )} + + {error && {error}} + +
+ + +
+ + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/sign-in-with-idp.tsx b/auth/ui/v2/apps/login/src/components/sign-in-with-idp.tsx new file mode 100644 index 0000000..20bede1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/sign-in-with-idp.tsx @@ -0,0 +1,94 @@ +"use client"; + +import { redirectToIdp } from "@/lib/actions/idp"; +import { idpTypeToSlug } from "@/lib/idp"; +import { IdentityProvider, IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { ReactNode, useActionState } from "react"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { SignInWithIdentityProviderProps } from "./idps/base-button"; +import { SignInWithApple } from "./idps/sign-in-with-apple"; +import { SignInWithAzureAd } from "./idps/sign-in-with-azure-ad"; +import { SignInWithGeneric } from "./idps/sign-in-with-generic"; +import { SignInWithGithub } from "./idps/sign-in-with-github"; +import { SignInWithGitlab } from "./idps/sign-in-with-gitlab"; +import { SignInWithGoogle } from "./idps/sign-in-with-google"; +import { SignInWithZitadel } from "./idps/sign-in-with-zitadel"; +import { Translated } from "./translated"; + +export interface SignInWithIDPProps { + children?: ReactNode; + identityProviders: IdentityProvider[]; + requestId?: string; + organization?: string; + sessionId?: string; + postErrorRedirectUrl?: string; + /** Forwarded to the IdP as login_hint so the user does not have to type the identifier again. */ + loginHint?: string; + showLabel?: boolean; +} + +export function SignInWithIdp({ + identityProviders, + requestId, + organization, + sessionId, + postErrorRedirectUrl, + loginHint, + showLabel = true, +}: Readonly) { + const [state, action, _isPending] = useActionState(redirectToIdp, {}); + + const renderIDPButton = (idp: IdentityProvider, index: number) => { + const { id, name, type } = idp; + + const components: Partial ReactNode>> = { + [IdentityProviderType.APPLE]: SignInWithApple, + [IdentityProviderType.OAUTH]: SignInWithGeneric, + [IdentityProviderType.OIDC]: SignInWithGeneric, + [IdentityProviderType.GITHUB]: SignInWithGithub, + [IdentityProviderType.GITHUB_ES]: SignInWithGithub, + [IdentityProviderType.AZURE_AD]: SignInWithAzureAd, + [IdentityProviderType.GOOGLE]: (props) => , + [IdentityProviderType.GITLAB]: SignInWithGitlab, + [IdentityProviderType.GITLAB_SELF_HOSTED]: SignInWithGitlab, + [IdentityProviderType.SAML]: SignInWithGeneric, + [IdentityProviderType.LDAP]: SignInWithGeneric, + [IdentityProviderType.JWT]: SignInWithGeneric, + [IdentityProviderType.ZITADEL]: SignInWithZitadel, + }; + + const Component = components[type]; + return Component ? ( +
+ + + + + {sessionId && } + {postErrorRedirectUrl && } + {loginHint && } + + + ) : null; + }; + + return ( +
+ {state?.samlData && } + {showLabel && ( +

+ +

+ )} + {!!identityProviders?.length && identityProviders?.map(renderIDPButton)} + {state?.error && ( +
+ {state?.error} +
+ )} +
+ ); +} + +SignInWithIdp.displayName = "SignInWithIDP"; diff --git a/auth/ui/v2/apps/login/src/components/skeleton-card.tsx b/auth/ui/v2/apps/login/src/components/skeleton-card.tsx new file mode 100644 index 0000000..ea8be3a --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/skeleton-card.tsx @@ -0,0 +1,55 @@ +import { getComponentRoundness, getThemeConfig, SPACING_STYLES } from "@/lib/theme"; +import { ThemeableProps } from "@/lib/themeUtils"; +import { clsx } from "clsx"; + +interface SkeletonCardProps extends ThemeableProps { + isLoading?: boolean; +} + +// Helper function to get default card roundness from theme +function getDefaultCardRoundness(): string { + return getComponentRoundness("card"); +} + +// Helper function to get default spacing from centralized theme system +function getDefaultSpacing(): string { + const themeConfig = getThemeConfig(); + return SPACING_STYLES[themeConfig.spacing].spacing; +} + +// Helper function to get default padding from centralized theme system +function getDefaultPadding(): string { + const themeConfig = getThemeConfig(); + return SPACING_STYLES[themeConfig.spacing].padding; +} +export const SkeletonCard = ({ + isLoading, + roundness, // Will use theme default if not provided + spacing, // Will use theme default if not provided + padding, // Will use theme default if not provided +}: SkeletonCardProps) => { + // Use theme-based values if not explicitly provided + const actualRoundness = roundness || getDefaultCardRoundness(); + const actualSpacing = spacing || getDefaultSpacing(); + const actualPadding = padding || getDefaultPadding(); + + return ( +
+
+
+
+
+
+
+ ); +}; diff --git a/auth/ui/v2/apps/login/src/components/skeleton.tsx b/auth/ui/v2/apps/login/src/components/skeleton.tsx new file mode 100644 index 0000000..0801239 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/skeleton.tsx @@ -0,0 +1,9 @@ +import { ReactNode } from "react"; + +export function Skeleton({ children }: { children?: ReactNode }) { + return ( +
+ {children} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/spinner.tsx b/auth/ui/v2/apps/login/src/components/spinner.tsx new file mode 100644 index 0000000..6e22bf2 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/spinner.tsx @@ -0,0 +1,22 @@ +import { FC } from "react"; + +export const Spinner: FC<{ className?: string }> = ({ className = "" }) => { + return ( + + + + + ); +}; diff --git a/auth/ui/v2/apps/login/src/components/state-badge.tsx b/auth/ui/v2/apps/login/src/components/state-badge.tsx new file mode 100644 index 0000000..b6ae682 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/state-badge.tsx @@ -0,0 +1,33 @@ +import { clsx } from "clsx"; +import { ReactNode } from "react"; + +export enum BadgeState { + Info = "info", + Error = "error", + Success = "success", + Alert = "alert", +} + +export type StateBadgeProps = { + state: BadgeState; + children: ReactNode; + evenPadding?: boolean; +}; + +const getBadgeClasses = (state: BadgeState, evenPadding: boolean) => + clsx({ + "w-fit border-box h-18.5px flex flex-row items-center whitespace-nowrap tracking-wider leading-4 items-center justify-center px-2 py-2px text-12px rounded-full shadow-sm": true, + "bg-state-success-light-background text-state-success-light-color dark:bg-state-success-dark-background dark:text-state-success-dark-color ": + state === BadgeState.Success, + "bg-state-neutral-light-background text-state-neutral-light-color dark:bg-state-neutral-dark-background dark:text-state-neutral-dark-color": + state === BadgeState.Info, + "bg-state-error-light-background text-state-error-light-color dark:bg-state-error-dark-background dark:text-state-error-dark-color": + state === BadgeState.Error, + "bg-state-alert-light-background text-state-alert-light-color dark:bg-state-alert-dark-background dark:text-state-alert-dark-color": + state === BadgeState.Alert, + "p-[2px]": evenPadding, + }); + +export function StateBadge({ state = BadgeState.Success, evenPadding = false, children }: StateBadgeProps) { + return {children}; +} diff --git a/auth/ui/v2/apps/login/src/components/tab-group.tsx b/auth/ui/v2/apps/login/src/components/tab-group.tsx new file mode 100644 index 0000000..afa625d --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/tab-group.tsx @@ -0,0 +1,16 @@ +import { Tab } from "@/components/tab"; + +export type Item = { + text: string; + slug?: string; +}; + +export const TabGroup = ({ path, items }: { path: string; items: Item[] }) => { + return ( +
+ {items.map((item) => ( + + ))} +
+ ); +}; diff --git a/auth/ui/v2/apps/login/src/components/tab.tsx b/auth/ui/v2/apps/login/src/components/tab.tsx new file mode 100644 index 0000000..974cc16 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/tab.tsx @@ -0,0 +1,28 @@ +"use client"; + +import type { Item } from "@/components/tab-group"; +import { clsx } from "clsx"; +import Link from "next/link"; +import { useSelectedLayoutSegment } from "next/navigation"; + +export const Tab = ({ path, item: { slug, text } }: { path: string; item: Item }) => { + const segment = useSelectedLayoutSegment(); + const href = slug ? path + "/" + slug : path; + const isActive = + // Example home pages e.g. `/layouts` + (!slug && segment === null) || + // Nested pages e.g. `/layouts/electronics` + segment === slug; + + return ( + + {text} + + ); +}; diff --git a/auth/ui/v2/apps/login/src/components/theme-provider.tsx b/auth/ui/v2/apps/login/src/components/theme-provider.tsx new file mode 100644 index 0000000..9ae817f --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/theme-provider.tsx @@ -0,0 +1,11 @@ +"use client"; +import { ThemeProvider as ThemeP } from "next-themes"; +import { ReactNode } from "react"; + +export function ThemeProvider({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/theme-switch.tsx b/auth/ui/v2/apps/login/src/components/theme-switch.tsx new file mode 100644 index 0000000..dd9e9e1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/theme-switch.tsx @@ -0,0 +1,84 @@ +"use client"; + +import { APPEARANCE_STYLES, getComponentRoundness, getThemeConfig } from "@/lib/theme"; +import { ComputerDesktopIcon, MoonIcon, SunIcon } from "@heroicons/react/24/outline"; +import { ThemeMode } from "@zitadel/proto/zitadel/settings/v2/branding_settings_pb"; +import { useTheme } from "next-themes"; +import { useEffect, useState } from "react"; +import { useThemeMode } from "./branding-context"; +function getThemeToggleRoundness() { + return getComponentRoundness("themeSwitch"); +} + +// Helper function to get card appearance styles for the theme switch wrapper +function getThemeSwitchCardAppearance(): string { + const themeConfig = getThemeConfig(); + const appearance = APPEARANCE_STYLES[themeConfig.appearance]; + return appearance?.card || "bg-black/5 dark:bg-white/5"; // Fallback to current styling +} + +// Helper function to get selected button styling for clear visibility +function getSelectedButtonStyle(isSelected: boolean): string { + const themeConfig = getThemeConfig(); + + if (!isSelected) { + return "text-gray-400 hover:text-gray-300 dark:text-gray-500 dark:hover:text-gray-400"; + } + + // Selected state styling based on appearance theme + switch (themeConfig.appearance) { + case "glass": + return "bg-white/30 dark:bg-black/30 text-gray-900 dark:text-white shadow-lg backdrop-blur-sm border border-white/40 dark:border-white/20"; + case "material": + return "bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-md"; + case "flat": + default: + return "bg-white dark:bg-gray-800 text-gray-900 dark:text-white border border-gray-200 dark:border-gray-700"; + } +} + +export default function ThemeSwitch() { + const [mounted, setMounted] = useState(false); + const { theme, setTheme } = useTheme(); + const themeMode = useThemeMode(); + const toggleRoundness = getThemeToggleRoundness(); + const cardAppearance = getThemeSwitchCardAppearance(); + + useEffect(() => { + setMounted(true); + }, []); + + if (!mounted) return null; + + // Hide toggle when theme is forced to light or dark only + if (themeMode === ThemeMode.LIGHT || themeMode === ThemeMode.DARK) { + return null; + } + + // themeMode is AUTO (1) or UNSPECIFIED (0): show light, system, dark options + return ( +
+ + + +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/theme-wrapper.tsx b/auth/ui/v2/apps/login/src/components/theme-wrapper.tsx new file mode 100644 index 0000000..e601cae --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/theme-wrapper.tsx @@ -0,0 +1,121 @@ +"use client"; + +import { setTheme } from "@/helpers/colors"; +import { BrandingSettings, ThemeMode } from "@zitadel/proto/zitadel/settings/v2/branding_settings_pb"; +import { useTheme } from "next-themes"; +import { ReactNode, useEffect, useLayoutEffect } from "react"; +import { setThemeMode } from "./branding-context"; + +type Props = { + branding: BrandingSettings | undefined; + children: ReactNode; +}; + +export const ThemeWrapper = ({ children, branding }: Props) => { + const { setTheme: setNextTheme } = useTheme(); + + useEffect(() => { + setTheme(document, branding); + }, [branding]); + + // Apply custom font from branding settings before paint to avoid FOUC. + // When a custom font is uploaded via the label/branding policy, fontUrl + // contains a fully-resolved URL to the font file served by the assets API. + // We inject a @font-face rule and set a CSS custom property so the entire + // login UI picks up the custom font with the existing font as fallback. + useLayoutEffect(() => { + const STYLE_ID = "zitadel-custom-font"; + + if (branding?.fontUrl) { + let fontSrc: string; + try { + fontSrc = new URL(branding.fontUrl).href; + } catch { + // Malformed URL — skip custom font + return; + } + + let styleEl = document.getElementById(STYLE_ID) as HTMLStyleElement | null; + if (!styleEl) { + styleEl = document.createElement("style"); + styleEl.id = STYLE_ID; + document.head.appendChild(styleEl); + } + // Capture the current font-family (Lato from next/font) before overriding, + // so it serves as fallback if the custom font fails to load. + const existingFont = getComputedStyle(document.documentElement).fontFamily || "sans-serif"; + const fontStack = `'ZitadelCustomFont', ${existingFont}`; + + styleEl.textContent = ` + @font-face { + font-family: 'ZitadelCustomFont'; + font-style: normal; + font-display: swap; + src: url('${fontSrc}'); + } + `; + + document.documentElement.style.setProperty("--zitadel-font-family", fontStack); + // Inline style overrides the class-based Lato from next/font + document.documentElement.style.setProperty("font-family", fontStack); + } else { + // No custom font — remove injected style and let Lato class take over + const existing = document.getElementById(STYLE_ID); + if (existing) { + existing.remove(); + } + document.documentElement.style.removeProperty("--zitadel-font-family"); + document.documentElement.style.removeProperty("font-family"); + } + + return () => { + const existing = document.getElementById(STYLE_ID); + if (existing) { + existing.remove(); + } + document.documentElement.style.removeProperty("--zitadel-font-family"); + document.documentElement.style.removeProperty("font-family"); + }; + }, [branding?.fontUrl]); + + // Publish themeMode to the module-level store so ThemeSwitch can read it + useEffect(() => { + setThemeMode(branding?.themeMode ?? ThemeMode.UNSPECIFIED); + }, [branding?.themeMode]); + + // Handle branding themeMode to force specific theme. + // Uses useLayoutEffect to apply before paint and writes the forced value + // to localStorage so next-themes doesn't fall back to system default. + useLayoutEffect(() => { + if (branding?.themeMode !== undefined) { + switch (branding.themeMode) { + case ThemeMode.LIGHT: + document.documentElement.classList.remove("dark"); + try { + localStorage.setItem("cp-theme", "light"); + } catch { + /* localStorage unavailable (e.g. private mode) */ + } + setNextTheme("light"); + break; + case ThemeMode.DARK: + document.documentElement.classList.add("dark"); + try { + localStorage.setItem("cp-theme", "dark"); + } catch { + /* localStorage unavailable (e.g. private mode) */ + } + setNextTheme("dark"); + break; + case ThemeMode.AUTO: + case ThemeMode.UNSPECIFIED: + default: + setNextTheme("system"); + break; + } + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [branding?.themeMode]); + + return
{children}
; +}; diff --git a/auth/ui/v2/apps/login/src/components/totp-register.test.tsx b/auth/ui/v2/apps/login/src/components/totp-register.test.tsx new file mode 100644 index 0000000..3acced1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/totp-register.test.tsx @@ -0,0 +1,33 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { TotpRegister } from "./totp-register"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/verify", () => ({ + verifyTOTP: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + handleServerActionResponse: vi.fn(), + completeFlowOrGetUrl: vi.fn(), +})); + +vi.mock("qrcode.react", () => ({ + QRCodeSVG: ({ value }: { value: string }) => , +})); + +describe("TotpRegister", () => { + afterEach(cleanup); + + test("should autofocus the code input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("code-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/totp-register.tsx b/auth/ui/v2/apps/login/src/components/totp-register.tsx new file mode 100644 index 0000000..6dc8bc5 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/totp-register.tsx @@ -0,0 +1,152 @@ +"use client"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { verifyTOTP } from "@/lib/actions/verify"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { useTranslations } from "next-intl"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { QRCodeSVG } from "qrcode.react"; +import { useState } from "react"; +import { useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { Button, ButtonVariants } from "./button"; +import { CopyToClipboard } from "./copy-to-clipboard"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = { + code: string; +}; + +type Props = { + uri: string; + secret: string; + loginName?: string; + sessionId?: string; + requestId?: string; + organization?: string; + checkAfter?: boolean; + loginSettings?: LoginSettings; +}; +export function TotpRegister({ uri, loginName, sessionId, requestId, organization, checkAfter, loginSettings }: Props) { + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + const router = useRouter(); + + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + code: "", + }, + }); + + const t = useTranslations("otp"); + + async function continueWithCode(values: Inputs) { + setLoading(true); + return verifyTOTP(values.code, loginName, organization) + .then(async () => { + // if attribute is set, validate MFA after it is setup, otherwise proceed as usual (when mfa is enforced to login) + if (checkAfter) { + const params = new URLSearchParams({}); + + if (loginName) { + params.append("loginName", loginName); + } + if (requestId) { + params.append("requestId", requestId); + } + if (organization) { + params.append("organization", organization); + } + + return router.push(`/otp/time-based?` + params); + } else { + if (requestId && sessionId) { + const callbackResponse = await completeFlowOrGetUrl( + { + sessionId: sessionId, + requestId: requestId, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + + handleServerActionResponse(callbackResponse, router, setSamlData, setError); + } else if (loginName) { + const callbackResponse = await completeFlowOrGetUrl( + { + loginName: loginName, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + + handleServerActionResponse(callbackResponse, router, setSamlData, setError); + } + } + }) + .catch((e) => { + setError(e.message); + return; + }) + .finally(() => { + setLoading(false); + }); + } + + return ( +
+ {samlData && } + {uri && ( + <> + +
+ + {uri} + + + +
+
+
+ +
+ + {error && ( +
+ {error} +
+ )} + +
+ + +
+
+ + )} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/translated.tsx b/auth/ui/v2/apps/login/src/components/translated.tsx new file mode 100644 index 0000000..2a9f5c1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/translated.tsx @@ -0,0 +1,22 @@ +import { useTranslations } from "next-intl"; + +export function Translated({ + i18nKey, + namespace, + data, + ...props +}: { + i18nKey: string; + children?: React.ReactNode; + namespace?: string; + data?: any; +} & React.HTMLAttributes) { + const t = useTranslations(namespace); + const helperKey = `${namespace ? `${namespace}.` : ""}${i18nKey}`; + + return ( + + {t(i18nKey, data)} + + ); +} diff --git a/auth/ui/v2/apps/login/src/components/user-avatar.tsx b/auth/ui/v2/apps/login/src/components/user-avatar.tsx new file mode 100644 index 0000000..4782e74 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/user-avatar.tsx @@ -0,0 +1,55 @@ +import { Avatar } from "@/components/avatar"; +import { getComponentRoundness } from "@/lib/theme"; +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import Link from "next/link"; + +// Helper function to get user avatar container roundness from theme +function getUserAvatarRoundness(): string { + return getComponentRoundness("avatarContainer"); +} + +type Props = { + loginName?: string; + displayName?: string; + showDropdown: boolean; + searchParams?: Record; +}; + +export function UserAvatar({ loginName, displayName, showDropdown, searchParams }: Props) { + const params = new URLSearchParams({}); + const userAvatarRoundness = getUserAvatarRoundness(); + + if (searchParams?.sessionId) { + params.set("sessionId", searchParams.sessionId); + } + + if (searchParams?.organization) { + params.set("organization", searchParams.organization); + } + + if (searchParams?.requestId) { + params.set("requestId", searchParams.requestId); + } + + if (searchParams?.loginName) { + params.set("loginName", searchParams.loginName); + } + + return ( +
+
+ +
+ {loginName} + + {showDropdown && ( + + + + )} +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/username-form.test.tsx b/auth/ui/v2/apps/login/src/components/username-form.test.tsx new file mode 100644 index 0000000..3385fda --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/username-form.test.tsx @@ -0,0 +1,26 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { UsernameForm } from "./username-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn() }), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/loginname", () => ({ + sendLoginname: vi.fn(), +})); + +describe("UsernameForm", () => { + afterEach(cleanup); + + test("should autofocus the loginName input on mount", () => { + const { getByTestId } = render( + , + ); + expect(getByTestId("username-text-input")).toHaveFocus(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/username-form.tsx b/auth/ui/v2/apps/login/src/components/username-form.tsx new file mode 100644 index 0000000..7a5f37a --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/username-form.tsx @@ -0,0 +1,163 @@ +"use client"; + +import { sendLoginname } from "@/lib/actions/loginname"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import { Alert } from "./alert"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = { + loginName: string; +}; + +type Props = { + loginName: string | undefined; + requestId: string | undefined; + loginSettings: LoginSettings | undefined; + organization?: string; + defaultOrganization?: string; + suffix?: string; + hideSuffix?: boolean; + submit: boolean; + allowRegister: boolean; +}; + +export function UsernameForm({ + loginName, + requestId, + organization, + defaultOrganization, + suffix, + hideSuffix, + loginSettings, + submit, + allowRegister, +}: Props) { + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + loginName: loginName ? loginName : "", + }, + }); + + const t = useTranslations("loginname"); + + const router = useRouter(); + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const submitLoginName = useCallback( + async (values: Inputs, organization?: string) => { + setLoading(true); + + try { + const res = await sendLoginname({ + loginName: values.loginName, + organization, + defaultOrganization, + requestId, + suffix, + }); + + handleServerActionResponse(res, router, setSamlData, setError); + return res; + } catch { + setError(t("errors.internalError")); + } finally { + setLoading(false); + } + }, + [defaultOrganization, requestId, suffix, router, t], + ); + + useEffect(() => { + if (submit && loginName) { + // When we navigate to this page, we always want to be redirected if submit is true and the parameters are valid. + submitLoginName({ loginName }, organization); + } + }, [submit, loginName, organization, submitLoginName]); + + let inputLabel = t("labels.loginname"); + if (loginSettings?.disableLoginWithEmail && loginSettings?.disableLoginWithPhone) { + inputLabel = t("labels.username"); + } else if (loginSettings?.disableLoginWithEmail) { + inputLabel = t("labels.usernameOrPhoneNumber"); + } else if (loginSettings?.disableLoginWithPhone) { + inputLabel = t("labels.usernameOrEmail"); + } + + return ( + <> + {samlData && } +
+
+ + {allowRegister && ( + + )} +
+ + {error && ( +
+ {error} +
+ )} +
+ + + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/verify-form.test.tsx b/auth/ui/v2/apps/login/src/components/verify-form.test.tsx new file mode 100644 index 0000000..63cc3f8 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/verify-form.test.tsx @@ -0,0 +1,66 @@ +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { VerifyForm } from "./verify-form"; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), + usePathname: () => "/verify", + useSearchParams: () => new URLSearchParams(), +})); + +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +vi.mock("@/lib/actions/verify", () => ({ + sendVerification: vi.fn(), + resendVerification: vi.fn(), +})); + +describe("VerifyForm", () => { + let mockSendVerification: ReturnType; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { sendVerification } = await import("@/lib/actions/verify"); + mockSendVerification = vi.mocked(sendVerification); + mockSendVerification.mockResolvedValue({ redirect: "/success" }); + }); + + afterEach(cleanup); + + describe("Input Focus", () => { + test("should autofocus the code input on mount", () => { + const { getByTestId } = render(); + expect(getByTestId("code-text-input")).toHaveFocus(); + }); + }); + + describe("Auto-submit Behavior", () => { + test("should call sendVerification automatically when submit=true", async () => { + render(); + + await waitFor(() => { + expect(mockSendVerification).toHaveBeenCalledWith( + expect.objectContaining({ + code: "123456", + userId: "user-1", + }), + ); + }); + }); + + test("should prefill code but not auto-submit when submit=false", () => { + render(); + + const input = screen.getByTestId("code-text-input"); + expect(input).toHaveValue("123456"); + + const submitButton = screen.getByTestId("submit-button"); + expect(submitButton).toBeInTheDocument(); + + expect(mockSendVerification).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/components/verify-form.tsx b/auth/ui/v2/apps/login/src/components/verify-form.tsx new file mode 100644 index 0000000..28c193f --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/verify-form.tsx @@ -0,0 +1,188 @@ +"use client"; + +import { Alert, AlertType } from "@/components/alert"; +import { resendVerification, sendVerification } from "@/lib/actions/verify"; +import { handleServerActionResponse } from "@/lib/client-utils"; +import { UNKNOWN_USER_ID } from "@/lib/constants"; +import { useTranslations } from "next-intl"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { useForm } from "react-hook-form"; +import { AutoSubmitForm } from "./auto-submit-form"; +import { BackButton } from "./back-button"; +import { Button, ButtonVariants } from "./button"; +import { TextInput } from "./input"; +import { Spinner } from "./spinner"; +import { Translated } from "./translated"; + +type Inputs = { + code: string; +}; + +type Props = { + userId: string; + loginName?: string; + organization?: string; + code?: string; + isInvite: boolean; + requestId?: string; + submit: boolean; +}; + +export function VerifyForm({ userId, loginName, organization, requestId, code, isInvite, submit }: Props) { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const codeSent = searchParams.get("codeSent") === "true"; + + const { register, handleSubmit, formState } = useForm({ + mode: "onChange", + defaultValues: { + code: code ?? "", + }, + }); + + const t = useTranslations("verify"); + + const [error, setError] = useState(""); + const [samlData, setSamlData] = useState<{ url: string; fields: Record } | null>(null); + + const [loading, setLoading] = useState(false); + + async function resendCode() { + setError(""); + setLoading(true); + + // do not send code for dummy userid that is set to prevent user enumeration + if (userId === UNKNOWN_USER_ID) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + setLoading(false); + return; + } + + const response = await resendVerification({ + userId, + isInvite: isInvite, + requestId: requestId, + }) + .catch(() => { + setError(t("errors.couldNotResendEmail")); + return; + }) + .finally(() => { + setLoading(false); + }); + + if (response && "error" in response && response?.error) { + setError(response.error); + return; + } + + // Signal success via URL search param so the "code sent" alert is shown + const params = new URLSearchParams(searchParams.toString()); + params.set("codeSent", "true"); + router.replace(`${pathname}?${params.toString()}`); + + return response; + } + + const processedCode = useRef(undefined); + + const fcn = useCallback( + async function submitCodeAndContinue(value: Inputs): Promise { + setError(""); + setLoading(true); + + try { + const response = await sendVerification({ + code: value.code, + userId, + isInvite: isInvite, + loginName: loginName, + organization: organization, + requestId: requestId, + }); + + handleServerActionResponse(response, router, setSamlData, setError); + } catch { + setError(t("errors.couldNotVerifyUser")); + } finally { + setLoading(false); + } + }, + [isInvite, userId, loginName, organization, requestId, router, t], + ); + + useEffect(() => { + if (submit && code && code !== processedCode.current) { + processedCode.current = code; + fcn({ code }); + } + }, [submit, code, fcn]); + + return ( + <> + {samlData && } + {codeSent && ( +
+ + + +
+ )} +
+ +
+ + + + +
+
+
+ +
+ + {error && ( +
+ {error} +
+ )} + +
+ + + +
+
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/components/verify-success-continue.tsx b/auth/ui/v2/apps/login/src/components/verify-success-continue.tsx new file mode 100644 index 0000000..2fe4c75 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/verify-success-continue.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { Button, ButtonVariants } from "./button"; + +type Props = { + continueUrl: string; +}; + +export function VerifySuccessContinue({ continueUrl }: Props) { + const router = useRouter(); + const t = useTranslations("verify"); + + return ( +
+ +
+ ); +} diff --git a/auth/ui/v2/apps/login/src/components/zitadel-logo-dark.tsx b/auth/ui/v2/apps/login/src/components/zitadel-logo-dark.tsx new file mode 100644 index 0000000..2164fe4 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/zitadel-logo-dark.tsx @@ -0,0 +1,203 @@ +import { FC } from "react"; + +export const ZitadelLogoDark: FC = () => ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +); diff --git a/auth/ui/v2/apps/login/src/components/zitadel-logo-light.tsx b/auth/ui/v2/apps/login/src/components/zitadel-logo-light.tsx new file mode 100644 index 0000000..6655a8a --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/zitadel-logo-light.tsx @@ -0,0 +1,203 @@ +import { FC } from "react"; + +export const ZitadelLogoLight: FC = () => ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +); diff --git a/auth/ui/v2/apps/login/src/components/zitadel-logo.tsx b/auth/ui/v2/apps/login/src/components/zitadel-logo.tsx new file mode 100644 index 0000000..472e879 --- /dev/null +++ b/auth/ui/v2/apps/login/src/components/zitadel-logo.tsx @@ -0,0 +1,19 @@ +type Props = { + height?: number; + width?: number; +}; + +export function ZitadelLogo({ height = 40, width = 147.5 }: Props) { + return ( + <> +
+ {/* */} + + zitadel logo +
+
+ zitadel logo +
+ + ); +} diff --git a/auth/ui/v2/apps/login/src/helpers/base64.test.ts b/auth/ui/v2/apps/login/src/helpers/base64.test.ts new file mode 100644 index 0000000..faebedf --- /dev/null +++ b/auth/ui/v2/apps/login/src/helpers/base64.test.ts @@ -0,0 +1,315 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { coerceToArrayBuffer, coerceToBase64Url } from "./base64"; + +const originalBtoa = global.btoa; +const originalAtob = global.atob; + +beforeEach(() => { + global.btoa = (str: string) => Buffer.from(str, "binary").toString("base64"); + global.atob = (b64: string) => Buffer.from(b64, "base64").toString("binary"); + global.window = global.window || ({} as any); + (global.window as any).btoa = global.btoa; + (global.window as any).atob = global.atob; +}); + +afterEach(() => { + global.btoa = originalBtoa; + global.atob = originalAtob; +}); + +describe("base64 utilities", () => { + describe("coerceToBase64Url", () => { + it("should convert Uint8Array to base64url", () => { + const uint8Array = new Uint8Array([72, 101, 108, 108, 111]); + const result = coerceToBase64Url(uint8Array, "test"); + + expect(result).not.toContain("+"); + expect(result).not.toContain("/"); + expect(result).not.toContain("="); + expect(typeof result).toBe("string"); + }); + + it("should convert Array to base64url", () => { + const array = [72, 101, 108, 108, 111]; + const result = coerceToBase64Url(array, "test"); + + expect(result).not.toContain("+"); + expect(result).not.toContain("/"); + expect(result).not.toContain("="); + expect(typeof result).toBe("string"); + }); + + it("should convert ArrayBuffer to base64url", () => { + const buffer = new Uint8Array([72, 101, 108, 108, 111]).buffer; + const result = coerceToBase64Url(buffer, "test"); + + expect(result).not.toContain("+"); + expect(result).not.toContain("/"); + expect(result).not.toContain("="); + expect(typeof result).toBe("string"); + }); + + it("should convert standard base64 string to base64url", () => { + const base64 = "Hello+World/Test="; + const result = coerceToBase64Url(base64, "test"); + + expect(result).toBe("Hello-World_Test"); + expect(result).not.toContain("+"); + expect(result).not.toContain("/"); + expect(result).not.toContain("="); + }); + + it("should handle already URL-safe base64 strings", () => { + const base64url = "Hello-World_Test"; + const result = coerceToBase64Url(base64url, "test"); + + expect(result).toBe("Hello-World_Test"); + }); + + it("should remove padding from base64 strings", () => { + const base64WithPadding = "Test=="; + const result = coerceToBase64Url(base64WithPadding, "test"); + + expect(result).toBe("Test"); + expect(result).not.toContain("="); + }); + + it("should handle empty Uint8Array", () => { + const uint8Array = new Uint8Array([]); + const result = coerceToBase64Url(uint8Array, "test"); + + expect(typeof result).toBe("string"); + expect(result).toBe(""); + }); + + it("should handle empty string", () => { + const result = coerceToBase64Url("", "test"); + + expect(result).toBe(""); + }); + + it("should throw error for non-coercible types", () => { + expect(() => coerceToBase64Url(123, "number")).toThrow("could not coerce 'number' to string"); + + expect(() => coerceToBase64Url(null, "null")).toThrow("could not coerce 'null' to string"); + + expect(() => coerceToBase64Url(undefined, "undefined")).toThrow("could not coerce 'undefined' to string"); + + expect(() => coerceToBase64Url({}, "object")).toThrow("could not coerce 'object' to string"); + }); + + it("should handle binary data correctly", () => { + const binaryData = new Uint8Array([0, 1, 2, 255, 254, 253]); + const result = coerceToBase64Url(binaryData, "binary"); + + expect(typeof result).toBe("string"); + expect(result.length).toBeGreaterThan(0); + }); + + it("should handle large Uint8Arrays", () => { + const largeArray = new Uint8Array(1000); + for (let i = 0; i < 1000; i++) { + largeArray[i] = i % 256; + } + + const result = coerceToBase64Url(largeArray, "large"); + + expect(typeof result).toBe("string"); + expect(result.length).toBeGreaterThan(0); + }); + + it("should produce consistent results for same input", () => { + const input = new Uint8Array([1, 2, 3, 4, 5]); + const result1 = coerceToBase64Url(input, "test"); + const result2 = coerceToBase64Url(input, "test"); + + expect(result1).toBe(result2); + }); + }); + + describe("coerceToArrayBuffer", () => { + it("should convert base64url string to ArrayBuffer", () => { + const base64url = "SGVsbG8"; + const result = coerceToArrayBuffer(base64url, "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + expect(result.byteLength).toBeGreaterThan(0); + }); + + it("should convert base64 string with URL-safe characters to ArrayBuffer", () => { + const base64url = "Hello-World_Test"; + const result = coerceToArrayBuffer(base64url, "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + }); + + it("should convert Array to ArrayBuffer", () => { + const array = [72, 101, 108, 108, 111]; + const result = coerceToArrayBuffer(array, "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + + const view = new Uint8Array(result); + expect(Array.from(view)).toEqual(array); + }); + + it("should convert Uint8Array to ArrayBuffer", () => { + const uint8Array = new Uint8Array([72, 101, 108, 108, 111]); + const result = coerceToArrayBuffer(uint8Array, "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + expect(result).toBe(uint8Array.buffer); + }); + + it("should handle ArrayBuffer input (passthrough)", () => { + const buffer = new Uint8Array([1, 2, 3]).buffer; + const result = coerceToArrayBuffer(buffer, "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + expect(result).toBe(buffer); + }); + + it("should handle empty string", () => { + const result = coerceToArrayBuffer("", "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + expect(result.byteLength).toBe(0); + }); + + it("should handle empty array", () => { + const result = coerceToArrayBuffer([], "test"); + + expect(result).toBeInstanceOf(ArrayBuffer); + expect(result.byteLength).toBe(0); + }); + + it("should throw TypeError for non-coercible types", () => { + expect(() => coerceToArrayBuffer(123, "number")).toThrow(TypeError); + expect(() => coerceToArrayBuffer(123, "number")).toThrow("could not coerce 'number' to ArrayBuffer"); + + expect(() => coerceToArrayBuffer(null, "null")).toThrow(TypeError); + expect(() => coerceToArrayBuffer(undefined, "undefined")).toThrow(TypeError); + expect(() => coerceToArrayBuffer({}, "object")).toThrow(TypeError); + }); + + it("should handle binary data correctly", () => { + const binaryArray = [0, 1, 2, 255, 254, 253]; + const result = coerceToArrayBuffer(binaryArray, "binary"); + + expect(result).toBeInstanceOf(ArrayBuffer); + + const view = new Uint8Array(result); + expect(Array.from(view)).toEqual(binaryArray); + }); + + it("should handle large arrays", () => { + const largeArray = new Array(1000).fill(0).map((_, i) => i % 256); + const result = coerceToArrayBuffer(largeArray, "large"); + + expect(result).toBeInstanceOf(ArrayBuffer); + expect(result.byteLength).toBe(1000); + }); + + it("should produce consistent results for same input", () => { + const input = [1, 2, 3, 4, 5]; + const result1 = coerceToArrayBuffer(input, "test"); + const result2 = coerceToArrayBuffer(input, "test"); + + const view1 = new Uint8Array(result1); + const view2 = new Uint8Array(result2); + + expect(Array.from(view1)).toEqual(Array.from(view2)); + }); + }); + + describe("round-trip conversions", () => { + it("should successfully round-trip Uint8Array -> base64url -> ArrayBuffer", () => { + const original = new Uint8Array([1, 2, 3, 4, 5, 255, 254, 253]); + + const base64url = coerceToBase64Url(original, "test"); + const recovered = coerceToArrayBuffer(base64url, "test"); + + const recoveredArray = new Uint8Array(recovered); + expect(Array.from(recoveredArray)).toEqual(Array.from(original)); + }); + + it("should successfully round-trip Array -> base64url -> ArrayBuffer -> Array", () => { + const original = [10, 20, 30, 40, 50]; + + const base64url = coerceToBase64Url(original, "test"); + const buffer = coerceToArrayBuffer(base64url, "test"); + const recovered = Array.from(new Uint8Array(buffer)); + + expect(recovered).toEqual(original); + }); + + it("should handle empty data in round-trip", () => { + const original = new Uint8Array([]); + + const base64url = coerceToBase64Url(original, "test"); + const recovered = coerceToArrayBuffer(base64url, "test"); + + expect(recovered.byteLength).toBe(0); + }); + + it("should handle special characters in round-trip", () => { + const original = new Uint8Array([0xff, 0xff, 0xff, 0xfe, 0x00, 0x01]); + + const base64url = coerceToBase64Url(original, "test"); + + expect(base64url).not.toContain("+"); + expect(base64url).not.toContain("/"); + expect(base64url).not.toContain("="); + + const recovered = coerceToArrayBuffer(base64url, "test"); + const recoveredArray = new Uint8Array(recovered); + + expect(Array.from(recoveredArray)).toEqual(Array.from(original)); + }); + + it("should handle large data in round-trip", () => { + const original = new Uint8Array(1024); + for (let i = 0; i < 1024; i++) { + original[i] = Math.floor(Math.random() * 256); + } + + const base64url = coerceToBase64Url(original, "test"); + const recovered = coerceToArrayBuffer(base64url, "test"); + const recoveredArray = new Uint8Array(recovered); + + expect(Array.from(recoveredArray)).toEqual(Array.from(original)); + }); + }); + + describe("edge cases", () => { + it("should handle all zero bytes", () => { + const zeros = new Uint8Array([0, 0, 0, 0]); + const base64url = coerceToBase64Url(zeros, "test"); + const recovered = coerceToArrayBuffer(base64url, "test"); + + expect(Array.from(new Uint8Array(recovered))).toEqual([0, 0, 0, 0]); + }); + + it("should handle all max bytes", () => { + const maxBytes = new Uint8Array([255, 255, 255, 255]); + const base64url = coerceToBase64Url(maxBytes, "test"); + const recovered = coerceToArrayBuffer(base64url, "test"); + + expect(Array.from(new Uint8Array(recovered))).toEqual([255, 255, 255, 255]); + }); + + it("should handle single byte", () => { + const singleByte = new Uint8Array([42]); + const base64url = coerceToBase64Url(singleByte, "test"); + const recovered = coerceToArrayBuffer(base64url, "test"); + + expect(Array.from(new Uint8Array(recovered))).toEqual([42]); + }); + + it("should provide meaningful error messages with parameter names", () => { + expect(() => coerceToBase64Url(123, "myParameter")).toThrow("could not coerce 'myParameter' to string"); + + expect(() => coerceToArrayBuffer(123, "anotherParam")).toThrow("could not coerce 'anotherParam' to ArrayBuffer"); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/helpers/base64.ts b/auth/ui/v2/apps/login/src/helpers/base64.ts new file mode 100644 index 0000000..967cdc8 --- /dev/null +++ b/auth/ui/v2/apps/login/src/helpers/base64.ts @@ -0,0 +1,63 @@ +export function coerceToBase64Url(thing: any, name: string) { + // Array or ArrayBuffer to Uint8Array + if (Array.isArray(thing)) { + thing = Uint8Array.from(thing); + } + + if (thing instanceof ArrayBuffer) { + thing = new Uint8Array(thing); + } + + // Uint8Array to base64 + if (thing instanceof Uint8Array) { + var str = ""; + var len = thing.byteLength; + + for (var i = 0; i < len; i++) { + str += String.fromCharCode(thing[i]); + } + thing = window.btoa(str); + } + + if (typeof thing !== "string") { + throw new Error("could not coerce '" + name + "' to string"); + } + + // base64 to base64url + // NOTE: "=" at the end of challenge is optional, strip it off here + thing = thing.replace(/\+/g, "-").replace(/\//g, "_").replace(/=*$/g, ""); + + return thing; +} + +export function coerceToArrayBuffer(thing: any, name: string) { + if (typeof thing === "string") { + // base64url to base64 + thing = thing.replace(/-/g, "+").replace(/_/g, "/"); + + // base64 to Uint8Array + var str = window.atob(thing); + var bytes = new Uint8Array(str.length); + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + thing = bytes; + } + + // Array to Uint8Array + if (Array.isArray(thing)) { + thing = new Uint8Array(thing); + } + + // Uint8Array to ArrayBuffer + if (thing instanceof Uint8Array) { + thing = thing.buffer; + } + + // error if none of the above worked + if (!(thing instanceof ArrayBuffer)) { + throw new TypeError("could not coerce '" + name + "' to ArrayBuffer"); + } + + return thing; +} diff --git a/auth/ui/v2/apps/login/src/helpers/colors.test.ts b/auth/ui/v2/apps/login/src/helpers/colors.test.ts new file mode 100644 index 0000000..24d7dcb --- /dev/null +++ b/auth/ui/v2/apps/login/src/helpers/colors.test.ts @@ -0,0 +1,622 @@ +import { BrandingSettings } from "@zitadel/proto/zitadel/settings/v2/branding_settings_pb"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + BACKGROUND, + computeMap, + DARK_BACKGROUND, + DARK_PRIMARY, + DARK_TEXT, + DARK_WARN, + PRIMARY, + setTheme, + TEXT, + WARN, +} from "./colors"; + +describe("color utilities", () => { + describe("computeMap", () => { + it("should compute light theme color maps with default colors", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: PRIMARY, + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + expect(result).toHaveProperty("background"); + expect(result).toHaveProperty("primary"); + expect(result).toHaveProperty("warn"); + expect(result).toHaveProperty("text"); + expect(result).toHaveProperty("link"); + + expect(result.background).toHaveLength(14); + expect(result.primary).toHaveLength(14); + expect(result.warn).toHaveLength(14); + expect(result.text).toHaveLength(14); + expect(result.link).toHaveLength(14); + }); + + it("should compute dark theme color maps", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: PRIMARY, + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, true); + + expect(result.background).toHaveLength(14); + expect(result.primary).toHaveLength(14); + expect(result.warn).toHaveLength(14); + expect(result.text).toHaveLength(14); + expect(result.link).toHaveLength(14); + }); + + it("should generate color objects with correct properties", () => { + const branding = { + lightTheme: { + backgroundColor: "#ffffff", + fontColor: "#000000", + primaryColor: "#5469d4", + warnColor: "#cd3d56", + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + result.primary.forEach((color) => { + expect(color).toHaveProperty("name"); + expect(color).toHaveProperty("hex"); + expect(color).toHaveProperty("rgb"); + expect(color).toHaveProperty("contrastColor"); + + expect(color.hex).toMatch(/^#[0-9a-f]{6}$/i); + expect(color.rgb).toMatch(/^rgb\(/); + expect(["#ffffff", "hsla(0, 0%, 0%, 0.87)"]).toContain(color.contrastColor); + }); + }); + + it("should generate correct shade names", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: PRIMARY, + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + const expectedNames = [ + "50", + "100", + "200", + "300", + "400", + "500", + "600", + "700", + "800", + "900", + "A100", + "A200", + "A400", + "A700", + ]; + + expect(result.primary.map((c) => c.name)).toEqual(expectedNames); + }); + + it("should compute different colors for light vs dark theme", () => { + const branding = { + lightTheme: { + backgroundColor: "#ffffff", + fontColor: "#000000", + primaryColor: "#5469d4", + warnColor: "#cd3d56", + }, + darkTheme: { + backgroundColor: "#111827", + fontColor: "#ffffff", + primaryColor: "#2073c4", + warnColor: "#ff3b5b", + }, + }; + + const light = computeMap(branding, false); + const dark = computeMap(branding, true); + + // Primary colors should be different + expect(light.primary[5].hex).not.toBe(dark.primary[5].hex); + + // Background colors should be different + expect(light.background[5].hex).not.toBe(dark.background[5].hex); + + // Text colors should be different + expect(light.text[5].hex).not.toBe(dark.text[5].hex); + }); + + it("should handle custom brand colors", () => { + const customBranding = { + lightTheme: { + backgroundColor: "#f0f0f0", + fontColor: "#333333", + primaryColor: "#ff6b6b", + warnColor: "#feca57", + }, + darkTheme: { + backgroundColor: "#1e1e1e", + fontColor: "#e0e0e0", + primaryColor: "#ff8b8b", + warnColor: "#fed57", + }, + }; + + const result = computeMap(customBranding, false); + + // Should generate valid hex colors + result.primary.forEach((color) => { + expect(color.hex).toMatch(/^#[0-9a-f]{6}$/i); + }); + }); + + it("should generate lighter shades for lower values", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: "#5469d4", + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + // 50 should be lighter than 500 + const shade50 = result.primary.find((c) => c.name === "50"); + const shade500 = result.primary.find((c) => c.name === "500"); + + expect(shade50).toBeDefined(); + expect(shade500).toBeDefined(); + + // Lighter colors have higher RGB values + const rgb50 = shade50!.rgb; + const rgb500 = shade500!.rgb; + + expect(rgb50).toBeDefined(); + expect(rgb500).toBeDefined(); + }); + + it("should generate darker shades for higher values", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: "#5469d4", + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + // 900 should be darker than 500 + const shade500 = result.primary.find((c) => c.name === "500"); + const shade900 = result.primary.find((c) => c.name === "900"); + + expect(shade500).toBeDefined(); + expect(shade900).toBeDefined(); + }); + + it("should compute link colors using primary color", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: "#5469d4", + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + // Link should be computed based on primary color + expect(result.link).toHaveLength(14); + result.link.forEach((color) => { + expect(color.hex).toMatch(/^#[0-9a-f]{6}$/i); + }); + }); + + it("should handle grayscale colors", () => { + const grayscaleBranding = { + lightTheme: { + backgroundColor: "#ffffff", + fontColor: "#000000", + primaryColor: "#808080", + warnColor: "#666666", + }, + darkTheme: { + backgroundColor: "#000000", + fontColor: "#ffffff", + primaryColor: "#a0a0a0", + warnColor: "#999999", + }, + }; + + const result = computeMap(grayscaleBranding, false); + + // Should handle grayscale without errors + result.primary.forEach((color) => { + expect(color.hex).toMatch(/^#[0-9a-f]{6}$/i); + expect(color.contrastColor).toBeDefined(); + }); + }); + + it("should assign correct contrast colors for light backgrounds", () => { + const branding = { + lightTheme: { + backgroundColor: "#ffffff", + fontColor: TEXT, + primaryColor: "#ffeb3b", // Light yellow + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + // Light colors should have dark contrast + const lightShades = result.primary.filter((c) => ["50", "100", "200", "A100"].includes(c.name)); + + lightShades.forEach((color) => { + expect(color.contrastColor).toBe("hsla(0, 0%, 0%, 0.87)"); + }); + }); + + it("should assign correct contrast colors for dark backgrounds", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: "#1a237e", // Dark blue + warnColor: WARN, + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + const result = computeMap(branding, false); + + // Dark colors should have light contrast + const darkShades = result.primary.filter((c) => ["800", "900"].includes(c.name)); + + darkShades.forEach((color) => { + expect(color.contrastColor).toBe("#ffffff"); + }); + }); + }); + + describe("setTheme", () => { + let mockDocument: any; + + beforeEach(() => { + mockDocument = { + documentElement: { + style: { + setProperty: vi.fn(), + }, + }, + }; + }); + + it("should set theme with default colors when no policy provided", () => { + setTheme(mockDocument); + + expect(mockDocument.documentElement.style.setProperty).toHaveBeenCalled(); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + const hasLightBackground = propertyNames.some((name: string) => name.includes("--theme-light-background-")); + const hasDarkBackground = propertyNames.some((name: string) => name.includes("--theme-dark-background-")); + const hasLightPrimary = propertyNames.some((name: string) => name.includes("--theme-light-primary-")); + const hasDarkPrimary = propertyNames.some((name: string) => name.includes("--theme-dark-primary-")); + + expect(hasLightBackground).toBe(true); + expect(hasDarkBackground).toBe(true); + expect(hasLightPrimary).toBe(true); + expect(hasDarkPrimary).toBe(true); + }); + + it("should set theme with custom policy colors", () => { + const customPolicy = { + lightTheme: { + backgroundColor: "#f5f5f5", + fontColor: "#212121", + primaryColor: "#ff6b6b", + warnColor: "#feca57", + }, + darkTheme: { + backgroundColor: "#1a1a1a", + fontColor: "#fafafa", + primaryColor: "#ff8b8b", + warnColor: "#fed57", + }, + } as BrandingSettings; + + setTheme(mockDocument, customPolicy); + + expect(mockDocument.documentElement.style.setProperty).toHaveBeenCalled(); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + expect(calls.length).toBeGreaterThan(0); + }); + + it("should set CSS custom properties for all color shades", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900"].forEach((shade) => { + const hasShade = propertyNames.some((name: string) => name.includes(`-${shade}`)); + expect(hasShade).toBe(true); + }); + + ["A100", "A200", "A400", "A700"].forEach((shade) => { + const hasShade = propertyNames.some((name: string) => name.includes(`-${shade}`)); + expect(hasShade).toBe(true); + }); + }); + + it("should set contrast colors for each shade", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + const contrastProperties = propertyNames.filter((name: string) => name.includes("-contrast-")); + + expect(contrastProperties.length).toBeGreaterThan(0); + }); + + it("should set secondary alpha colors for text and link", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + const secondaryProperties = propertyNames.filter((name: string) => name.includes("-secondary-")); + + expect(secondaryProperties.length).toBeGreaterThan(0); + + secondaryProperties.forEach((prop: string) => { + expect(prop.includes("-text-") || prop.includes("-link-")).toBe(true); + }); + }); + + it("should set properties for both light and dark themes", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + const lightProperties = propertyNames.filter((name: string) => name.includes("--theme-light-")); + const darkProperties = propertyNames.filter((name: string) => name.includes("--theme-dark-")); + + expect(lightProperties.length).toBeGreaterThan(0); + expect(darkProperties.length).toBeGreaterThan(0); + }); + + it("should set properties for all color types", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + const types = ["background", "primary", "warn", "text", "link"]; + + types.forEach((type) => { + const typeProperties = propertyNames.filter((name: string) => name.includes(`-${type}-`)); + expect(typeProperties.length).toBeGreaterThan(0); + }); + }); + + it("should use fallback colors when policy has partial values", () => { + const partialPolicy = { + lightTheme: { + primaryColor: "#ff0000", + }, + } as BrandingSettings; + + setTheme(mockDocument, partialPolicy); + + expect(mockDocument.documentElement.style.setProperty).toHaveBeenCalled(); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + expect(calls.length).toBeGreaterThan(0); + }); + + it("should handle undefined policy gracefully", () => { + expect(() => setTheme(mockDocument, undefined)).not.toThrow(); + expect(mockDocument.documentElement.style.setProperty).toHaveBeenCalled(); + }); + + it("should set valid hex color values", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + + calls.forEach((call: any[]) => { + const [propertyName, propertyValue] = call; + + if (!propertyName.includes("-contrast-") && !propertyName.includes("-secondary-")) { + expect(propertyValue).toMatch(/^#[0-9a-f]{6}$/i); + } + }); + }); + + it("should set alpha channel for secondary colors", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + + const secondaryCalls = calls.filter((call: any[]) => call[0].includes("-secondary-")); + + secondaryCalls.forEach((call: any[]) => { + const [, propertyValue] = call; + expect(propertyValue).toMatch(/c7$/i); + }); + }); + + it("should call setProperty exactly once per CSS variable", () => { + setTheme(mockDocument); + + const calls = mockDocument.documentElement.style.setProperty.mock.calls; + const propertyNames = calls.map((call: any[]) => call[0]); + + // Check for duplicates + const uniqueProperties = new Set(propertyNames); + expect(uniqueProperties.size).toBe(propertyNames.length); + }); + }); + + describe("default color constants", () => { + it("should have valid default color values", () => { + expect(PRIMARY).toMatch(/^#[0-9a-f]{6}$/i); + expect(DARK_PRIMARY).toMatch(/^#[0-9a-f]{6}$/i); + expect(WARN).toMatch(/^#[0-9a-f]{6}$/i); + expect(DARK_WARN).toMatch(/^#[0-9a-f]{6}$/i); + expect(BACKGROUND).toMatch(/^#[0-9a-f]{6}$/i); + expect(DARK_BACKGROUND).toMatch(/^#[0-9a-f]{6}$/i); + expect(TEXT).toMatch(/^#[0-9a-f]{6}$/i); + expect(DARK_TEXT).toMatch(/^#[0-9a-f]{6}$/i); + }); + + it("should have distinct colors for light and dark themes", () => { + expect(PRIMARY).not.toBe(DARK_PRIMARY); + expect(WARN).not.toBe(DARK_WARN); + expect(BACKGROUND).not.toBe(DARK_BACKGROUND); + expect(TEXT).not.toBe(DARK_TEXT); + }); + }); + + describe("edge cases", () => { + it("should handle extreme light colors", () => { + const branding = { + lightTheme: { + backgroundColor: "#ffffff", + fontColor: "#fefefe", + primaryColor: "#fffacd", + warnColor: "#fff8dc", + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: DARK_PRIMARY, + warnColor: DARK_WARN, + }, + }; + + expect(() => computeMap(branding, false)).not.toThrow(); + }); + + it("should handle extreme dark colors", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: PRIMARY, + warnColor: WARN, + }, + darkTheme: { + backgroundColor: "#000000", + fontColor: "#010101", + primaryColor: "#0a0a0a", + warnColor: "#141414", + }, + }; + + expect(() => computeMap(branding, true)).not.toThrow(); + }); + + it("should handle highly saturated colors", () => { + const branding = { + lightTheme: { + backgroundColor: BACKGROUND, + fontColor: TEXT, + primaryColor: "#ff0000", + warnColor: "#00ff00", + }, + darkTheme: { + backgroundColor: DARK_BACKGROUND, + fontColor: DARK_TEXT, + primaryColor: "#0000ff", + warnColor: "#ffff00", + }, + }; + + const result = computeMap(branding, false); + expect(result.primary).toHaveLength(14); + expect(result.warn).toHaveLength(14); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/helpers/colors.ts b/auth/ui/v2/apps/login/src/helpers/colors.ts new file mode 100644 index 0000000..b56f16f --- /dev/null +++ b/auth/ui/v2/apps/login/src/helpers/colors.ts @@ -0,0 +1,366 @@ +import { BrandingSettings } from "@zitadel/proto/zitadel/settings/v2/branding_settings_pb"; +import tinycolor from "tinycolor2"; + +export interface Color { + name: string; + hex: string; + rgb: string; + contrastColor: string; +} + +export type MapName = "background" | "primary" | "warn" | "text" | "link"; + +export type ColorName = + "50" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "C900" | "A100" | "A200" | "A400" | "A700"; + +export type ColorMap = { + [_key in MapName]: Color[]; +}; + +export const DARK_PRIMARY = "#eeeeee"; +export const PRIMARY = "#5469d4"; + +export const DARK_WARN = "#ff3b5b"; +export const WARN = "#cd3d56"; + +export const DARK_BACKGROUND = "#252526"; +export const BACKGROUND = "#fafafa"; + +export const DARK_TEXT = "#ffffff"; +export const TEXT = "#000000"; + +export type LabelPolicyColors = { + backgroundColor: string; + backgroundColorDark: string; + fontColor: string; + fontColorDark: string; + warnColor: string; + warnColorDark: string; + primaryColor: string; + primaryColorDark: string; +}; + +type BrandingColors = { + lightTheme: { + backgroundColor: string; + fontColor: string; + primaryColor: string; + warnColor: string; + }; + darkTheme: { + backgroundColor: string; + fontColor: string; + primaryColor: string; + warnColor: string; + }; +}; + +export function setTheme(document: any, policy?: BrandingSettings) { + const lP: BrandingColors = { + lightTheme: { + backgroundColor: policy?.lightTheme?.backgroundColor || BACKGROUND, + fontColor: policy?.lightTheme?.fontColor || TEXT, + primaryColor: policy?.lightTheme?.primaryColor || PRIMARY, + warnColor: policy?.lightTheme?.warnColor || WARN, + }, + darkTheme: { + backgroundColor: policy?.darkTheme?.backgroundColor || DARK_BACKGROUND, + fontColor: policy?.darkTheme?.fontColor || DARK_TEXT, + primaryColor: policy?.darkTheme?.primaryColor || DARK_PRIMARY, + warnColor: policy?.darkTheme?.warnColor || DARK_WARN, + }, + }; + + const dark = computeMap(lP, true); + const light = computeMap(lP, false); + + setColorShades(dark.background, "background", "dark", document); + setColorShades(light.background, "background", "light", document); + + setColorShades(dark.primary, "primary", "dark", document); + setColorShades(light.primary, "primary", "light", document); + + setColorShades(dark.warn, "warn", "dark", document); + setColorShades(light.warn, "warn", "light", document); + + setColorAlpha(dark.text, "text", "dark", document); + setColorAlpha(light.text, "text", "light", document); + + setColorAlpha(dark.link, "link", "dark", document); + setColorAlpha(light.link, "link", "light", document); +} + +function setColorShades(map: Color[], type: string, theme: string, document: any) { + map.forEach((color) => { + document.documentElement.style.setProperty(`--theme-${theme}-${type}-${color.name}`, color.hex); + document.documentElement.style.setProperty(`--theme-${theme}-${type}-contrast-${color.name}`, color.contrastColor); + }); +} + +function setColorAlpha(map: Color[], type: string, theme: string, document: any) { + map.forEach((color) => { + document.documentElement.style.setProperty(`--theme-${theme}-${type}-${color.name}`, color.hex); + document.documentElement.style.setProperty(`--theme-${theme}-${type}-contrast-${color.name}`, color.contrastColor); + document.documentElement.style.setProperty(`--theme-${theme}-${type}-secondary-${color.name}`, `${color.hex}c7`); + }); +} + +function computeColors(hex: string): Color[] { + return [ + getColorObject(tinycolor(hex).lighten(52), "50"), + getColorObject(tinycolor(hex).lighten(37), "100"), + getColorObject(tinycolor(hex).lighten(26), "200"), + getColorObject(tinycolor(hex).lighten(12), "300"), + getColorObject(tinycolor(hex).lighten(6), "400"), + getColorObject(tinycolor(hex), "500"), + getColorObject(tinycolor(hex).darken(6), "600"), + getColorObject(tinycolor(hex).darken(12), "700"), + getColorObject(tinycolor(hex).darken(18), "800"), + getColorObject(tinycolor(hex).darken(24), "900"), + getColorObject(tinycolor(hex).lighten(50).saturate(30), "A100"), + getColorObject(tinycolor(hex).lighten(30).saturate(30), "A200"), + getColorObject(tinycolor(hex).lighten(10).saturate(15), "A400"), + getColorObject(tinycolor(hex).lighten(5).saturate(5), "A700"), + ]; +} + +function getColorObject(value: any, name: string): Color { + const c = tinycolor(value); + return { + name: name, + hex: c.toHexString(), + rgb: c.toRgbString(), + contrastColor: getContrast(c.toHexString()), + } as Color; +} + +function getContrast(color: string): string { + const onBlack = tinycolor.readability("#000", color); + const onWhite = tinycolor.readability("#fff", color); + if (onBlack > onWhite) { + return "hsla(0, 0%, 0%, 0.87)"; + } else { + return "#ffffff"; + } +} + +export function computeMap(branding: BrandingColors, dark: boolean): ColorMap { + return { + background: computeColors(dark ? branding.darkTheme.backgroundColor : branding.lightTheme.backgroundColor), + primary: computeColors(dark ? branding.darkTheme.primaryColor : branding.lightTheme.primaryColor), + warn: computeColors(dark ? branding.darkTheme.warnColor : branding.lightTheme.warnColor), + text: computeColors(dark ? branding.darkTheme.fontColor : branding.lightTheme.fontColor), + link: computeColors(dark ? branding.darkTheme.fontColor : branding.lightTheme.fontColor), + }; +} + +export interface ColorShade { + 200: string; + 300: string; + 500: string; + 600: string; + 700: string; + 900: string; +} + +export const COLORS = [ + { + 500: "#ef4444", + 200: "#fecaca", + 300: "#fca5a5", + 600: "#dc2626", + 700: "#b91c1c", + 900: "#7f1d1d", + }, + { + 500: "#f97316", + 200: "#fed7aa", + 300: "#fdba74", + 600: "#ea580c", + 700: "#c2410c", + 900: "#7c2d12", + }, + { + 500: "#f59e0b", + 200: "#fde68a", + 300: "#fcd34d", + 600: "#d97706", + 700: "#b45309", + 900: "#78350f", + }, + { + 500: "#eab308", + 200: "#fef08a", + 300: "#fde047", + 600: "#ca8a04", + 700: "#a16207", + 900: "#713f12", + }, + { + 500: "#84cc16", + 200: "#d9f99d", + 300: "#bef264", + 600: "#65a30d", + 700: "#4d7c0f", + 900: "#365314", + }, + { + 500: "#22c55e", + 200: "#bbf7d0", + 300: "#86efac", + 600: "#16a34a", + 700: "#15803d", + 900: "#14532d", + }, + { + 500: "#10b981", + 200: "#a7f3d0", + 300: "#6ee7b7", + 600: "#059669", + 700: "#047857", + 900: "#064e3b", + }, + { + 500: "#14b8a6", + 200: "#99f6e4", + 300: "#5eead4", + 600: "#0d9488", + 700: "#0f766e", + 900: "#134e4a", + }, + { + 500: "#06b6d4", + 200: "#a5f3fc", + 300: "#67e8f9", + 600: "#0891b2", + 700: "#0e7490", + 900: "#164e63", + }, + { + 500: "#0ea5e9", + 200: "#bae6fd", + 300: "#7dd3fc", + 600: "#0284c7", + 700: "#0369a1", + 900: "#0c4a6e", + }, + { + 500: "#3b82f6", + 200: "#bfdbfe", + 300: "#93c5fd", + 600: "#2563eb", + 700: "#1d4ed8", + 900: "#1e3a8a", + }, + { + 500: "#6366f1", + 200: "#c7d2fe", + 300: "#a5b4fc", + 600: "#4f46e5", + 700: "#4338ca", + 900: "#312e81", + }, + { + 500: "#8b5cf6", + 200: "#ddd6fe", + 300: "#c4b5fd", + 600: "#7c3aed", + 700: "#6d28d9", + 900: "#4c1d95", + }, + { + 500: "#a855f7", + 200: "#e9d5ff", + 300: "#d8b4fe", + 600: "#9333ea", + 700: "#7e22ce", + 900: "#581c87", + }, + { + 500: "#d946ef", + 200: "#f5d0fe", + 300: "#f0abfc", + 600: "#c026d3", + 700: "#a21caf", + 900: "#701a75", + }, + { + 500: "#ec4899", + 200: "#fbcfe8", + 300: "#f9a8d4", + 600: "#db2777", + 700: "#be185d", + 900: "#831843", + }, + { + 500: "#f43f5e", + 200: "#fecdd3", + 300: "#fda4af", + 600: "#e11d48", + 700: "#be123c", + 900: "#881337", + }, +]; + +export function getColorHash(value: string): ColorShade { + let hash = 0; + + if (value.length === 0) { + return COLORS[hash]; + } + + hash = hashCode(value); + return COLORS[hash % COLORS.length]; +} + +export function hashCode(str: string, seed = 0): number { + let h1 = 0xdeadbeef ^ seed, + h2 = 0x41c6ce57 ^ seed; + for (let i = 0, ch; i < str.length; i++) { + ch = str.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return 4294967296 * (2097151 & h2) + (h1 >>> 0); +} + +export function getMembershipColor(role: string): ColorShade { + const hash = hashCode(role); + switch (role) { + case "IAM_OWNER": + return COLORS[0]; + case "IAM_OWNER_VIEWER": + return COLORS[14]; + case "IAM_ORG_MANAGER": + return COLORS[11]; + case "IAM_USER_MANAGER": + return COLORS[8]; + + case "ORG_OWNER": + return COLORS[16]; + case "ORG_USER_MANAGER": + return COLORS[8]; + case "ORG_OWNER_VIEWER": + return COLORS[14]; + case "ORG_USER_PERMISSION_EDITOR": + return COLORS[7]; + case "ORG_PROJECT_PERMISSION_EDITOR": + return COLORS[11]; + case "ORG_PROJECT_CREATOR": + return COLORS[12]; + + case "PROJECT_OWNER": + return COLORS[9]; + case "PROJECT_OWNER_VIEWER": + return COLORS[10]; + case "PROJECT_OWNER_GLOBAL": + return COLORS[11]; + case "PROJECT_OWNER_VIEWER_GLOBAL": + return COLORS[12]; + + default: + return COLORS[hash % COLORS.length]; + } +} diff --git a/auth/ui/v2/apps/login/src/helpers/validators.test.ts b/auth/ui/v2/apps/login/src/helpers/validators.test.ts new file mode 100644 index 0000000..d76243f --- /dev/null +++ b/auth/ui/v2/apps/login/src/helpers/validators.test.ts @@ -0,0 +1,317 @@ +import { describe, expect, it } from "vitest"; +import { lowerCaseValidator, numberValidator, symbolValidator, upperCaseValidator } from "./validators"; + +describe("validators", () => { + describe("symbolValidator", () => { + it("should return true for strings with symbols", () => { + expect(symbolValidator("!")).toBe(true); + expect(symbolValidator("@")).toBe(true); + expect(symbolValidator("#")).toBe(true); + expect(symbolValidator("$")).toBe(true); + expect(symbolValidator("%")).toBe(true); + expect(symbolValidator("^")).toBe(true); + expect(symbolValidator("&")).toBe(true); + expect(symbolValidator("*")).toBe(true); + expect(symbolValidator("(")).toBe(true); + expect(symbolValidator(")")).toBe(true); + }); + + it("should return true for strings with punctuation", () => { + expect(symbolValidator(".")).toBe(true); + expect(symbolValidator(",")).toBe(true); + expect(symbolValidator(";")).toBe(true); + expect(symbolValidator(":")).toBe(true); + expect(symbolValidator("?")).toBe(true); + expect(symbolValidator("'")).toBe(true); + expect(symbolValidator('"')).toBe(true); + }); + + it("should return true for strings with special characters", () => { + expect(symbolValidator("-")).toBe(true); + expect(symbolValidator("_")).toBe(true); + expect(symbolValidator("=")).toBe(true); + expect(symbolValidator("+")).toBe(true); + expect(symbolValidator("[")).toBe(true); + expect(symbolValidator("]")).toBe(true); + expect(symbolValidator("{")).toBe(true); + expect(symbolValidator("}")).toBe(true); + expect(symbolValidator("|")).toBe(true); + expect(symbolValidator("\\")).toBe(true); + expect(symbolValidator("/")).toBe(true); + }); + + it("should return true for strings with whitespace", () => { + expect(symbolValidator(" ")).toBe(true); + expect(symbolValidator("\t")).toBe(true); + expect(symbolValidator("\n")).toBe(true); + }); + + it("should return false for strings with only letters", () => { + expect(symbolValidator("abc")).toBe(false); + expect(symbolValidator("ABC")).toBe(false); + expect(symbolValidator("aBc")).toBe(false); + }); + + it("should return false for strings with only numbers", () => { + expect(symbolValidator("123")).toBe(false); + expect(symbolValidator("0")).toBe(false); + }); + + it("should return false for alphanumeric strings", () => { + expect(symbolValidator("abc123")).toBe(false); + expect(symbolValidator("ABC123")).toBe(false); + expect(symbolValidator("Test123")).toBe(false); + }); + + it("should return true for mixed strings with symbols", () => { + expect(symbolValidator("Password!")).toBe(true); + expect(symbolValidator("Test@123")).toBe(true); + expect(symbolValidator("hello-world")).toBe(true); + expect(symbolValidator("user_name")).toBe(true); + }); + + it("should return false for empty strings", () => { + expect(symbolValidator("")).toBe(false); + }); + + it("should return true for Unicode symbols", () => { + expect(symbolValidator("€")).toBe(true); + expect(symbolValidator("©")).toBe(true); + expect(symbolValidator("™")).toBe(true); + }); + }); + + describe("numberValidator", () => { + it("should return true for strings with single digits", () => { + expect(numberValidator("0")).toBe(true); + expect(numberValidator("1")).toBe(true); + expect(numberValidator("5")).toBe(true); + expect(numberValidator("9")).toBe(true); + }); + + it("should return true for strings with multiple digits", () => { + expect(numberValidator("123")).toBe(true); + expect(numberValidator("000")).toBe(true); + expect(numberValidator("999")).toBe(true); + }); + + it("should return false for strings without numbers", () => { + expect(numberValidator("abc")).toBe(false); + expect(numberValidator("ABC")).toBe(false); + expect(numberValidator("test")).toBe(false); + }); + + it("should return true for alphanumeric strings", () => { + expect(numberValidator("abc123")).toBe(true); + expect(numberValidator("Test1")).toBe(true); + expect(numberValidator("1test")).toBe(true); + }); + + it("should return false for strings with only symbols", () => { + expect(numberValidator("!@#$%")).toBe(false); + expect(numberValidator("***")).toBe(false); + }); + + it("should return true for mixed content with numbers", () => { + expect(numberValidator("Password1")).toBe(true); + expect(numberValidator("Test@123")).toBe(true); + expect(numberValidator("hello-2-world")).toBe(true); + }); + + it("should return false for empty strings", () => { + expect(numberValidator("")).toBe(false); + }); + + it("should return false for whitespace only", () => { + expect(numberValidator(" ")).toBe(false); + expect(numberValidator("\t\n")).toBe(false); + }); + + it("should handle numbers anywhere in the string", () => { + expect(numberValidator("a1")).toBe(true); + expect(numberValidator("1a")).toBe(true); + expect(numberValidator("abc1def")).toBe(true); + }); + }); + + describe("upperCaseValidator", () => { + it("should return true for strings with single uppercase letters", () => { + expect(upperCaseValidator("A")).toBe(true); + expect(upperCaseValidator("Z")).toBe(true); + expect(upperCaseValidator("M")).toBe(true); + }); + + it("should return true for strings with multiple uppercase letters", () => { + expect(upperCaseValidator("ABC")).toBe(true); + expect(upperCaseValidator("TEST")).toBe(true); + expect(upperCaseValidator("HELLO")).toBe(true); + }); + + it("should return false for strings with only lowercase letters", () => { + expect(upperCaseValidator("abc")).toBe(false); + expect(upperCaseValidator("test")).toBe(false); + expect(upperCaseValidator("hello")).toBe(false); + }); + + it("should return true for mixed case strings", () => { + expect(upperCaseValidator("Test")).toBe(true); + expect(upperCaseValidator("heLLo")).toBe(true); + expect(upperCaseValidator("aBcDeF")).toBe(true); + }); + + it("should return false for strings with only numbers", () => { + expect(upperCaseValidator("123")).toBe(false); + expect(upperCaseValidator("000")).toBe(false); + }); + + it("should return false for strings with only symbols", () => { + expect(upperCaseValidator("!@#$%")).toBe(false); + expect(upperCaseValidator("***")).toBe(false); + }); + + it("should return true for complex passwords with uppercase", () => { + expect(upperCaseValidator("Password1!")).toBe(true); + expect(upperCaseValidator("test@Test123")).toBe(true); + expect(upperCaseValidator("hello-World")).toBe(true); + }); + + it("should return false for empty strings", () => { + expect(upperCaseValidator("")).toBe(false); + }); + + it("should handle uppercase anywhere in the string", () => { + expect(upperCaseValidator("Aaaa")).toBe(true); + expect(upperCaseValidator("aaaA")).toBe(true); + expect(upperCaseValidator("aaAaa")).toBe(true); + }); + + it("should work with numbers and symbols present", () => { + expect(upperCaseValidator("Test123!@#")).toBe(true); + expect(upperCaseValidator("123A456")).toBe(true); + expect(upperCaseValidator("!@#A$%^")).toBe(true); + }); + }); + + describe("lowerCaseValidator", () => { + it("should return true for strings with single lowercase letters", () => { + expect(lowerCaseValidator("a")).toBe(true); + expect(lowerCaseValidator("z")).toBe(true); + expect(lowerCaseValidator("m")).toBe(true); + }); + + it("should return true for strings with multiple lowercase letters", () => { + expect(lowerCaseValidator("abc")).toBe(true); + expect(lowerCaseValidator("test")).toBe(true); + expect(lowerCaseValidator("hello")).toBe(true); + }); + + it("should return false for strings with only uppercase letters", () => { + expect(lowerCaseValidator("ABC")).toBe(false); + expect(lowerCaseValidator("TEST")).toBe(false); + expect(lowerCaseValidator("HELLO")).toBe(false); + }); + + it("should return true for mixed case strings", () => { + expect(lowerCaseValidator("Test")).toBe(true); + expect(lowerCaseValidator("heLLo")).toBe(true); + expect(lowerCaseValidator("aBcDeF")).toBe(true); + }); + + it("should return false for strings with only numbers", () => { + expect(lowerCaseValidator("123")).toBe(false); + expect(lowerCaseValidator("000")).toBe(false); + }); + + it("should return false for strings with only symbols", () => { + expect(lowerCaseValidator("!@#$%")).toBe(false); + expect(lowerCaseValidator("***")).toBe(false); + }); + + it("should return true for complex passwords with lowercase", () => { + expect(lowerCaseValidator("Password1!")).toBe(true); + expect(lowerCaseValidator("TEST@test123")).toBe(true); + expect(lowerCaseValidator("HELLO-world")).toBe(true); + }); + + it("should return false for empty strings", () => { + expect(lowerCaseValidator("")).toBe(false); + }); + + it("should handle lowercase anywhere in the string", () => { + expect(lowerCaseValidator("aAAA")).toBe(true); + expect(lowerCaseValidator("AAAa")).toBe(true); + expect(lowerCaseValidator("AAaAA")).toBe(true); + }); + + it("should work with numbers and symbols present", () => { + expect(lowerCaseValidator("test123!@#")).toBe(true); + expect(lowerCaseValidator("123a456")).toBe(true); + expect(lowerCaseValidator("!@#a$%^")).toBe(true); + }); + }); + + describe("password complexity validation scenarios", () => { + it("should validate a strong password with all requirements", () => { + const password = "MyP@ssw0rd!"; + + expect(upperCaseValidator(password)).toBe(true); + expect(lowerCaseValidator(password)).toBe(true); + expect(numberValidator(password)).toBe(true); + expect(symbolValidator(password)).toBe(true); + }); + + it("should fail weak password without symbols", () => { + const password = "MyPassword123"; + + expect(upperCaseValidator(password)).toBe(true); + expect(lowerCaseValidator(password)).toBe(true); + expect(numberValidator(password)).toBe(true); + expect(symbolValidator(password)).toBe(false); + }); + + it("should fail password without uppercase", () => { + const password = "myp@ssw0rd!"; + + expect(upperCaseValidator(password)).toBe(false); + expect(lowerCaseValidator(password)).toBe(true); + expect(numberValidator(password)).toBe(true); + expect(symbolValidator(password)).toBe(true); + }); + + it("should fail password without lowercase", () => { + const password = "MYP@SSW0RD!"; + + expect(upperCaseValidator(password)).toBe(true); + expect(lowerCaseValidator(password)).toBe(false); + expect(numberValidator(password)).toBe(true); + expect(symbolValidator(password)).toBe(true); + }); + + it("should fail password without numbers", () => { + const password = "MyP@ssword!"; + + expect(upperCaseValidator(password)).toBe(true); + expect(lowerCaseValidator(password)).toBe(true); + expect(numberValidator(password)).toBe(false); + expect(symbolValidator(password)).toBe(true); + }); + + it("should validate very long complex password", () => { + const password = "ThisIsAVeryLongP@ssw0rd!WithManyCharacters123"; + + expect(upperCaseValidator(password)).toBe(true); + expect(lowerCaseValidator(password)).toBe(true); + expect(numberValidator(password)).toBe(true); + expect(symbolValidator(password)).toBe(true); + }); + + it("should validate password with multiple symbols", () => { + const password = "P@$$w0rd!#%"; + + expect(upperCaseValidator(password)).toBe(true); + expect(lowerCaseValidator(password)).toBe(true); + expect(numberValidator(password)).toBe(true); + expect(symbolValidator(password)).toBe(true); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/helpers/validators.ts b/auth/ui/v2/apps/login/src/helpers/validators.ts new file mode 100644 index 0000000..6a61d13 --- /dev/null +++ b/auth/ui/v2/apps/login/src/helpers/validators.ts @@ -0,0 +1,19 @@ +export function symbolValidator(value: string): boolean { + const REGEXP = /[^a-zA-Z0-9]/gi; + return REGEXP.test(value); +} + +export function numberValidator(value: string): boolean { + const REGEXP = /[0-9]/g; + return REGEXP.test(value); +} + +export function upperCaseValidator(value: string): boolean { + const REGEXP = /[A-Z]/g; + return REGEXP.test(value); +} + +export function lowerCaseValidator(value: string): boolean { + const REGEXP = /[a-z]/g; + return REGEXP.test(value); +} diff --git a/auth/ui/v2/apps/login/src/i18n/request.ts b/auth/ui/v2/apps/login/src/i18n/request.ts new file mode 100644 index 0000000..f95e08c --- /dev/null +++ b/auth/ui/v2/apps/login/src/i18n/request.ts @@ -0,0 +1,90 @@ +import { LANGS, LANGUAGE_COOKIE_NAME, LANGUAGE_HEADER_NAME } from "@/lib/i18n"; +import { mergeMessages } from "@/lib/server/merge-messages"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getAllowedLanguages, getHostedLoginTranslation } from "@/lib/server/zitadel"; +import { JsonObject } from "@zitadel/client"; +import { getRequestConfig } from "next-intl/server"; +import { cookies, headers } from "next/headers"; + +export default getRequestConfig(async () => { + const fallback = "en"; + const cookiesList = await cookies(); + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + let allowedLanguages = LANGS.map((l) => l.code); + let defaultLanguage = fallback; + + try { + const settings = await getAllowedLanguages({ serviceConfig }); + if (settings.allowedLanguages?.length) { + const localLanguageCodes = LANGS.map((l) => l.code); + allowedLanguages = settings.allowedLanguages.filter((l) => localLanguageCodes.includes(l)); + } + if (settings.defaultLanguage) { + defaultLanguage = settings.defaultLanguage; + } + } catch (e) { + console.warn("Failed to load global settings", e); + } + + let locale: string = defaultLanguage; + + const languageHeader = await (await headers()).get(LANGUAGE_HEADER_NAME); + if (languageHeader) { + // splits "en-US,en;q=0.9" to ["en", "US"] or ["en"] + const headerLocale = languageHeader.split(",")[0].split("-")[0]; + if (allowedLanguages.includes(headerLocale)) { + locale = headerLocale; + } + } + + const languageCookie = cookiesList?.get(LANGUAGE_COOKIE_NAME); + if (languageCookie && languageCookie.value) { + if (allowedLanguages.includes(languageCookie.value)) { + locale = languageCookie.value; + } else { + // If the cookie tells a language that is other than the supported ones, fall back to the default. + locale = defaultLanguage; + } + } + + const i18nOrganization = _headers.get("x-zitadel-i18n-organization") || ""; // You may need to set this header in middleware + + let translations: JsonObject | Record = {}; + try { + const i18nJSON = await getHostedLoginTranslation({ + serviceConfig, + locale, + organization: i18nOrganization, + }); + + if (i18nJSON) { + translations = i18nJSON; + } + } catch (error) { + console.warn("Error fetching custom translations:", error); + } + + const customMessages = translations; + + // Load locale messages, fall back to default language messages if locale not found + let localeMessages; + try { + localeMessages = (await import(`../../locales/${locale}.json`)).default; + } catch { + try { + localeMessages = (await import(`../../locales/${defaultLanguage}.json`)).default; + } catch { + localeMessages = (await import(`../../locales/${fallback}.json`)).default; + } + } + + const fallbackMessages = (await import(`../../locales/${fallback}.json`)).default; + + return { + locale, + messages: mergeMessages(fallbackMessages, localeMessages, customMessages) as Record, + }; +}); diff --git a/auth/ui/v2/apps/login/src/instrumentation.node.ts b/auth/ui/v2/apps/login/src/instrumentation.node.ts new file mode 100644 index 0000000..6872e72 --- /dev/null +++ b/auth/ui/v2/apps/login/src/instrumentation.node.ts @@ -0,0 +1,45 @@ +import type { LoggerProvider } from "@opentelemetry/api-logs"; + +export async function registerNode(): Promise { + const [ + { NodeSDK }, + { envDetector, processDetector, hostDetector, resourceFromAttributes }, + { containerDetector }, + { gcpDetector }, + { logs }, + { getNodeAutoInstrumentations }, + ] = await Promise.all([ + import("@opentelemetry/sdk-node"), + import("@opentelemetry/resources"), + import("@opentelemetry/resource-detector-container"), + import("@opentelemetry/resource-detector-gcp"), + import("@opentelemetry/api-logs"), + import("@opentelemetry/auto-instrumentations-node"), + ]); + + const sdk = new NodeSDK({ + resource: resourceFromAttributes({ + "deployment.environment.name": process.env.NODE_ENV || "development", + }), + resourceDetectors: [envDetector, processDetector, hostDetector, containerDetector, gcpDetector], + instrumentations: [ + getNodeAutoInstrumentations({ + "@opentelemetry/instrumentation-http": { + ignoreIncomingRequestHook: (req) => + ["/healthy", "/ready", "/_next/", "/favicon.ico", "/__nextjs", "/metrics"].some((p) => req.url?.includes(p)), + }, + "@opentelemetry/instrumentation-fs": { enabled: false }, + "@opentelemetry/instrumentation-winston": { disableLogSending: false }, + }), + ], + }); + + sdk.start(); + + // Use console during shutdown as the logger may be unavailable + const shutdown = () => sdk.shutdown().catch(console.error); + process.once("SIGTERM", shutdown); + process.once("SIGINT", shutdown); + + return logs.getLoggerProvider(); +} diff --git a/auth/ui/v2/apps/login/src/instrumentation.test.ts b/auth/ui/v2/apps/login/src/instrumentation.test.ts new file mode 100644 index 0000000..f3f5ff7 --- /dev/null +++ b/auth/ui/v2/apps/login/src/instrumentation.test.ts @@ -0,0 +1,155 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const verifyApiCredentials = vi.fn(); +const registerNode = vi.fn(); + +// Keep the real FATAL_CREDENTIAL_CHECK_RESULTS, but replace the check itself +// and cut the import chain into the API client. +vi.mock("@/lib/server/verify-credentials", async (importOriginal) => ({ + ...(await importOriginal()), + verifyApiCredentials, +})); +vi.mock("@/lib/server/service", () => ({ createServiceForHost: vi.fn() })); +vi.mock("./instrumentation.node", () => ({ registerNode })); +const startupLogger = { warn: vi.fn(), error: vi.fn() }; +vi.mock("@/lib/server/logger", () => ({ createLogger: () => startupLogger })); + +async function loadRegister() { + vi.resetModules(); + const { register } = await import("./instrumentation"); + return register; +} + +describe("register", () => { + const savedEnv = { + NEXT_RUNTIME: process.env.NEXT_RUNTIME, + NODE_ENV: process.env.NODE_ENV, + OTEL_SDK_DISABLED: process.env.OTEL_SDK_DISABLED, + }; + let exitSpy: ReturnType; + + beforeEach(() => { + process.env.NEXT_RUNTIME = "nodejs"; + process.env.OTEL_SDK_DISABLED = "true"; + verifyApiCredentials.mockReset().mockResolvedValue("ok"); + registerNode.mockReset().mockResolvedValue(null); + exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); + startupLogger.warn.mockReset(); + startupLogger.error.mockReset(); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + }); + + afterEach(() => { + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + test("verifies credentials on startup and continues when they are accepted", async () => { + const register = await loadRegister(); + + await register(); + + expect(verifyApiCredentials).toHaveBeenCalledTimes(1); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + test.each(["rejected", "invalid", "missing"])("exits the process when the credential check returns %s", async (result) => { + verifyApiCredentials.mockResolvedValue(result); + const register = await loadRegister(); + + await register(); + + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + test.each(["unreachable", "skipped"])("continues when the credential check returns %s", async (result) => { + verifyApiCredentials.mockResolvedValue(result); + const register = await loadRegister(); + + await register(); + + expect(exitSpy).not.toHaveBeenCalled(); + }); + + test("does nothing outside the nodejs runtime", async () => { + process.env.NEXT_RUNTIME = "edge"; + const register = await loadRegister(); + + await register(); + + expect(verifyApiCredentials).not.toHaveBeenCalled(); + expect(registerNode).not.toHaveBeenCalled(); + }); + + test("registers OpenTelemetry before the credential check when enabled", async () => { + delete process.env.OTEL_SDK_DISABLED; + const calls: string[] = []; + registerNode.mockImplementation(async () => { + calls.push("otel"); + return null; + }); + verifyApiCredentials.mockImplementation(async () => { + calls.push("credentials"); + return "ok"; + }); + const register = await loadRegister(); + + await register(); + + expect(calls).toEqual(["otel", "credentials"]); + }); + + test("still verifies credentials when OpenTelemetry is disabled", async () => { + const register = await loadRegister(); + + await register(); + + expect(registerNode).not.toHaveBeenCalled(); + expect(verifyApiCredentials).toHaveBeenCalledTimes(1); + }); + + describe("session cookie secret notice", () => { + test("logs nothing when a dedicated secret is configured", async () => { + const register = await loadRegister(); + + await register(); + + expect(startupLogger.warn).not.toHaveBeenCalled(); + expect(startupLogger.error).not.toHaveBeenCalled(); + }); + + test("warns about the deprecated credential fallback, also in development", async () => { + vi.stubEnv("NODE_ENV", "development"); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", undefined); + vi.stubEnv("ZITADEL_SERVICE_USER_TOKEN", "service-user-token"); + const register = await loadRegister(); + + await register(); + + expect(startupLogger.warn).toHaveBeenCalledWith(expect.stringMatching(/fallback is deprecated/)); + }); + + test("logs an error for a too short secret before the credential check", async () => { + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "too-short"); + const calls: string[] = []; + startupLogger.error.mockImplementation(() => calls.push("notice")); + verifyApiCredentials.mockImplementation(async () => { + calls.push("credentials"); + return "ok"; + }); + const register = await loadRegister(); + + await register(); + + expect(calls).toEqual(["notice", "credentials"]); + expect(startupLogger.error).toHaveBeenCalledWith(expect.stringMatching(/at least 32 characters/)); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/instrumentation.ts b/auth/ui/v2/apps/login/src/instrumentation.ts new file mode 100644 index 0000000..4739d71 --- /dev/null +++ b/auth/ui/v2/apps/login/src/instrumentation.ts @@ -0,0 +1,79 @@ +import type { LoggerProvider } from "@opentelemetry/api-logs"; + +/** + * @module instrumentation + * + * OpenTelemetry instrumentation for Next.js applications using NodeSDK. + * Set OTEL_SDK_DISABLED=true to disable instrumentation entirely. + * + * Configuration via standard OTEL environment variables: + * + * ### Exporters (all default to "otlp") + * - OTEL_TRACES_EXPORTER: trace exporter (otlp, console, none) + * - OTEL_METRICS_EXPORTER: metric exporter (otlp, prometheus, console, none) + * - OTEL_LOGS_EXPORTER: log exporter (otlp, console, none) + * - OTEL_EXPORTER_OTLP_ENDPOINT: base endpoint for OTLP signals + * - OTEL_EXPORTER_PROMETHEUS_PORT: Prometheus scrape port (default 9464) + * + * ### Batch Processors + * - OTEL_BSP_SCHEDULE_DELAY: span export delay (default 5000ms) + * - OTEL_METRIC_EXPORT_INTERVAL: metric push interval (default 60000ms) + * + * ### Resource + * - OTEL_SERVICE_NAME: service.name attribute + * - OTEL_RESOURCE_ATTRIBUTES: additional attributes (key=value,key=value) + * + * @see https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/ + */ + +let _loggerProvider: LoggerProvider | null = null; + +export async function register(): Promise { + // Only run in the Node.js environment + if (process.env.NEXT_RUNTIME !== "nodejs") return; + + if (isOtelEnabled()) { + const { registerNode } = await import("./instrumentation.node"); + _loggerProvider = await registerNode(); + } + + // Logged after the SDK is registered so the logger is instrumented, and before the + // credential check so it is visible even if that check exits the process. + await logSessionCookieSecretNotice(); + + // Verify the configured API credentials once at startup (fail fast). + // Connectivity problems are only logged; reachability is covered by the + // readiness probe (/ready) and ZITADEL_API_AWAITINITIALCONN. + const { verifyApiCredentials, FATAL_CREDENTIAL_CHECK_RESULTS } = await import("@/lib/server/verify-credentials"); + const result = await verifyApiCredentials(); + if (FATAL_CREDENTIAL_CHECK_RESULTS.has(result)) { + process.exit(1); + } +} + +function isOtelEnabled(): boolean { + // Disable by default in local development to avoid unnecessary overhead + if (process.env.NODE_ENV === "development" && process.env.OTEL_SDK_DISABLED !== "false") { + return false; + } + // Explicit check for disabled env variable + return process.env.OTEL_SDK_DISABLED !== "true"; +} + +/** + * Logs once at startup if session cookies are signed via the deprecated API credential fallback + * or cannot be signed at all (see lib/session-cookie-signature.ts). + */ +async function logSessionCookieSecretNotice(): Promise { + const { getSessionCookieSecretStartupNotice } = await import("@/lib/server/session-cookie-signature"); + const notice = getSessionCookieSecretStartupNotice(); + if (!notice) { + return; + } + const { createLogger } = await import("@/lib/server/logger"); + createLogger("startup")[notice.level](notice.message); +} + +export function getLoggerProvider(): LoggerProvider | null { + return _loggerProvider; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/device.test.ts b/auth/ui/v2/apps/login/src/lib/actions/device.test.ts new file mode 100644 index 0000000..ebaf3aa --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/device.test.ts @@ -0,0 +1,213 @@ +import { approveDeviceAuthorization, denyDeviceAuthorization } from "@/lib/actions/device"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@/lib/server/zitadel", () => ({ + authorizeOrDenyDeviceAuthorization: vi.fn(), + getDeviceAuthorizationRequest: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + isSessionValid: vi.fn(), + loadSession: vi.fn(), +})); + +vi.mock("@/lib/server/device-code-check", () => ({ + checkDeviceCodeCheckCookie: vi.fn(), + deleteDeviceCodeCheckCookie: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("@/lib/actions/loginname", () => ({ + sendLoginname: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +const cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + organization: "org-1", +}; + +const session = { + id: "session-1", + factors: { user: { id: "user-1", loginName: "user@example.com", organizationId: "org-1" } }, +}; + +describe("device authorization actions", () => { + let authorizeOrDenyDeviceAuthorization: any; + let getDeviceAuthorizationRequest: any; + let loadSession: any; + let getSessionCookieById: any; + let isSessionValid: any; + let sendLoginname: any; + let checkDeviceCodeCheckCookie: any; + let deleteDeviceCodeCheckCookie: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const zitadel = await import("@/lib/server/zitadel"); + const cookies = await import("@/lib/server/cookies"); + const sessionLib = await import("@/lib/server/session"); + const loginname = await import("@/lib/actions/loginname"); + const deviceCodeCheck = await import("@/lib/server/device-code-check"); + + authorizeOrDenyDeviceAuthorization = vi.mocked(zitadel.authorizeOrDenyDeviceAuthorization); + getDeviceAuthorizationRequest = vi.mocked(zitadel.getDeviceAuthorizationRequest); + loadSession = vi.mocked(sessionLib.loadSession); + getSessionCookieById = vi.mocked(cookies.getSessionCookieById); + isSessionValid = vi.mocked(sessionLib.isSessionValid); + sendLoginname = vi.mocked(loginname.sendLoginname); + checkDeviceCodeCheckCookie = vi.mocked(deviceCodeCheck.checkDeviceCodeCheckCookie); + deleteDeviceCodeCheckCookie = vi.mocked(deviceCodeCheck.deleteDeviceCodeCheckCookie); + + getSessionCookieById.mockResolvedValue(cookie); + loadSession.mockResolvedValue(session); + checkDeviceCodeCheckCookie.mockResolvedValue(true); + isSessionValid.mockResolvedValue(true); + getDeviceAuthorizationRequest.mockResolvedValue({ + deviceAuthorizationRequest: { id: "device-request-1", appName: "My Device" }, + }); + authorizeOrDenyDeviceAuthorization.mockResolvedValue({ details: {} }); + }); + + describe("approveDeviceAuthorization", () => { + test("approves with the session of the cookie identified by sessionId", async () => { + const res = await approveDeviceAuthorization({ + userCode: "ABCD-1234", + sessionId: "session-1", + organization: "org-1", + }); + + expect(checkDeviceCodeCheckCookie).toHaveBeenCalledWith("ABCD-1234"); + expect(getSessionCookieById).toHaveBeenCalledWith({ sessionId: "session-1", organization: "org-1" }); + expect(loadSession).toHaveBeenCalledWith(expect.anything(), cookie); + expect(getDeviceAuthorizationRequest).toHaveBeenCalledWith({ + serviceConfig: expect.anything(), + userCode: "ABCD-1234", + }); + expect(authorizeOrDenyDeviceAuthorization).toHaveBeenCalledWith({ + serviceConfig: expect.anything(), + deviceAuthorizationId: "device-request-1", + session: { sessionId: "session-1", sessionToken: "token-1" }, + }); + expect(res).toEqual({ redirect: expect.stringContaining("/signedin?") }); + expect((res as { redirect: string }).redirect).toContain("requestId=device_ABCD-1234"); + expect(deleteDeviceCodeCheckCookie).toHaveBeenCalled(); + }); + + test("redirects to the code entry page and does not approve when the device code check fails", async () => { + checkDeviceCodeCheckCookie.mockResolvedValue(false); + + const res = await approveDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(res).toEqual({ redirect: "/device?user_code=ABCD-1234" }); + expect(getDeviceAuthorizationRequest).not.toHaveBeenCalled(); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + + test("returns an error and does not approve when the session is stale", async () => { + loadSession.mockResolvedValue(undefined); + + const res = await approveDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(res).toEqual({ error: "sessionExpired" }); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + + test("never takes the session token from the caller", async () => { + await approveDeviceAuthorization({ + userCode: "ABCD-1234", + sessionId: "session-1", + sessionToken: "attacker-token", + } as any); + + expect(authorizeOrDenyDeviceAuthorization).toHaveBeenCalledWith( + expect.objectContaining({ session: { sessionId: "session-1", sessionToken: "token-1" } }), + ); + }); + + test("returns an error and does not approve when no cookie matches", async () => { + getSessionCookieById.mockResolvedValue(undefined); + + const res = await approveDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(res).toHaveProperty("error"); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + + test("returns a redirect into the login funnel and does not approve when the session is not valid", async () => { + isSessionValid.mockResolvedValue(false); + sendLoginname.mockResolvedValue({ redirect: "/password?loginName=user%40example.com" }); + + const res = await approveDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(sendLoginname).toHaveBeenCalledWith({ + loginName: "user@example.com", + organization: "org-1", + requestId: "device_ABCD-1234", + }); + expect(res).toEqual({ redirect: "/password?loginName=user%40example.com" }); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + }); + + describe("denyDeviceAuthorization", () => { + test("denies the request without passing the session to the backend", async () => { + await denyDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1", organization: "org-1" }); + + expect(getSessionCookieById).toHaveBeenCalledWith({ sessionId: "session-1", organization: "org-1" }); + + expect(getDeviceAuthorizationRequest).toHaveBeenCalledWith({ + serviceConfig: expect.anything(), + userCode: "ABCD-1234", + }); + expect(authorizeOrDenyDeviceAuthorization).toHaveBeenCalledWith({ + serviceConfig: expect.anything(), + deviceAuthorizationId: "device-request-1", + }); + expect(deleteDeviceCodeCheckCookie).toHaveBeenCalled(); + }); + + test("redirects to the code entry page and does not deny when the device code check fails", async () => { + checkDeviceCodeCheckCookie.mockResolvedValue(false); + + const res = await denyDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(res).toEqual({ redirect: "/device?user_code=ABCD-1234" }); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + + test("returns an error and does not deny without a session cookie", async () => { + getSessionCookieById.mockResolvedValue(undefined); + + const res = await denyDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(res).toEqual({ error: "unknownContext" }); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + + test("returns an error and does not deny when the session is stale", async () => { + loadSession.mockResolvedValue(undefined); + + const res = await denyDeviceAuthorization({ userCode: "ABCD-1234", sessionId: "session-1" }); + + expect(res).toEqual({ error: "sessionExpired" }); + expect(authorizeOrDenyDeviceAuthorization).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/device.ts b/auth/ui/v2/apps/login/src/lib/actions/device.ts new file mode 100644 index 0000000..13cdc73 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/device.ts @@ -0,0 +1,129 @@ +"use server"; + +import { sendLoginname } from "@/lib/actions/loginname"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { checkDeviceCodeCheckCookie, deleteDeviceCodeCheckCookie } from "@/lib/server/device-code-check"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { isSessionValid, loadSession } from "@/lib/server/session"; +import { authorizeOrDenyDeviceAuthorization, getDeviceAuthorizationRequest } from "@/lib/server/zitadel"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +type DeviceAuthorizationCommand = { + userCode: string; + sessionId: string; + organization?: string; +}; + +// Shared by approve and deny: the user code must have been entered in this browser, +// and the session must come from this browser's `sessions` cookie and still exist. +async function resolveConsentSession({ userCode, sessionId, organization }: DeviceAuthorizationCommand) { + if (!(await checkDeviceCodeCheckCookie(userCode))) { + return { redirect: "/device?" + new URLSearchParams({ user_code: userCode }) }; + } + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const t = await getTranslations("error"); + + const cookie = await getSessionCookieById({ sessionId, organization }); + + if (!cookie) { + return { error: t("unknownContext") }; + } + + const session = await loadSession(serviceConfig, cookie); + + if (!session?.factors?.user) { + return { error: t("sessionExpired") }; + } + + return { serviceConfig, t, cookie, session, user: session.factors.user }; +} + +/** + * Approves a device authorization request for the user of the current session. + * + * The session token is never taken from the caller: it is read from the `sessions` cookie + * server-side. Together with the Next.js server action origin check this makes the approval + * an explicit, same-origin user action instead of a side effect of rendering a page. + * The `deviceCodeCheck` cookie makes sure the user code was entered in this browser. + */ +export async function approveDeviceAuthorization(command: DeviceAuthorizationCommand) { + const consent = await resolveConsentSession(command); + + if (!consent.session) { + return consent; + } + + const { userCode, organization } = command; + const { serviceConfig, t, cookie, session, user } = consent; + + // Validate the session (including MFA) before handing out a token to the device. + const valid = await isSessionValid({ serviceConfig, session }); + + if (!valid) { + // Send the user through the login funnel, the same way continueWithSession does. + const res = await sendLoginname({ + loginName: user.loginName, + organization: user.organizationId, + requestId: `device_${userCode}`, + }); + + if (res && "redirect" in res && res.redirect) { + return { redirect: res.redirect }; + } + + return { error: t("sessionExpired") }; + } + + const { deviceAuthorizationRequest } = await getDeviceAuthorizationRequest({ serviceConfig, userCode }); + + if (!deviceAuthorizationRequest) { + return { error: t("noDeviceRequest") }; + } + + await authorizeOrDenyDeviceAuthorization({ + serviceConfig, + deviceAuthorizationId: deviceAuthorizationRequest.id, + session: { sessionId: cookie.id, sessionToken: cookie.token }, + }); + + await deleteDeviceCodeCheckCookie(); + + const params = new URLSearchParams({ requestId: `device_${userCode}`, sessionId: cookie.id }); + + if (organization) { + params.append("organization", organization); + } + + return { redirect: `/signedin?` + params }; +} + +export async function denyDeviceAuthorization(command: DeviceAuthorizationCommand) { + const consent = await resolveConsentSession(command); + + if (!consent.session) { + return consent; + } + + const { userCode } = command; + const { serviceConfig, t } = consent; + + const { deviceAuthorizationRequest } = await getDeviceAuthorizationRequest({ serviceConfig, userCode }); + + if (!deviceAuthorizationRequest) { + return { error: t("noDeviceRequest") }; + } + + // without a session, the device auth request is denied + const response = await authorizeOrDenyDeviceAuthorization({ + serviceConfig, + deviceAuthorizationId: deviceAuthorizationRequest.id, + }); + + await deleteDeviceCodeCheckCookie(); + + return response; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/flow.ts b/auth/ui/v2/apps/login/src/lib/actions/flow.ts new file mode 100644 index 0000000..efc97f6 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/flow.ts @@ -0,0 +1,41 @@ +"use server"; + +import { completeAuthFlow } from "@/lib/server/auth-flow"; +import { FinishFlowCommand, getNextUrl } from "@/lib/server/next-url"; + +/** + * Complete authentication flow or get next URL for navigation + * - For OIDC/SAML flows with sessionId+requestId: completes flow directly via server action + * - For device flows: returns URL to signed-in page + * - For other cases: returns default redirect or fallback URL + */ +export async function completeFlowOrGetUrl( + command: FinishFlowCommand & { organization?: string }, + defaultRedirectUri?: string, +): Promise<{ redirect: string } | { error: string } | { samlData: { url: string; fields: Record } }> { + console.log("completeFlowOrGetUrl called with:", command, "defaultRedirectUri:", defaultRedirectUri); + + // Complete OIDC/SAML flows directly with server action + if ( + "sessionId" in command && + "requestId" in command && + (command.requestId.startsWith("saml_") || command.requestId.startsWith("oidc_")) + ) { + console.log("completeFlowOrGetUrl: OIDC/SAML flow detected"); + // This completes the flow and returns a redirect URL or error + const result = await completeAuthFlow({ + sessionId: command.sessionId, + requestId: command.requestId, + }); + console.log("completeFlowOrGetUrl: got OIDC/SAML flow result"); + return result; + } + + console.log("completeFlowOrGetUrl: Regular flow, getting next URL"); + // For all other cases, return URL for navigation + const url = await getNextUrl(command, defaultRedirectUri); + console.log("completeFlowOrGetUrl: got Next URL:", url); + const result = { redirect: url }; + console.log("completeFlowOrGetUrl: got final result"); + return result; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/idp-intent.test.ts b/auth/ui/v2/apps/login/src/lib/actions/idp-intent.test.ts new file mode 100644 index 0000000..7378220 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/idp-intent.test.ts @@ -0,0 +1,1687 @@ +import { processIDPCallback } from "@/lib/actions/idp-intent"; +import { createIdpFlowProof } from "@/lib/server/idp-flow-proof"; +import { AutoLinkingOption } from "@zitadel/proto/zitadel/idp/v2/idp_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import crypto from "crypto"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +// Mock all the dependencies +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("@zitadel/client", () => ({ + create: vi.fn((schema: any, data: any) => data), + // Convert a {seconds} Timestamp-like object into a real Date so the real + // hasVerifiedPrimaryFactor (via the enrollment guard) can evaluate expiry. + timestampDate: vi.fn((ts: { seconds: bigint | number }) => new Date(Number(ts.seconds) * 1000)), + ConnectError: class extends Error { + code: any; + constructor(message: string, code: any) { + super(message); + this.code = code; + } + }, + Code: { + AlreadyExists: 6, + }, +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + retrieveIDPIntent: vi.fn(), + getIDPByID: vi.fn(), + updateUser: vi.fn(), + addIDPLink: vi.fn(), + listUsers: vi.fn(), + createUser: vi.fn(), + getLoginSettings: vi.fn(), + getOrgsByDomain: vi.fn(), + getActiveIdentityProviders: vi.fn(), + getUserByID: vi.fn(), + getDefaultOrg: vi.fn(), + getSession: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), +})); + +vi.mock("@/lib/server/idp-session", () => ({ + createNewSessionFromIdpIntent: vi.fn(), +})); + +// The linking guard (getEnrollmentAuthorizationError) runs for real; only its +// leaf dependency checkUserVerification (cookie/fingerprint proof) is mocked. +vi.mock("@/lib/server/verify-helper", () => ({ + checkUserVerification: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +vi.mock("@/lib/server/fingerprint", () => ({ + getBindingIdCookie: vi.fn(), +})); + +describe("processIDPCallback", () => { + // Mock modules + let mockHeaders: any; + let mockGetServiceUrlFromHeaders: any; + let mockRetrieveIDPIntent: any; + let mockGetIDPByID: any; + let mockUpdateUser: any; + let mockAddIDPLink: any; + let mockListUsers: any; + let mockCreateUser: any; + let mockGetLoginSettings: any; + let mockGetOrgsByDomain: any; + let mockGetActiveIdentityProviders: any; + let mockGetUserByID: any; + let mockGetDefaultOrg: any; + let mockGetSession: any; + let mockCreateNewSessionFromIdpIntent: any; + let mockGetSessionCookieById: any; + let mockGetBindingIdCookie: any; + let mockListAuthenticationMethodTypes: any; + let mockCheckUserVerification: any; + + const browserBindingId = "fp123"; + // assigned in beforeEach: the flowFingerprint proof needs the signing secret + let defaultParams: { + provider: string; + id: string; + token: string; + requestId: string; + organization: string; + flowFingerprint: string; + }; + + const defaultIntent = { + idpInformation: { + idpId: "idp123", + userId: "user123", + userName: "testuser", + }, + userId: "user123", + addHumanUser: { + username: "testuser", + profile: { + givenName: "Test", + familyName: "User", + displayName: "Test User", + }, + email: { + email: "test@example.com", + verification: { + case: "isVerified", + value: true, + }, + }, + }, + updateHumanUser: { + username: "testuser", + profile: { + givenName: "Test", + familyName: "User 1", + displayName: "Test User 1", + }, + email: { + email: "test@example.com", + verification: { + case: "isVerified", + value: true, + }, + }, + }, + }; + + const defaultIdp = { + id: "idp123", + config: { + options: { + isAutoUpdate: false, + isLinkingAllowed: false, + isCreationAllowed: false, + isAutoCreation: false, + autoLinking: undefined, + }, + }, + }; + + beforeEach(async () => { + vi.resetAllMocks(); + + // Import mocked modules + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { + retrieveIDPIntent, + getIDPByID, + updateUser, + addIDPLink, + listUsers, + createUser, + getLoginSettings, + getOrgsByDomain, + getActiveIdentityProviders, + getUserByID, + getDefaultOrg, + getSession, + listAuthenticationMethodTypes, + } = await import("@/lib/server/zitadel"); + const { createNewSessionFromIdpIntent } = await import("@/lib/server/idp-session"); + const { getSessionCookieById } = await import("@/lib/server/cookies"); + const { getBindingIdCookie } = await import("@/lib/server/fingerprint"); + const { checkUserVerification } = await import("@/lib/server/verify-helper"); + + // Setup mocks + mockHeaders = vi.mocked(headers); + mockGetServiceUrlFromHeaders = vi.mocked(getServiceConfig); + mockRetrieveIDPIntent = vi.mocked(retrieveIDPIntent); + mockGetIDPByID = vi.mocked(getIDPByID); + mockUpdateUser = vi.mocked(updateUser); + mockAddIDPLink = vi.mocked(addIDPLink); + mockListUsers = vi.mocked(listUsers); + mockCreateUser = vi.mocked(createUser); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockGetOrgsByDomain = vi.mocked(getOrgsByDomain); + mockGetActiveIdentityProviders = vi.mocked(getActiveIdentityProviders); + mockGetUserByID = vi.mocked(getUserByID); + mockGetDefaultOrg = vi.mocked(getDefaultOrg); + mockGetSession = vi.mocked(getSession); + + mockCreateNewSessionFromIdpIntent = vi.mocked(createNewSessionFromIdpIntent); + mockGetSessionCookieById = vi.mocked(getSessionCookieById); + mockGetBindingIdCookie = vi.mocked(getBindingIdCookie); + mockListAuthenticationMethodTypes = vi.mocked(listAuthenticationMethodTypes); + mockCheckUserVerification = vi.mocked(checkUserVerification); + + // Default: the callback is opened in the browser that started the flow + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + defaultParams = { + provider: "google", + id: "intent123", + token: "token123", + requestId: "req123", + organization: "org123", + flowFingerprint: createIdpFlowProof(browserBindingId), + }; + mockGetBindingIdCookie.mockResolvedValue({ name: "bindingId", value: browserBindingId }); + + // Default mock implementations + mockHeaders.mockResolvedValue({} as any); + mockGetServiceUrlFromHeaders.mockReturnValue({ + serviceConfig: { baseUrl: "https://api.example.com" }, + }); + mockRetrieveIDPIntent.mockResolvedValue(defaultIntent); + mockGetIDPByID.mockResolvedValue(defaultIdp); + mockCreateNewSessionFromIdpIntent.mockResolvedValue({ + redirect: "https://app.example.com/success", + }); + + // Default mocks for validation functions + mockGetUserByID.mockResolvedValue({ + userId: "user123", + details: { + resourceOwner: "org123", + }, + }); + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp123", name: "Test IDP" }], + }); + // Default: the linking guard authorizes (no configured auth methods yet + a passed + // user-verification check — the first-authenticator onboarding path). Individual tests + // override these to exercise the identify-only rejection paths. + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + mockCheckUserVerification.mockResolvedValue(true); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + describe("Parameter validation", () => { + test("should return error redirect when provider is missing", async () => { + const result = await processIDPCallback({ + provider: "", + id: "intent123", + token: "token123", + }); + + expect(result.redirect).toContain("/idp//failure"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + }); + + test("should return error redirect when id is missing", async () => { + const result = await processIDPCallback({ + provider: "google", + id: "", + token: "token123", + }); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + }); + + test("should return error redirect when token is missing", async () => { + const result = await processIDPCallback({ + provider: "google", + id: "intent123", + token: "", + }); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + }); + + test("should preserve requestId and organization in error redirect", async () => { + const result = await processIDPCallback({ + provider: "google", + id: "", + token: "token123", + requestId: "req123", + organization: "org123", + }); + + expect(result.redirect).toContain("requestId=req123"); + expect(result.redirect).toContain("organization=org123"); + }); + }); + + describe("Browser binding (flowFingerprint)", () => { + test.each([ + ["a missing proof", () => undefined], + ["a proof for another browser", () => createIdpFlowProof("attacker-fp")], + ["a linking flow proof for a sign-in", () => createIdpFlowProof(browserBindingId, "session123")], + ["a garbage value", () => "not-a-proof"], + ])("should reject %s without touching the intent", async (_name, makeFlowFingerprint) => { + const result = await processIDPCallback({ + ...defaultParams, + postErrorRedirectUrl: "https://app.example.com/error", + flowFingerprint: makeFlowFingerprint(), + }); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(result.redirect).toContain("error=flow_mismatch"); + expect(result.redirect).toContain("requestId=req123"); + expect(result.redirect).toContain("organization=org123"); + expect(result.redirect).toContain("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + expect(mockCreateNewSessionFromIdpIntent).not.toHaveBeenCalled(); + }); + + test("should reject a proof signed for the API-visible fingerprintId instead of the binding id", async () => { + // an attacker can read a victim's fingerprintId through the Session API and get a proof signed for it, + // but the proof is checked against the binding id cookie, which never leaves the browser + mockGetBindingIdCookie.mockResolvedValue({ name: "bindingId", value: "secret-binding-id" }); + + const result = await processIDPCallback({ ...defaultParams, flowFingerprint: createIdpFlowProof("api-visible-fp") }); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + expect(mockCreateNewSessionFromIdpIntent).not.toHaveBeenCalled(); + }); + + test("should reject a valid proof when the browser has no binding id cookie", async () => { + mockGetBindingIdCookie.mockResolvedValue(undefined); + + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + expect(mockCreateNewSessionFromIdpIntent).not.toHaveBeenCalled(); + }); + + test("should sign in when the proof matches the binding id cookie of this browser", async () => { + const result = await processIDPCallback(defaultParams); + + expect(mockRetrieveIDPIntent).toHaveBeenCalled(); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + }); + + describe("Intent retrieval errors", () => { + test("should return error redirect when IDP information is missing", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + idpInformation: undefined, + userId: "user123", + }); + + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(result.redirect).toContain("error=missing_idp_info"); + }); + + test("should return error when IDP is not found", async () => { + mockGetIDPByID.mockResolvedValue(null); + + const result = await processIDPCallback(defaultParams); + + expect(result.error).toBe("errors.idpNotFound"); + }); + + test("should handle retrieval errors gracefully", async () => { + mockRetrieveIDPIntent.mockRejectedValue(new Error("Network error")); + + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(result.redirect).toContain("error=Network+error"); + expect(result.redirect).toContain("requestId=req123"); + }); + }); + + describe("CASE 1: User exists and should sign in", () => { + test("should create session for existing user without auto-update", async () => { + const result = await processIDPCallback(defaultParams); + + expect(mockRetrieveIDPIntent).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + id: "intent123", + token: "token123", + }); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith({ + userId: "user123", + idpIntent: { + idpIntentId: "intent123", + idpIntentToken: "token123", + }, + requestId: "req123", + organization: "org123", + }); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should auto-update user profile when enabled", async () => { + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoUpdate: true, + }, + }, + }); + + await processIDPCallback(defaultParams); + + // Falls back to the deprecated update_human_user and maps it into the new UpdateUser shape. + expect(mockUpdateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + userId: "user123", + userType: expect.objectContaining({ + case: "human", + value: expect.objectContaining({ + profile: expect.objectContaining({ + givenName: "Test", + familyName: "User 1", + }), + email: defaultIntent.updateHumanUser.email, + }), + }), + }), + }); + }); + + test("should auto-update user from the new update_user action including metadata", async () => { + const metadata = [{ key: "role", value: new Uint8Array([1, 2, 3]) }]; + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + // New user_action oneof: takes precedence over the deprecated update_human_user field. + addHumanUser: undefined, + updateHumanUser: undefined, + userAction: { + case: "updateUser", + value: { + userId: "user123", + userType: { + case: "human", + value: { + profile: { givenName: "Test", familyName: "User 1" }, + email: { email: "test@example.com" }, + }, + }, + metadata, + }, + }, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoUpdate: true, + }, + }, + }); + + await processIDPCallback(defaultParams); + + expect(mockUpdateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + userId: "user123", + userType: expect.objectContaining({ + case: "human", + value: expect.objectContaining({ + profile: { givenName: "Test", familyName: "User 1" }, + email: { email: "test@example.com" }, + }), + }), + metadata, + }), + }); + }); + + test("should auto-update metadata even when the update_user action has no human userType", async () => { + const metadata = [{ key: "role", value: new Uint8Array([1, 2, 3]) }]; + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + addHumanUser: undefined, + updateHumanUser: undefined, + // Metadata-only update: user_type is unset, only metadata is provided. + userAction: { + case: "updateUser", + value: { + userId: "user123", + userType: { case: undefined, value: undefined }, + metadata, + }, + }, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoUpdate: true, + }, + }, + }); + + await processIDPCallback(defaultParams); + + // Metadata must still be applied, without forcing a human userType. + expect(mockUpdateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + userId: "user123", + metadata, + }), + }); + expect(mockUpdateUser.mock.calls[0][0].request.userType).toBeUndefined(); + }); + + test("should skip auto-update when update_user action has neither human data nor metadata", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + addHumanUser: undefined, + updateHumanUser: undefined, + userAction: { + case: "updateUser", + value: { + userId: "user123", + userType: { case: undefined, value: undefined }, + metadata: [], + }, + }, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoUpdate: true, + }, + }, + }); + + await processIDPCallback(defaultParams); + + expect(mockUpdateUser).not.toHaveBeenCalled(); + }); + + test("should continue session creation even if auto-update fails", async () => { + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoUpdate: true, + }, + }, + }); + mockUpdateUser.mockRejectedValue(new Error("Update failed")); + + const result = await processIDPCallback(defaultParams); + + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should return error when session creation fails", async () => { + mockCreateNewSessionFromIdpIntent.mockResolvedValue({ + error: "Session creation error", + }); + + const result = await processIDPCallback(defaultParams); + + expect(result.error).toBe("Session creation error"); + }); + + test("should return error when session creation returns neither redirect nor error", async () => { + mockCreateNewSessionFromIdpIntent.mockResolvedValue({}); + + const result = await processIDPCallback(defaultParams); + + expect(result.error).toBe("errors.sessionCreationFailed"); + }); + }); + + describe("CASE 2: Link IDP to existing user", () => { + const sessionId = "session123"; + const fingerprintValue = "fp123"; + let linkParams: typeof defaultParams & { sessionId: string }; + + beforeEach(() => { + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + linkParams = { + ...defaultParams, + sessionId, + flowFingerprint: createIdpFlowProof(fingerprintValue, sessionId), + }; + + mockGetBindingIdCookie.mockResolvedValue({ name: "bindingId", value: fingerprintValue }); + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + mockGetSessionCookieById.mockResolvedValue({ id: sessionId, token: "token123" }); + mockGetSession.mockResolvedValue({ + session: { + factors: { + user: { + id: "user123", + }, + }, + }, + }); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test.each([ + [ + "the legacy, client computable sha256(sessionId + fingerprint)", + () => + crypto + .createHash("sha256") + .update(sessionId + fingerprintValue) + .digest("hex"), + ], + ["a proof for another session", () => createIdpFlowProof(fingerprintValue, "other-session")], + ["a proof for another browser", () => createIdpFlowProof("other-fp", sessionId)], + ["a plain sign-in proof without the session", () => createIdpFlowProof(fingerprintValue)], + ])("should reject %s as flowFingerprint without touching the intent", async (_name, makeFlowFingerprint) => { + mockGetIDPByID.mockResolvedValue(defaultIdp); + + const result = await processIDPCallback({ ...linkParams, flowFingerprint: makeFlowFingerprint() }); + + expect(result.redirect).toBe("/idp/google/linking-failed?error=session_mismatch"); + expect(mockRetrieveIDPIntent).not.toHaveBeenCalled(); + expect(mockAddIDPLink).not.toHaveBeenCalled(); + }); + + test("should link IDP and create session when linking is allowed", async () => { + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isLinkingAllowed: true, + }, + }, + }); + + const result = await processIDPCallback(linkParams); + + expect(mockGetSessionCookieById).toHaveBeenCalledWith({ sessionId: "session123" }); + + expect(mockAddIDPLink).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + idp: { + id: "idp123", + userId: "user123", + userName: "testuser", + }, + userId: "user123", + }); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should return error redirect when linking is not allowed", async () => { + const result = await processIDPCallback(linkParams); + + expect(result.redirect).toContain("/idp/google/linking-failed"); + expect(result.redirect).toContain("error=linking_not_allowed"); + expect(mockAddIDPLink).not.toHaveBeenCalled(); + }); + + // Security regression: an "identify-only" session (login name submitted, no verified + // primary factor) must never drive linking, even when the IDP allows it and the browser + // fingerprint matches. Otherwise an unauthenticated attacker who only knows a victim's + // login name could bind their own external identity to the victim's account (ATO). + // + // These four cases run the real enrollment guard (getEnrollmentAuthorizationError); only + // its leaf dependencies (listAuthenticationMethodTypes, checkUserVerification) are mocked. + const linkingAllowedIdp = { + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isLinkingAllowed: true, + }, + }, + }; + + test("should reject linking for an identify-only session when the user already has credentials", async () => { + // Identify-only session (default) + user has a configured auth method → not authorized. + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockGetIDPByID.mockResolvedValue(linkingAllowedIdp); + + const result = await processIDPCallback(linkParams); + + expect(result.redirect).toContain("/idp/google/linking-failed"); + expect(result.redirect).toContain("error=session_invalid"); + expect(mockAddIDPLink).not.toHaveBeenCalled(); + }); + + test("should reject linking for an identify-only session with no credentials and no verification check", async () => { + // No auth methods yet, but the user-verification check has not been passed → not authorized. + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + mockCheckUserVerification.mockResolvedValue(false); + mockGetIDPByID.mockResolvedValue(linkingAllowedIdp); + + const result = await processIDPCallback(linkParams); + + expect(result.redirect).toContain("/idp/google/linking-failed"); + expect(result.redirect).toContain("error=session_invalid"); + expect(mockAddIDPLink).not.toHaveBeenCalled(); + }); + + test("should reject linking when the primary factor is expired", async () => { + // A password factor was verified, but the session has expired, so it no longer counts + // as a verified primary factor. Were it still valid, the guard would authorize at the + // primary-factor branch; expired, it falls through and the configured credential + // (PASSWORD) means it is not the credential-less onboarding path → rejected. + const past = { seconds: BigInt(Math.floor(Date.now() / 1000) - 3600), nanos: 0 }; + const factorVerifiedAt = { seconds: BigInt(Math.floor(Date.now() / 1000) - 7200), nanos: 0 }; + mockGetSession.mockResolvedValue({ + session: { + factors: { + user: { id: "user123" }, + password: { verifiedAt: factorVerifiedAt }, + }, + expirationDate: past, + }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockGetIDPByID.mockResolvedValue(linkingAllowedIdp); + + const result = await processIDPCallback(linkParams); + + expect(result.redirect).toContain("/idp/google/linking-failed"); + expect(result.redirect).toContain("error=session_invalid"); + expect(mockAddIDPLink).not.toHaveBeenCalled(); + }); + + test("should allow linking as the first authenticator when the user-verification check passed", async () => { + // Identify-only session, no auth methods yet, but the email/invite-code verification + // check passed → the legitimate "link an IDP as the first authenticator" onboarding path. + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + mockCheckUserVerification.mockResolvedValue(true); + mockGetIDPByID.mockResolvedValue(linkingAllowedIdp); + + const result = await processIDPCallback(linkParams); + + expect(mockAddIDPLink).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should allow linking when the session has a verified, non-expired primary factor", async () => { + // A fully authenticated session (verified password, not expired) is authorized at the + // primary-factor branch regardless of configured methods / verification check. This pins + // the other half of the guard's OR so a refactor cannot silently drop it. + const future = { seconds: BigInt(Math.floor(Date.now() / 1000) + 3600), nanos: 0 }; + mockGetSession.mockResolvedValue({ + session: { + factors: { + user: { id: "user123" }, + password: { verifiedAt: future }, + }, + expirationDate: future, + }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockCheckUserVerification.mockResolvedValue(false); + mockGetIDPByID.mockResolvedValue(linkingAllowedIdp); + + const result = await processIDPCallback(linkParams); + + expect(mockAddIDPLink).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should return error redirect when linking fails", async () => { + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isLinkingAllowed: true, + }, + }, + }); + mockAddIDPLink.mockRejectedValue(new Error("Linking failed")); + + const result = await processIDPCallback(linkParams); + + expect(result.redirect).toContain("/idp/google/linking-failed"); + }); + + test("should return error when session creation fails after linking", async () => { + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isLinkingAllowed: true, + }, + }, + }); + mockCreateNewSessionFromIdpIntent.mockResolvedValue({ + error: "Session error", + }); + + const result = await processIDPCallback(linkParams); + + expect(result.error).toBe("Session error"); + }); + }); + + describe("CASE 3: Auto-linking by email", () => { + beforeEach(() => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, // No existing userId + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + autoLinking: AutoLinkingOption.EMAIL, + isLinkingAllowed: true, + }, + }, + }); + }); + + test("should auto-link user by email and create session", async () => { + const foundUser = { + userId: "found123", + details: { + resourceOwner: "org123", + }, + }; + mockListUsers.mockResolvedValue({ + result: [foundUser], + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockListUsers).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + email: "test@example.com", + organizationId: "org123", + }); + expect(mockAddIDPLink).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + idp: { + id: "idp123", + userId: "user123", + userName: "testuser", + }, + userId: "found123", + }); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith({ + userId: "found123", + idpIntent: { + idpIntentId: "intent123", + idpIntentToken: "token123", + }, + requestId: "req123", + organization: "org123", + }); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should continue to next case when no user found by email", async () => { + mockListUsers.mockResolvedValue({ + result: [], + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockAddIDPLink).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/account-not-found"); + }); + + test("should return error redirect when auto-linking fails", async () => { + mockListUsers.mockResolvedValue({ + result: [{ userId: "found123" }], + }); + mockAddIDPLink.mockRejectedValue(new Error("Linking failed")); + + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/linking-failed"); + }); + }); + + describe("CASE 3: Auto-linking by username", () => { + beforeEach(() => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + autoLinking: AutoLinkingOption.USERNAME, + isLinkingAllowed: true, + }, + }, + }); + }); + + test("should auto-link user by username", async () => { + mockListUsers.mockResolvedValue({ + result: [ + { + userId: "found123", + details: { + resourceOwner: "org123", + }, + }, + ], + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockListUsers).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userName: "testuser", + organizationId: "org123", + }); + expect(mockAddIDPLink).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + }); + + describe("CASE 4: Auto-creation of user", () => { + beforeEach(() => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoCreation: true, + }, + }, + }); + }); + + test("should auto-create user and create session", async () => { + mockCreateUser.mockResolvedValue({ + id: "newuser123", + }); + + const result = await processIDPCallback(defaultParams); + + // Falls back to the deprecated add_human_user and maps it into the new CreateUser shape. + expect(mockCreateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + organizationId: "org123", + username: "testuser", + userType: expect.objectContaining({ + case: "human", + value: expect.objectContaining({ + profile: defaultIntent.addHumanUser.profile, + email: defaultIntent.addHumanUser.email, + }), + }), + }), + }); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith({ + userId: "newuser123", + idpIntent: { + idpIntentId: "intent123", + idpIntentToken: "token123", + }, + requestId: "req123", + organization: "org123", + }); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should auto-create user from the new create_user action including metadata", async () => { + const metadata = [{ key: "role", value: new Uint8Array([1, 2, 3]) }]; + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + // New user_action oneof: takes precedence over the deprecated add_human_user field. + addHumanUser: undefined, + updateHumanUser: undefined, + userAction: { + case: "createUser", + value: { + username: "testuser", + userType: { + case: "human", + value: { + profile: { givenName: "Test", familyName: "User" }, + email: { email: "test@example.com" }, + idpLinks: [{ idpId: "idp123", userId: "ext123", userName: "testuser" }], + }, + }, + metadata, + }, + }, + }); + mockCreateUser.mockResolvedValue({ id: "newuser123" }); + + const result = await processIDPCallback(defaultParams); + + // The action's request is passed through and only the resolved organization is injected. + expect(mockCreateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + organizationId: "org123", + username: "testuser", + userType: expect.objectContaining({ + case: "human", + value: expect.objectContaining({ + idpLinks: [{ idpId: "idp123", userId: "ext123", userName: "testuser" }], + }), + }), + metadata, + }), + }); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith(expect.objectContaining({ userId: "newuser123" })); + expect(result.redirect).toBe("https://app.example.com/success"); + }); + + test("should resolve organization from username domain", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + username: "user@example.com", + }, + }); + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "org-from-domain" }], + }); + mockGetLoginSettings.mockResolvedValue({ + allowDomainDiscovery: true, + }); + mockCreateUser.mockResolvedValue({ id: "newuser123" }); + + await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(mockGetOrgsByDomain).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + domain: "example.com", + }); + expect(mockCreateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + organizationId: "org-from-domain", + }), + }); + }); + + test("should fallback to default organization when not resolved", async () => { + mockGetDefaultOrg.mockResolvedValue({ id: "default-org" }); + mockCreateUser.mockResolvedValue({ id: "newuser123" }); + + await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(mockGetDefaultOrg).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + }); + expect(mockCreateUser).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + request: expect.objectContaining({ + organizationId: "default-org", + }), + }); + }); + + test("should return error when no organization context can be determined", async () => { + mockGetDefaultOrg.mockResolvedValue(null); + + const result = await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(mockGetDefaultOrg).toHaveBeenCalled(); + expect(mockCreateUser).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/failure"); + expect(result.redirect).toContain("error=no_organization_context"); + }); + + test("should return error redirect when user creation fails", async () => { + mockCreateUser.mockRejectedValue(new Error("Creation failed")); + + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/failure"); + expect(result.redirect).toContain("error=user_creation_failed"); + }); + + test("should return error when session creation fails after user creation", async () => { + mockCreateUser.mockResolvedValue({ id: "newuser123" }); + mockCreateNewSessionFromIdpIntent.mockResolvedValue({ + error: "Session error", + }); + + const result = await processIDPCallback(defaultParams); + + expect(result.error).toBe("Session error"); + }); + + test("should redirect to complete registration when givenName is missing", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + profile: { + givenName: "", + familyName: "User", + displayName: "User", + }, + }, + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockCreateUser).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("id=intent123"); + expect(result.redirect).toContain("token=token123"); + expect(result.redirect).toContain("organization=org123"); + expect(result.redirect).toContain("familyName=User"); + const params = new URLSearchParams(result.redirect!.split("?")[1]); + expect(params.get("flowFingerprint")).toBe(defaultParams.flowFingerprint); + }); + + test("should redirect to complete registration when familyName is missing", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + profile: { + givenName: "Test", + familyName: "", + displayName: "Test", + }, + }, + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockCreateUser).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("id=intent123"); + expect(result.redirect).toContain("token=token123"); + expect(result.redirect).toContain("organization=org123"); + expect(result.redirect).toContain("givenName=Test"); + }); + + test("should redirect to complete registration when both givenName and familyName are missing", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + profile: { + givenName: "", + familyName: "", + displayName: "", + }, + }, + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockCreateUser).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("id=intent123"); + expect(result.redirect).toContain("token=token123"); + expect(result.redirect).toContain("organization=org123"); + }); + + test("should redirect to complete registration when profile is undefined", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + profile: undefined, + }, + }); + + const result = await processIDPCallback(defaultParams); + + expect(mockCreateUser).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("id=intent123"); + expect(result.redirect).toContain("token=token123"); + }); + + test("should use fallback organization when required fields missing and no org provided", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + profile: { + givenName: "", + familyName: "User", + displayName: "User", + }, + }, + }); + mockGetDefaultOrg.mockResolvedValue({ id: "default-org" }); + + const result = await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(mockGetDefaultOrg).toHaveBeenCalled(); + expect(mockCreateUser).not.toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("organization=default-org"); + }); + }); + + describe("CASE 5: Manual user creation allowed", () => { + beforeEach(() => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isCreationAllowed: true, + }, + }, + }); + }); + + test("should redirect to complete registration page with user data", async () => { + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("id=intent123"); + expect(result.redirect).toContain("token=token123"); + expect(result.redirect).toContain("requestId=req123"); + expect(result.redirect).toContain("organization=org123"); + expect(result.redirect).toContain("idpId=idp123"); + expect(result.redirect).toContain("idpUserId=user123"); + expect(result.redirect).toContain("idpUserName=testuser"); + expect(result.redirect).toContain("givenName=Test"); + expect(result.redirect).toContain("familyName=User"); + expect(result.redirect).toContain("email=test%40example.com"); + // the complete-registration form must stay bound to this browser + const params = new URLSearchParams(result.redirect!.split("?")[1]); + expect(params.get("flowFingerprint")).toBe(defaultParams.flowFingerprint); + }); + + test("should fallback to default organization for registration", async () => { + mockGetDefaultOrg.mockResolvedValue({ id: "default-org" }); + + const result = await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(mockGetDefaultOrg).toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/complete-registration"); + expect(result.redirect).toContain("organization=default-org"); + }); + + test("should redirect to registration failed when no organization context available", async () => { + mockGetDefaultOrg.mockResolvedValue(null); + + const result = await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(mockGetDefaultOrg).toHaveBeenCalled(); + expect(result.redirect).toContain("/idp/google/registration-failed"); + expect(result.redirect).toContain("id=intent123"); + }); + + test("should resolve organization from domain for registration", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + addHumanUser: { + ...defaultIntent.addHumanUser, + username: "user@example.com", + }, + }); + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "org-from-domain" }], + }); + mockGetLoginSettings.mockResolvedValue({ + allowDomainDiscovery: true, + }); + + const result = await processIDPCallback({ + ...defaultParams, + organization: undefined, + }); + + expect(result.redirect).toContain("organization=org-from-domain"); + }); + }); + + describe("CASE 6: No user found and creation not allowed", () => { + beforeEach(() => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + }); + + test("should redirect to account not found page", async () => { + const result = await processIDPCallback(defaultParams); + + expect(result.redirect).toContain("/idp/google/account-not-found"); + expect(result.redirect).toContain("id=intent123"); + expect(result.redirect).toContain("requestId=req123"); + expect(result.redirect).toContain("organization=org123"); + }); + }); + + describe("Priority of cases", () => { + test("should prioritize existing user sign-in over auto-linking", async () => { + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + autoLinking: AutoLinkingOption.EMAIL, + }, + }, + }); + + await processIDPCallback(defaultParams); + + // Should not search for users when userId already exists + expect(mockListUsers).not.toHaveBeenCalled(); + expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith( + expect.objectContaining({ + userId: "user123", + }), + ); + }); + + test("should prioritize auto-linking over auto-creation", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + autoLinking: AutoLinkingOption.EMAIL, + isLinkingAllowed: true, + isAutoCreation: true, + }, + }, + }); + mockListUsers.mockResolvedValue({ + result: [ + { + userId: "found123", + details: { + resourceOwner: "org123", + }, + }, + ], + }); + + await processIDPCallback(defaultParams); + + // Should link, not create + expect(mockAddIDPLink).toHaveBeenCalled(); + expect(mockCreateUser).not.toHaveBeenCalled(); + }); + + test("should prioritize auto-creation over manual creation", async () => { + mockRetrieveIDPIntent.mockResolvedValue({ + ...defaultIntent, + userId: undefined, + }); + mockGetIDPByID.mockResolvedValue({ + ...defaultIdp, + config: { + options: { + ...defaultIdp.config.options, + isAutoCreation: true, + isCreationAllowed: true, + }, + }, + }); + mockCreateUser.mockResolvedValue({ id: "newuser123" }); + + const result = await processIDPCallback(defaultParams); + + // Should auto-create, not redirect to manual form + expect(mockCreateUser).toHaveBeenCalled(); + expect(result.redirect).toBe("https://app.example.com/success"); + expect(result.redirect).not.toContain("complete-registration"); + }); + }); + + describe("postErrorRedirectUrl handling", () => { + test("should preserve postErrorRedirectUrl in all redirects", async () => { + const paramsWithError = { + ...defaultParams, + postErrorRedirectUrl: "https://app.example.com/error", + }; + + mockRetrieveIDPIntent.mockRejectedValue(new Error("Test error")); + + const result = await processIDPCallback(paramsWithError); + + expect(result.redirect).toContain("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror"); + }); + }); +}); + +describe("validateIDPLinkingPermissions", () => { + let mockGetLoginSettings: any; + let mockGetActiveIdentityProviders: any; + let validateIDPLinkingPermissions: any; + + beforeEach(async () => { + vi.resetAllMocks(); + + // Import mocked modules + const { getLoginSettings, getActiveIdentityProviders } = await import("@/lib/server/zitadel"); + const { validateIDPLinkingPermissions: validate } = await import("@/lib/server/idp-linking"); + + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockGetActiveIdentityProviders = vi.mocked(getActiveIdentityProviders); + validateIDPLinkingPermissions = validate; + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("Organization login settings validation", () => { + test("should return false when allowExternalIdp is false", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: false, + }); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + expect(mockGetLoginSettings).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + organization: "org123", + }); + expect(mockGetActiveIdentityProviders).not.toHaveBeenCalled(); + }); + + test("should return false when login settings are undefined", async () => { + mockGetLoginSettings.mockResolvedValue(undefined); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + }); + + test("should return false when allowExternalIdp is missing", async () => { + mockGetLoginSettings.mockResolvedValue({}); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + }); + }); + + describe("Active IDP validation", () => { + test("should return false when IDP is not in active list", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [ + { id: "idp456", name: "Other IDP" }, + { id: "idp789", name: "Another IDP" }, + ], + }); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + orgId: "org123", + linking_allowed: true, + }); + }); + + test("should return false when identityProviders list is empty", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [], + }); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + }); + + test("should return false when identityProviders is undefined", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({}); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + }); + }); + + describe("Successful validation", () => { + test("should return true when all validations pass", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [ + { id: "idp123", name: "Target IDP" }, + { id: "idp456", name: "Other IDP" }, + ], + }); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(true); + expect(mockGetLoginSettings).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + organization: "org123", + }); + expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + orgId: "org123", + linking_allowed: true, + }); + }); + + test("should find IDP in middle of list", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [ + { id: "idp111", name: "IDP 1" }, + { id: "idp222", name: "IDP 2" }, + { id: "idp123", name: "Target IDP" }, + { id: "idp333", name: "IDP 3" }, + ], + }); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(true); + }); + }); + + describe("Edge cases", () => { + test("should handle getLoginSettings throwing an error", async () => { + mockGetLoginSettings.mockRejectedValue(new Error("Network error")); + + await expect( + validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }), + ).rejects.toThrow("Network error"); + }); + + test("should handle getActiveIdentityProviders throwing an error", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockRejectedValue(new Error("Network error")); + + await expect( + validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }), + ).rejects.toThrow("Network error"); + }); + + test("should perform case-sensitive IDP ID comparison", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowExternalIdp: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "IDP123", name: "Target IDP" }], + }); + + const result = await validateIDPLinkingPermissions({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userOrganizationId: "org123", + idpId: "idp123", + }); + + expect(result).toBe(false); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/idp-intent.ts b/auth/ui/v2/apps/login/src/lib/actions/idp-intent.ts new file mode 100644 index 0000000..bd84536 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/idp-intent.ts @@ -0,0 +1,891 @@ +"use server"; + +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { getBindingIdCookie } from "@/lib/server/fingerprint"; +import { isClassifiedError } from "@/lib/server/grpc/interceptors/error-classification"; +import { isIdpFlowProofValid } from "@/lib/server/idp-flow-proof"; +import { validateIDPLinkingPermissions } from "@/lib/server/idp-linking"; +import { createNewSessionFromIdpIntent } from "@/lib/server/idp-session"; +import { syncInstanceRolesFromIdpIntent } from "@/lib/server/instance-roles"; +import { createLogger } from "@/lib/server/logger"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { + addIDPLink, + createUser, + getDefaultOrg, + getIDPByID, + getLoginSettings, + getOrgsByDomain, + getSession, + getUserByID, + listUsers, + retrieveIDPIntent, + ServiceConfig, + updateUser, +} from "@/lib/server/zitadel"; +import { Code, create } from "@zitadel/client"; +import { AutoLinkingOption } from "@zitadel/proto/zitadel/idp/v2/idp_pb"; +import { SetHumanEmail } from "@zitadel/proto/zitadel/user/v2/email_pb"; +import { SetHumanProfile } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { + CreateUserRequest, + CreateUserRequestSchema, + UpdateUserRequest, + UpdateUserRequestSchema, +} from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +const logger = createLogger("idp-intent"); + +const ORG_SUFFIX_REGEX = /(?<=@)(.+)/; + +type IDPIntentResult = Awaited>; + +/** + * Flattened view of the "create user" information contained in an IDP intent response, + * used for reads (organization resolution, required-field checks and form pre-filling). + */ +interface ResolvedCreateUser { + username?: string; + profile?: SetHumanProfile; + email?: SetHumanEmail; +} + +/** + * Reads the "create user" information from an IDP intent response. + * + * Prefers the new `user_action.create_user` oneof (CreateUserRequest, which supports metadata). + * Falls back to the deprecated `add_human_user` field so that responses from older API versions + * keep working during the transition. + */ +function resolveCreateUser(intent: IDPIntentResult): ResolvedCreateUser | undefined { + if (intent.userAction?.case === "createUser") { + const request = intent.userAction.value; + const human = request.userType?.case === "human" ? request.userType.value : undefined; + return { + username: request.username, + profile: human?.profile, + email: human?.email, + }; + } + + // Fallback: deprecated add_human_user (does not support the new top-level metadata). + if (intent.addHumanUser) { + return { + username: intent.addHumanUser.username, + profile: intent.addHumanUser.profile, + email: intent.addHumanUser.email, + }; + } + + return undefined; +} + +/** + * Builds the request for the non-deprecated CreateUser endpoint from an IDP intent response. + * + * Prefers the new `user_action.create_user` oneof: the action's request is passed through as-is + * and only the resolved organization is injected. Falls back to mapping the deprecated + * `add_human_user` (flat) fields into the new nested shape for older API responses. + */ +function buildCreateUserRequest(intent: IDPIntentResult, organizationId: string): CreateUserRequest | undefined { + if (intent.userAction?.case === "createUser") { + return create(CreateUserRequestSchema, { + ...intent.userAction.value, + organizationId, + }); + } + + // Fallback: map the deprecated flat add_human_user payload into the CreateUserRequest shape. + if (intent.addHumanUser) { + const add = intent.addHumanUser; + return create(CreateUserRequestSchema, { + organizationId, + username: add.username, + userType: { + case: "human", + value: { + profile: add.profile, + email: add.email, + phone: add.phone, + idpLinks: add.idpLinks, + }, + }, + // SetMetadataEntry and Metadata share the same {key, value} shape; map explicitly. + metadata: add.metadata?.map((entry) => ({ key: entry.key, value: entry.value })), + }); + } + + return undefined; +} + +/** + * Builds the request for the non-deprecated UpdateUser endpoint from an IDP intent response. + * + * Prefers the new `user_action.update_user` oneof (UpdateUserRequest, which supports metadata). + * Falls back to the deprecated `update_human_user` field for older API responses. + * + * Note: we intentionally sync only profile, email, phone and metadata here (not the username) to + * preserve the existing auto-update behaviour and avoid invalidating sessions on every login. + */ +function buildUpdateUserRequest(intent: IDPIntentResult, userId: string): UpdateUserRequest | undefined { + if (intent.userAction?.case === "updateUser") { + const request = intent.userAction.value; + // UpdateUserRequest.user_type is optional and also supports machine updates. Only sync a + // human profile (IDP users are human); for any other case we still carry the metadata over, + // since metadata is a top-level field independent of the user type. + const human = request.userType?.case === "human" ? request.userType.value : undefined; + + // Nothing to apply: neither human profile data nor metadata. Skip the update entirely. + if (!human && (request.metadata?.length ?? 0) === 0) { + return undefined; + } + + return create(UpdateUserRequestSchema, { + userId, + userType: human + ? { + case: "human", + value: { + profile: human.profile, + email: human.email, + phone: human.phone, + }, + } + : undefined, + metadata: request.metadata, + }); + } + + // Fallback: deprecated update_human_user (has no metadata support). + if (intent.updateHumanUser) { + const update = intent.updateHumanUser; + return create(UpdateUserRequestSchema, { + userId, + userType: { + case: "human", + value: { + // The deprecated profile is a SetHumanProfile; map it to the Update profile shape. + profile: update.profile + ? { + givenName: update.profile.givenName, + familyName: update.profile.familyName, + nickName: update.profile.nickName, + displayName: update.profile.displayName, + preferredLanguage: update.profile.preferredLanguage, + gender: update.profile.gender, + } + : undefined, + email: update.email, + phone: update.phone, + }, + }, + }); + } + + return undefined; +} + +async function resolveOrganizationForUser({ + organization, + createUserData, + serviceConfig, +}: { + organization?: string; + createUserData?: ResolvedCreateUser; + serviceConfig: ServiceConfig; +}): Promise { + if (organization) return organization; + + if (createUserData?.username && ORG_SUFFIX_REGEX.test(createUserData.username)) { + const matched = ORG_SUFFIX_REGEX.exec(createUserData.username); + const suffix = matched?.[1] ?? ""; + + const orgs = await getOrgsByDomain({ serviceConfig, domain: suffix }); + const orgToCheckForDiscovery = orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined; + + if (orgToCheckForDiscovery) { + const orgLoginSettings = await getLoginSettings({ serviceConfig, organization: orgToCheckForDiscovery }); + if (orgLoginSettings?.allowDomainDiscovery) { + return orgToCheckForDiscovery; + } + } + } + + // Fallback to default organization if no org was resolved through discovery + const defaultOrg = await getDefaultOrg({ serviceConfig }); + return defaultOrg?.id; +} + +type IDPConfig = Awaited>; + +interface IDPHandlerContext { + serviceConfig: ServiceConfig; + t: (key: string) => string; + intent: IDPIntentResult; + idp: NonNullable; + options: NonNullable["config"]>["options"]; + params: { + provider: string; + id: string; + token: string; + requestId?: string; + organization?: string; + postErrorRedirectUrl?: string; + sessionId?: string; + }; + buildRedirectParams: (additionalParams?: Record, includeToken?: boolean) => string; +} + +type IDPHandlerResult = { + redirect?: string; + error?: string; + samlData?: { url: string; fields: Record }; +} | null; + +/** + * CASE 1: Explicit Linking (via sessionId) + * This happens when a logged-in user initiates an IDP flow to link it to their account. + */ +async function resolveUserIdFromSession({ + sessionId, + serviceConfig, + provider, +}: { + sessionId: string; + serviceConfig: ServiceConfig; + provider: string; +}) { + try { + const sessionCookie = await getSessionCookieById({ sessionId }); + if (!sessionCookie) { + logger.warn("Session for linking not found or invalid"); + return { redirect: `/idp/${provider}/linking-failed?error=session_invalid` }; + } + + const sessionResp = await getSession({ + serviceConfig, + sessionId: sessionCookie.id, + sessionToken: sessionCookie.token, + }); + const session = sessionResp.session; + + if (!session?.factors?.user?.id) { + logger.warn("Session found but no userId associated for linking"); + return { redirect: `/idp/${provider}/linking-failed?error=session_invalid` }; + } + + // Explicit linking must be authorized the same way credential enrollment is. An + // "identify-only" session — produced by only submitting a login name, with no verified + // primary factor (password / passkey / IDP intent) — must NOT be trusted on its own: + // otherwise an unauthenticated attacker who merely knows a victim's login name could bind + // their own external identity to the victim's account (account takeover). The flowFingerprint + // checked at the entry of processIDPCallback only proves the link request originated from + // the same browser that started the flow, not that the session was ever authenticated. + // + // getEnrollmentAuthorizationError authorizes when the session has a verified, non-expired + // primary factor, OR the user has no authentication methods yet AND passed a + // user-verification check (the email/invite-code proof bound to this browser's + // binding id). The latter preserves the legitimate "link an IDP as the first + // authenticator" onboarding flow, which isSessionValid would have rejected. + const enrollmentError = await getEnrollmentAuthorizationError({ + serviceConfig, + session, + userId: session.factors.user.id, + }); + if (enrollmentError) { + logger.warn("Session for linking is not authorized", { enrollmentError }); + return { redirect: `/idp/${provider}/linking-failed?error=session_invalid` }; + } + + return { userId: session.factors.user.id }; + } catch (error) { + logger.warn("Error retrieving session for linking", { error }); + return { redirect: `/idp/${provider}/linking-failed?error=session_invalid` }; + } +} + +async function handleExplicitLinking(ctx: IDPHandlerContext): Promise { + const { sessionId, provider } = ctx.params; + const { userId } = ctx.intent; + const { options, serviceConfig, intent, t, buildRedirectParams } = ctx; + + if (sessionId && !userId) { + // Intent should not have a userId if it is a linking intent + // 1. The flowFingerprint checked at the entry of processIDPCallback is bound to this sessionId and browser + // 2. Retrieve Session & Resolve User + const { userId: resolvedUserId, redirect: sessionRedirect } = await resolveUserIdFromSession({ + sessionId, + serviceConfig, + provider, + }); + + if (sessionRedirect || !resolvedUserId) { + return { redirect: sessionRedirect || `/idp/${provider}/linking-failed?error=session_invalid` }; + } + + logger.debug("Resolved userId from session link", { userId: resolvedUserId }); + + // 3. Perform Linking Logic + if (!options?.isLinkingAllowed) { + logger.error("Linking not allowed by IDP configuration"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/linking-failed?${params}&error=linking_not_allowed` }; + } + + try { + const targetUser = await getUserByID({ serviceConfig, userId: resolvedUserId }); + + if (!targetUser || !targetUser.details?.resourceOwner) { + logger.error("User not found or missing organization"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/linking-failed?${params}&error=user_not_found` }; + } + + const isAllowed = await validateIDPLinkingPermissions({ + serviceConfig, + userOrganizationId: targetUser.details.resourceOwner, + idpId: intent.idpInformation!.idpId, + }); + + if (!isAllowed) { + logger.error("IDP linking validation failed"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/linking-failed?${params}&error=validation_failed` }; + } + + await addIDPLink({ + serviceConfig, + idp: { + id: intent.idpInformation!.idpId, + userId: intent.idpInformation!.userId, + userName: intent.idpInformation!.userName, + }, + userId: resolvedUserId, + }); + logger.info("IDP linked successfully, creating session"); + + const sessionResult = await createNewSessionFromIdpIntent({ + userId: resolvedUserId, + idpIntent: { + idpIntentId: ctx.params.id, + idpIntentToken: ctx.params.token, + }, + requestId: ctx.params.requestId, + organization: ctx.params.organization, + }); + + if ("error" in sessionResult && sessionResult.error) { + logger.error("Error creating session", { error: sessionResult.error }); + return { error: sessionResult.error }; + } + + if ("redirect" in sessionResult && sessionResult.redirect) { + logger.debug("Session created, redirecting", { redirect: sessionResult.redirect }); + return { redirect: sessionResult.redirect }; + } + + if ("samlData" in sessionResult && sessionResult.samlData) { + logger.info("Session created, returning samlData"); + return { samlData: sessionResult.samlData }; + } + + return { error: t("errors.sessionCreationFailed") }; + } catch (error) { + logger.error("Error linking IDP", { error }); + const errorMessage = error instanceof Error ? error.message : t("errors.unknownError"); + let params = buildRedirectParams({ error: errorMessage }); + if (isClassifiedError(error) && error.code === Code.AlreadyExists) { + params = buildRedirectParams({ error: "external_idp_taken" }); + } + return { redirect: `/idp/${provider}/linking-failed?${params}` }; + } + } + + return null; +} + +/** + * CASE 2: User exists and should sign in + */ +async function handleUserExists(ctx: IDPHandlerContext): Promise { + const { sessionId } = ctx.params; + const { userId } = ctx.intent; + const { options, serviceConfig, t } = ctx; + + if (userId && !sessionId) { + // Auto-update user if enabled. Uses the non-deprecated UpdateUser endpoint so that + // metadata provided by the action response is applied in the same request. + const updateUserRequest = options?.isAutoUpdate ? buildUpdateUserRequest(ctx.intent, userId) : undefined; + if (updateUserRequest) { + try { + logger.debug("Auto-updating user profile"); + await updateUser({ serviceConfig, request: updateUserRequest }); + } catch (error) { + logger.warn("Failed to auto-update user", { error }); + // Continue with login even if update fails + } + } + + // Synchronize instance member roles for ZITADEL IdPs with instanceRolesInfo + // configured (e.g. support access). Merge-only and never blocks the login. + await syncInstanceRolesFromIdpIntent({ serviceConfig, intent: ctx.intent, userId }); + + // Create session and handle redirect + logger.debug("Creating session for existing user"); + const sessionResult = await createNewSessionFromIdpIntent({ + userId, + idpIntent: { + idpIntentId: ctx.params.id, + idpIntentToken: ctx.params.token, + }, + requestId: ctx.params.requestId, + organization: ctx.params.organization, + }); + + if ("error" in sessionResult && sessionResult.error) { + logger.error("Error creating session", { error: sessionResult.error }); + return { error: sessionResult.error }; + } + + if ("redirect" in sessionResult && sessionResult.redirect) { + logger.debug("Session created, redirecting", { redirect: sessionResult.redirect }); + return { redirect: sessionResult.redirect }; + } + + if ("samlData" in sessionResult && sessionResult.samlData) { + logger.info("Session created, returning samlData"); + return { samlData: sessionResult.samlData }; + } + + return { error: t("errors.sessionCreationFailed") }; + } + + return null; +} + +/** + * CASE 3: Auto-linking (search for user and link) + */ +async function handleAutoLinking(ctx: IDPHandlerContext): Promise { + const { options, intent, serviceConfig, buildRedirectParams, t } = ctx; + const { idpInformation } = intent; + const createUserData = resolveCreateUser(intent); + const { organization, provider } = ctx.params; + + if (options?.autoLinking) { + let foundUser; + const email = createUserData?.email?.email; + const emailVerified = + createUserData?.email?.verification?.case === "isVerified" && createUserData?.email?.verification?.value; + + // The lookups below are case insensitive, so they can return several users when case variants + // of the same address or username exist. Linking a verified IDP identity to an arbitrary one of + // them would be an account takeover, so only link when the match is unambiguous. Falling through + // with `null` leaves the user on the regular linking/creation flow. + const onlyMatch = (response: { result?: T[] }): T | null => { + if (!response.result?.length) { + return null; + } + + if (response.result.length > 1) { + logger.warn("Auto-linking skipped: user lookup was ambiguous", { matches: response.result.length }); + return null; + } + + return response.result[0]; + }; + + if (options.autoLinking === AutoLinkingOption.EMAIL && email && emailVerified) { + foundUser = await listUsers({ serviceConfig, email, organizationId: organization }).then(onlyMatch); + } else if (options.autoLinking === AutoLinkingOption.USERNAME) { + foundUser = await listUsers({ + serviceConfig, + userName: idpInformation!.userName, + organizationId: organization, + }).then(onlyMatch); + } + + if (foundUser) { + try { + if (!foundUser.details?.resourceOwner) { + logger.error("Found user missing organization information"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/linking-failed?${params}&error=missing_organization` }; + } + + // Validate IDP linking permissions + const isAllowed = await validateIDPLinkingPermissions({ + serviceConfig, + userOrganizationId: foundUser.details.resourceOwner, + idpId: idpInformation!.idpId, + }); + + if (!isAllowed) { + logger.error("Auto-linking validation failed"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/linking-failed?${params}&error=validation_failed` }; + } + + await addIDPLink({ + serviceConfig, + idp: { + id: idpInformation!.idpId, + userId: idpInformation!.userId, + userName: idpInformation!.userName, + }, + userId: foundUser.userId, + }); + logger.info("User auto-linked successfully, creating session"); + + // Synchronize instance member roles for ZITADEL IdPs with instanceRolesInfo + // configured (e.g. support access). Merge-only and never blocks the login. + // Required here as well: a user that is auto-linked on this login would + // otherwise only receive its roles on the next one (via the existing-user path). + await syncInstanceRolesFromIdpIntent({ serviceConfig, intent, userId: foundUser.userId }); + + // Create session after auto-linking + const sessionResult = await createNewSessionFromIdpIntent({ + userId: foundUser.userId, + idpIntent: { + idpIntentId: ctx.params.id, + idpIntentToken: ctx.params.token, + }, + requestId: ctx.params.requestId, + organization: ctx.params.organization, + }); + + if ("error" in sessionResult && sessionResult.error) { + logger.error("Error creating session", { error: sessionResult.error }); + return { error: sessionResult.error }; + } + + if ("redirect" in sessionResult && sessionResult.redirect) { + logger.debug("Session created, redirecting", { redirect: sessionResult.redirect }); + return { redirect: sessionResult.redirect }; + } + + if ("samlData" in sessionResult && sessionResult.samlData) { + logger.info("Session created, returning samlData"); + return { samlData: sessionResult.samlData }; + } + + return { error: t("errors.sessionCreationFailed") }; + } catch (error) { + logger.error("Error auto-linking user", { error }); + const errorMessage = error instanceof Error ? error.message : t("errors.unknownError"); + const params = buildRedirectParams({ error: errorMessage }); + return { redirect: `/idp/${provider}/linking-failed?${params}` }; + } + } + } + + return null; +} + +/** + * CASE 4: Auto-creation of user + */ +async function handleAutoCreation(ctx: IDPHandlerContext): Promise { + const { options, intent, serviceConfig, buildRedirectParams, t } = ctx; + const { idpInformation } = intent; + const createUserData = resolveCreateUser(intent); + const { organization, provider } = ctx.params; + + if (options?.isAutoCreation && createUserData) { + const orgToRegisterOn = await resolveOrganizationForUser({ + organization, + createUserData, + serviceConfig, + }); + + if (!orgToRegisterOn) { + logger.error("Could not determine organization for auto-creation (no default org available)"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/failure?${params}&error=no_organization_context` }; + } + + // Check if required profile fields are present + if (!createUserData.profile?.givenName || !createUserData.profile?.familyName) { + logger.info("Missing required profile fields (givenName or familyName), redirecting to complete registration"); + + if (!idpInformation!.userId) { + logger.error("IDP intent missing userId, cannot redirect to complete registration"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/failure?${params}&error=missing_idp_user_info` }; + } + + const params = buildRedirectParams( + { + organization: orgToRegisterOn, + idpId: idpInformation!.idpId, + idpUserId: idpInformation!.userId, + idpUserName: idpInformation!.userName || "", + // User data for pre-filling form + givenName: createUserData.profile?.givenName || "", + familyName: createUserData.profile?.familyName || "", + email: createUserData.email?.email || "", + }, + true, + ); + return { redirect: `/idp/${provider}/complete-registration?${params}` }; + } + + const createUserRequest = buildCreateUserRequest(intent, orgToRegisterOn); + + if (!createUserRequest) { + logger.error("Could not build create user request from intent"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/failure?${params}&error=user_creation_failed` }; + } + + try { + const newUser = await createUser({ serviceConfig, request: createUserRequest }); + logger.info("User auto-created successfully, creating session"); + + // Synchronize instance member roles for ZITADEL IdPs with instanceRolesInfo + // configured (e.g. support access). Merge-only and never blocks the login. + await syncInstanceRolesFromIdpIntent({ serviceConfig, intent, userId: newUser.id }); + + // Create session for newly created user + const sessionResult = await createNewSessionFromIdpIntent({ + userId: newUser.id, + idpIntent: { + idpIntentId: ctx.params.id, + idpIntentToken: ctx.params.token, + }, + requestId: ctx.params.requestId, + organization: ctx.params.organization, + }); + + if ("error" in sessionResult && sessionResult.error) { + logger.error("Error creating session", { error: sessionResult.error }); + return { error: sessionResult.error }; + } + + if ("redirect" in sessionResult && sessionResult.redirect) { + logger.debug("Session created, redirecting", { redirect: sessionResult.redirect }); + return { redirect: sessionResult.redirect }; + } + + if ("samlData" in sessionResult && sessionResult.samlData) { + logger.info("Session created, returning samlData"); + return { samlData: sessionResult.samlData }; + } + + return { error: t("errors.sessionCreationFailed") }; + } catch (error: unknown) { + logger.error("Error auto-creating user", { error }); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/failure?${params}&error=user_creation_failed` }; + } + } + + return null; +} + +/** + * CASE 5: Manual user creation allowed + */ +async function handleManualCreation(ctx: IDPHandlerContext): Promise { + const { options, intent, serviceConfig, buildRedirectParams } = ctx; + const { idpInformation } = intent; + const createUserData = resolveCreateUser(intent); + const { organization, provider } = ctx.params; + + if (options?.isCreationAllowed && createUserData) { + const orgToRegisterOn = await resolveOrganizationForUser({ + organization, + createUserData, + serviceConfig, + }); + + if (!orgToRegisterOn) { + logger.error("Could not determine organization for registration (no default org available)"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/registration-failed?${params}` }; + } + + // Store user data for manual registration form + // Note: includeToken=true because the session hasn't been created yet + // The token will be needed when registerUserAndLinkToIDP creates the session + if (!idpInformation!.userId) { + logger.error("IDP intent missing userId, cannot redirect to complete registration"); + const params = buildRedirectParams(); + return { redirect: `/idp/${provider}/failure?${params}&error=missing_idp_user_info` }; + } + + const params = buildRedirectParams( + { + organization: orgToRegisterOn, + idpId: idpInformation!.idpId, + idpUserId: idpInformation!.userId, + idpUserName: idpInformation!.userName || "", + // User data for pre-filling form + givenName: createUserData.profile?.givenName || "", + familyName: createUserData.profile?.familyName || "", + email: createUserData.email?.email || "", + }, + true, + ); // includeToken=true + return { redirect: `/idp/${provider}/complete-registration?${params}` }; + } + + return null; +} + +/** + * CASE 6: No user found and creation not allowed + */ +async function handleNoUserFound(ctx: IDPHandlerContext): Promise { + const { buildRedirectParams } = ctx; + logger.debug("No matching user and creation not allowed"); + const params = buildRedirectParams(); + return { redirect: `/idp/${ctx.params.provider}/account-not-found?${params}` }; +} + +/** + * Server action to process IDP callback and handle ALL business logic. + * This action: + * 1. Consumes the single-use token once + * 2. Performs all IDP-related operations (auto-update, auto-linking, auto-creation) + * 3. Returns redirect URL or error for client-side navigation + */ +export async function processIDPCallback({ + provider, + id, + token, + requestId, + organization, + postErrorRedirectUrl, + sessionId, + flowFingerprint, +}: { + provider: string; + id: string; + token: string; + requestId?: string; + organization?: string; + postErrorRedirectUrl?: string; + sessionId?: string; + flowFingerprint?: string; +}): Promise<{ redirect?: string; error?: string; samlData?: { url: string; fields: Record } }> { + // ... (headers and config retrieval) ... + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const t = await getTranslations("idp"); + + const errorParams = new URLSearchParams(); + if (requestId) errorParams.set("requestId", requestId); + if (organization) errorParams.set("organization", organization); + if (postErrorRedirectUrl) errorParams.set("postErrorRedirectUrl", postErrorRedirectUrl); + + // Validate required parameters + if (!provider || !id || !token) { + logger.error("Missing required parameters", { provider, id, hasToken: !!token }); + return { redirect: `/idp/${provider}/failure?${errorParams.toString()}` }; + } + + // Security Check: the flow must have been started in this browser (login CSRF) and, when linking, for this session + const bindingIdCookie = await getBindingIdCookie(); + if (!isIdpFlowProofValid(flowFingerprint, bindingIdCookie?.value, sessionId)) { + logger.warn("IDP flow fingerprint missing or mismatch"); + if (sessionId) { + return { redirect: `/idp/${provider}/linking-failed?error=session_mismatch` }; + } + errorParams.set("error", "flow_mismatch"); + return { redirect: `/idp/${provider}/failure?${errorParams.toString()}` }; + } + + try { + // Consume the single-use token ONCE + const intent = await retrieveIDPIntent({ serviceConfig, id, token }); + + logger.debug("Intent retrieved successfully, processing business logic"); + + const { idpInformation } = intent; + + // Verify we have IDP info early on + if (!idpInformation) { + logger.error("IDP information missing"); + errorParams.set("error", "missing_idp_info"); + return { redirect: `/idp/${provider}/failure?${errorParams.toString()}` }; + } + + // Get IDP configuration + const idp = await getIDPByID({ serviceConfig, id: idpInformation.idpId }); + + if (!idp) { + return { error: t("errors.idpNotFound") }; + } + + const options = idp?.config?.options; + + // Build base redirect params + const buildRedirectParams = (additionalParams?: Record, includeToken: boolean = false) => { + const params = new URLSearchParams(); + params.set("id", id); + if (includeToken) params.set("token", token); + // the token lets the complete-registration form consume the intent, so keep it bound to this browser + if (includeToken && flowFingerprint) params.set("flowFingerprint", flowFingerprint); + if (requestId) params.set("requestId", requestId); + if (organization) params.set("organization", organization); + if (postErrorRedirectUrl) params.set("postErrorRedirectUrl", postErrorRedirectUrl); + if (sessionId) params.set("linkToSessionId", sessionId); // Include sessionId in redirects + + if (additionalParams) { + Object.entries(additionalParams).forEach(([key, value]) => { + if (value) params.set(key, value); + }); + } + + return params.toString(); + }; + + const ctx: IDPHandlerContext = { + serviceConfig, + t, + intent, + idp, + options, + params: { + provider, + id, + token, + requestId, + organization, + postErrorRedirectUrl, + sessionId, + }, + buildRedirectParams, + }; + + const handlers = [ + handleExplicitLinking, + handleUserExists, + handleAutoLinking, + handleAutoCreation, + handleManualCreation, + handleNoUserFound, + ]; + + for (const handler of handlers) { + const result = await handler(ctx); + if (result) { + return result; + } + } + + // Should theoretically be unreachable if handleNoUserFound covers the rest + return { error: t("errors.unknown") }; + } catch (error: unknown) { + logger.error("Error processing intent", { error }); + + errorParams.set("error", error instanceof Error ? error.message : t("errors.unknownError")); + + return { redirect: `/idp/${provider}/failure?${errorParams.toString()}` }; + } +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/idp.test.ts b/auth/ui/v2/apps/login/src/lib/actions/idp.test.ts new file mode 100644 index 0000000..b593a3c --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/idp.test.ts @@ -0,0 +1,490 @@ +import { createNewSessionForLDAP, redirectToIdp } from "@/lib/actions/idp"; +import { createIdpFlowProof, isIdpFlowProofValid } from "@/lib/server/idp-flow-proof"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +// Mock all the dependencies +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("next/navigation", () => ({ + redirect: vi.fn((url: string) => { + throw new Error(`REDIRECT: ${url}`); + }), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/server/host", () => ({ + getInstanceHost: vi.fn(), + getPublicHost: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + startIdentityProviderFlow: vi.fn(), + startLDAPIdentityProviderFlow: vi.fn(), +})); + +vi.mock("@/lib/server/fingerprint", () => ({ + getBindingIdCookie: vi.fn(), + addIdpFlowProof: vi.fn(), +})); + +// the real helper reads the binding id cookie, here the browser binding id is "fp123" +async function mockAddIdpFlowProof() { + const { addIdpFlowProof } = await import("@/lib/server/fingerprint"); + vi.mocked(addIdpFlowProof).mockImplementation(async (params, linkToSessionId) => { + params.set("flowFingerprint", createIdpFlowProof("fp123", linkToSessionId)); + }); +} + +describe("redirectToIdp", () => { + let mockHeaders: any; + let mockGetServiceUrlFromHeaders: any; + let mockGetInstanceHost: any; + let mockGetPublicHost: any; + let mockStartIdentityProviderFlow: any; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + + // Import mocked modules + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getInstanceHost, getPublicHost } = await import("@/lib/server/host"); + const { startIdentityProviderFlow } = await import("@/lib/server/zitadel"); + const { getBindingIdCookie } = await import("@/lib/server/fingerprint"); + const { getSessionCookieById } = await import("@/lib/server/cookies"); + + // Setup mocks + mockHeaders = vi.mocked(headers); + mockGetServiceUrlFromHeaders = vi.mocked(getServiceConfig); + mockGetInstanceHost = vi.mocked(getInstanceHost); + mockGetPublicHost = vi.mocked(getPublicHost); + mockStartIdentityProviderFlow = vi.mocked(startIdentityProviderFlow); + const mockGetBindingIdCookie = vi.mocked(getBindingIdCookie); + const mockGetSessionCookieById = vi.mocked(getSessionCookieById); + + // Default mock implementations + mockGetBindingIdCookie.mockResolvedValue({ name: "bindingId", value: "fp123" }); + await mockAddIdpFlowProof(); + mockGetSessionCookieById.mockResolvedValue({} as any); + mockHeaders.mockResolvedValue({} as any); + mockGetServiceUrlFromHeaders.mockReturnValue({ + serviceConfig: { baseUrl: "https://api.example.com" }, + }); + mockGetInstanceHost.mockReturnValue("example.com"); + mockGetPublicHost.mockReturnValue("example.com"); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + describe("postErrorRedirectUrl parameter handling", () => { + test("should include postErrorRedirectUrl in success and failure URLs when provided", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("requestId", "req123"); + formData.append("organization", "org123"); + formData.append("postErrorRedirectUrl", "https://app.example.com/error"); + + mockStartIdentityProviderFlow.mockResolvedValue("https://idp.example.com/auth"); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + idpId: "idp123", + urls: { + successUrl: expect.stringContaining("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror"), + failureUrl: expect.stringContaining("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror"), + }, + }); + + // Verify both URLs contain all expected parameters + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + const successUrl = callArgs.urls.successUrl; + const failureUrl = callArgs.urls.failureUrl; + + expect(successUrl).toContain("requestId=req123"); + expect(successUrl).toContain("organization=org123"); + expect(successUrl).toContain("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror"); + + expect(failureUrl).toContain("requestId=req123"); + expect(failureUrl).toContain("organization=org123"); + expect(failureUrl).toContain("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror"); + }); + + test("should not include postErrorRedirectUrl in URLs when not provided", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("requestId", "req123"); + formData.append("organization", "org123"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + idpId: "idp123", + urls: { + successUrl: expect.not.stringContaining("postErrorRedirectUrl"), + failureUrl: expect.not.stringContaining("postErrorRedirectUrl"), + }, + }); + + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + expect(callArgs.urls.successUrl).not.toContain("postErrorRedirectUrl"); + expect(callArgs.urls.failureUrl).not.toContain("postErrorRedirectUrl"); + }); + + test("should not include postErrorRedirectUrl when it is an empty string", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("postErrorRedirectUrl", ""); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + expect(callArgs.urls.successUrl).not.toContain("postErrorRedirectUrl"); + expect(callArgs.urls.failureUrl).not.toContain("postErrorRedirectUrl"); + }); + + test("should include postErrorRedirectUrl in LDAP redirect URL", async () => { + const formData = new FormData(); + formData.append("id", "ldap123"); + formData.append("provider", "ldap"); + formData.append("requestId", "req123"); + formData.append("organization", "org123"); + formData.append("postErrorRedirectUrl", "/custom-error"); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT: /idp/ldap?"); + expect(error.message).toContain("requestId=req123"); + expect(error.message).toContain("organization=org123"); + expect(error.message).toContain("postErrorRedirectUrl=%2Fcustom-error"); + } + }); + + test("should handle postErrorRedirectUrl with special characters", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("postErrorRedirectUrl", "https://app.example.com/error?code=123&message=test"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + const successUrl = new URL(callArgs.urls.successUrl); + const failureUrl = new URL(callArgs.urls.failureUrl); + + // Verify the URL is properly encoded + expect(successUrl.searchParams.get("postErrorRedirectUrl")).toBe( + "https://app.example.com/error?code=123&message=test", + ); + expect(failureUrl.searchParams.get("postErrorRedirectUrl")).toBe( + "https://app.example.com/error?code=123&message=test", + ); + }); + + test("should preserve postErrorRedirectUrl alongside linkOnly parameter", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("sessionId", "session123"); + formData.append("postErrorRedirectUrl", "/custom-error"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + const successUrl = callArgs.urls.successUrl; + const failureUrl = callArgs.urls.failureUrl; + + // Both parameters should be present + expect(successUrl).toContain("linkToSessionId=session123"); + expect(successUrl).toContain("postErrorRedirectUrl=%2Fcustom-error"); + expect(failureUrl).toContain("linkToSessionId=session123"); + expect(failureUrl).toContain("postErrorRedirectUrl=%2Fcustom-error"); + }); + + test("should handle relative postErrorRedirectUrl paths", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "github"); + formData.append("postErrorRedirectUrl", "/loginname"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + expect(callArgs.urls.successUrl).toContain("postErrorRedirectUrl=%2Floginname"); + expect(callArgs.urls.failureUrl).toContain("postErrorRedirectUrl=%2Floginname"); + }); + }); + + describe("loginHint parameter handling", () => { + test("should forward the loginHint to the IDP flow when provided", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("loginHint", "user@example.com"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith( + expect.objectContaining({ + idpId: "idp123", + urls: expect.objectContaining({ loginHint: "user@example.com" }), + }), + ); + }); + + test("should not set a loginHint when it is missing or empty", async () => { + for (const loginHint of [undefined, ""]) { + mockStartIdentityProviderFlow.mockReset(); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + if (loginHint !== undefined) { + formData.append("loginHint", loginHint); + } + + try { + await redirectToIdp(undefined, formData); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toContain("REDIRECT:"); + } + + const callArgs = mockStartIdentityProviderFlow.mock.calls[0][0]; + expect(callArgs.urls.loginHint).toBeUndefined(); + } + }); + }); + + describe("General redirect behavior", () => { + test("should return error when IDP flow returns null", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + + mockStartIdentityProviderFlow.mockResolvedValue(null); + + const result = await redirectToIdp(undefined, formData); + + expect(result).toEqual({ error: "Could not start IDP flow" }); + }); + + test("should redirect when IDP flow returns a valid URL", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + try { + await redirectToIdp(undefined, formData); + // Should not reach here + expect(true).toBe(false); + } catch (error: any) { + // Redirect throws in tests + expect(error.message).toBe("REDIRECT: https://idp.example.com/auth"); + } + }); + }); + + describe("flowFingerprint (browser binding)", () => { + test("should add a flow proof bound to this browser's binding id to the success URL", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + await expect(redirectToIdp(undefined, formData)).rejects.toThrow("REDIRECT:"); + + const successUrl = mockStartIdentityProviderFlow.mock.calls[0][0].urls.successUrl; + const flowFingerprint = new URL(successUrl).searchParams.get("flowFingerprint") ?? undefined; + expect(isIdpFlowProofValid(flowFingerprint, "fp123")).toBe(true); + expect(isIdpFlowProofValid(flowFingerprint, "other-fp")).toBe(false); + }); + + test("should bind the flow proof to the session when linking", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("sessionId", "session123"); + + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + await expect(redirectToIdp(undefined, formData)).rejects.toThrow("REDIRECT:"); + + const successUrl = new URL(mockStartIdentityProviderFlow.mock.calls[0][0].urls.successUrl); + const flowFingerprint = successUrl.searchParams.get("flowFingerprint") ?? undefined; + expect(isIdpFlowProofValid(flowFingerprint, "fp123", "session123")).toBe(true); + expect(isIdpFlowProofValid(flowFingerprint, "fp123", "other-session")).toBe(false); + expect(isIdpFlowProofValid(flowFingerprint, "fp123")).toBe(false); + }); + + test("should reject linking to a session this browser does not own", async () => { + const { getSessionCookieById } = await import("@/lib/server/cookies"); + vi.mocked(getSessionCookieById).mockResolvedValue(undefined); + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "google"); + formData.append("sessionId", "victim-session"); + + const result = await redirectToIdp(undefined, formData); + + expect(result).toEqual({ error: "Invalid session for linking" }); + expect(mockStartIdentityProviderFlow).not.toHaveBeenCalled(); + }); + + test("should not add a flow proof to the LDAP credentials page redirect", async () => { + const formData = new FormData(); + formData.append("id", "idp123"); + formData.append("provider", "ldap"); + + const error = await redirectToIdp(undefined, formData).catch((e: Error) => e); + + expect((error as Error).message).toContain("REDIRECT: /idp/ldap?"); + expect((error as Error).message).not.toContain("flowFingerprint"); + }); + }); +}); + +describe("createNewSessionForLDAP", () => { + beforeEach(async () => { + vi.clearAllMocks(); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { startLDAPIdentityProviderFlow } = await import("@/lib/server/zitadel"); + const { getSessionCookieById } = await import("@/lib/server/cookies"); + + vi.mocked(headers).mockResolvedValue({} as any); + vi.mocked(getServiceConfig).mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } } as any); + await mockAddIdpFlowProof(); + vi.mocked(getSessionCookieById).mockResolvedValue({} as any); + vi.mocked(startLDAPIdentityProviderFlow).mockResolvedValue({ + nextStep: { case: "idpIntent", value: { userId: "user123", idpIntentId: "intent123", idpIntentToken: "token123" } }, + } as any); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + test("should add a flow proof bound to this browser's binding id to the process URL", async () => { + const result = await createNewSessionForLDAP({ + username: "user", + password: "secret", + idpId: "idp123", + link: false, + requestId: "req123", + }); + + expect("redirect" in result && result.redirect).toContain("/idp/ldap/process?"); + const params = new URLSearchParams((result as { redirect: string }).redirect.split("?")[1]); + expect(params.get("id")).toBe("intent123"); + expect(params.get("requestId")).toBe("req123"); + expect(isIdpFlowProofValid(params.get("flowFingerprint") ?? undefined, "fp123")).toBe(true); + expect(isIdpFlowProofValid(params.get("flowFingerprint") ?? undefined, "other-fp")).toBe(false); + }); + + test("should bind the flow proof to the session to link", async () => { + const result = await createNewSessionForLDAP({ + username: "user", + password: "secret", + idpId: "idp123", + link: true, + linkToSessionId: "session123", + }); + + const params = new URLSearchParams((result as { redirect: string }).redirect.split("?")[1]); + expect(params.get("linkToSessionId")).toBe("session123"); + expect(isIdpFlowProofValid(params.get("flowFingerprint") ?? undefined, "fp123", "session123")).toBe(true); + expect(isIdpFlowProofValid(params.get("flowFingerprint") ?? undefined, "fp123")).toBe(false); + }); + + test("should reject linking to a session this browser does not own", async () => { + const { getSessionCookieById } = await import("@/lib/server/cookies"); + const { startLDAPIdentityProviderFlow } = await import("@/lib/server/zitadel"); + vi.mocked(getSessionCookieById).mockResolvedValue(undefined); + + const result = await createNewSessionForLDAP({ + username: "user", + password: "secret", + idpId: "idp123", + link: true, + linkToSessionId: "victim-session", + }); + + expect(result).toEqual({ error: "Invalid session for linking" }); + expect(startLDAPIdentityProviderFlow).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/idp.ts b/auth/ui/v2/apps/login/src/lib/actions/idp.ts new file mode 100644 index 0000000..8d7c033 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/idp.ts @@ -0,0 +1,169 @@ +"use server"; + +import { getSessionCookieById } from "@/lib/server/cookies"; +import { addIdpFlowProof } from "@/lib/server/fingerprint"; +import { getPublicHost } from "@/lib/server/host"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { ServiceConfig, startIdentityProviderFlow, startLDAPIdentityProviderFlow } from "@/lib/server/zitadel"; +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +export type RedirectToIdpState = + { error?: string | null; samlData?: { url: string; fields: Record } } | undefined; + +export async function redirectToIdp(prevState: RedirectToIdpState, formData: FormData): Promise { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const host = getPublicHost(_headers); + + const params = new URLSearchParams(); + + const sessionId = formData.get("sessionId") as string; + const requestId = formData.get("requestId") as string; + const organization = formData.get("organization") as string; + const idpId = formData.get("id") as string; + const provider = formData.get("provider") as string; + const postErrorRedirectUrl = formData.get("postErrorRedirectUrl") as string; + const loginHint = formData.get("loginHint") as string; + + if (sessionId) { + // the session to link must be one of this browser's sessions + if (!(await getSessionCookieById({ sessionId }).catch(() => undefined))) { + return { error: "Invalid session for linking" }; + } + params.set("linkToSessionId", sessionId); + } + if (requestId) params.set("requestId", requestId); + if (organization) params.set("organization", organization); + if (postErrorRedirectUrl) params.set("postErrorRedirectUrl", postErrorRedirectUrl); + + // redirect to LDAP page where username and password is requested + if (provider === "ldap") { + params.set("idpId", idpId); + redirect(`/idp/ldap?` + params.toString()); + } + + // binds the flow to this browser (and the session to link), checked when the callback is processed + await addIdpFlowProof(params, sessionId); + + const response = await startIDPFlow({ + serviceConfig, + host, + idpId, + successUrl: `/idp/${provider}/process?` + params.toString(), + failureUrl: `/idp/${provider}/failure?` + params.toString(), + loginHint: loginHint || undefined, + }); + + if (!response) { + return { error: "Could not start IDP flow" }; + } + + if (response && "error" in response && response?.error) { + return { error: response.error }; + } + + if (response && "redirect" in response && response?.redirect) { + redirect(response.redirect); + } + + if (response && "samlData" in response && response?.samlData) { + return { samlData: response.samlData }; + } + + return { error: "Unexpected response from IDP flow" }; +} + +export type StartIDPFlowCommand = { + serviceConfig: ServiceConfig; + host: string; + idpId: string; + successUrl: string; + failureUrl: string; + loginHint?: string; +}; + +async function startIDPFlow(command: StartIDPFlowCommand) { + const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; + + const response = await startIdentityProviderFlow({ + serviceConfig: command.serviceConfig, + idpId: command.idpId, + urls: { + successUrl: `${command.host.includes("localhost") ? "http://" : "https://"}${command.host}${basePath}${command.successUrl}`, + failureUrl: `${command.host.includes("localhost") ? "http://" : "https://"}${command.host}${basePath}${command.failureUrl}`, + loginHint: command.loginHint, + }, + }); + + if (!response || !response.url) { + return { error: "Could not start IDP flow" }; + } + + if (response.fields) { + return { samlData: { url: response.url, fields: response.fields } }; + } + + return { redirect: response.url }; +} + +type createNewSessionForLDAPCommand = { + username: string; + password: string; + idpId: string; + link: boolean; + requestId?: string; + organization?: string; + postErrorRedirectUrl?: string; + linkToSessionId?: string; +}; + +export async function createNewSessionForLDAP(command: createNewSessionForLDAPCommand) { + const _headers = await headers(); + + const { serviceConfig } = getServiceConfig(_headers); + + if (!command.username || !command.password) { + return { error: "No username or password provided" }; + } + + // the session to link must be one of this browser's sessions, same as redirectToIdp + if (command.linkToSessionId) { + const sessionCookie = await getSessionCookieById({ sessionId: command.linkToSessionId }).catch(() => undefined); + if (!sessionCookie) { + return { error: "Invalid session for linking" }; + } + } + + const response = await startLDAPIdentityProviderFlow({ + serviceConfig, + idpId: command.idpId, + username: command.username, + password: command.password, + }); + + if (!response || response.nextStep.case !== "idpIntent" || !response.nextStep.value) { + return { error: "Could not start LDAP identity provider flow" }; + } + + const { userId, idpIntentId, idpIntentToken } = response.nextStep.value; + + const params = new URLSearchParams({ + userId, + id: idpIntentId, + token: idpIntentToken, + }); + await addIdpFlowProof(params, command.linkToSessionId); + + if (command.link) { + params.set("link", "true"); + } + if (command.requestId) params.set("requestId", command.requestId); + if (command.organization) params.set("organization", command.organization); + if (command.postErrorRedirectUrl) params.set("postErrorRedirectUrl", command.postErrorRedirectUrl); + if (command.linkToSessionId) params.set("linkToSessionId", command.linkToSessionId); + + return { + redirect: `/idp/ldap/process?` + params.toString(), + }; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/language.test.ts b/auth/ui/v2/apps/login/src/lib/actions/language.test.ts new file mode 100644 index 0000000..0df7f34 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/language.test.ts @@ -0,0 +1,27 @@ +import { setLanguageCookie } from "@/lib/actions/language"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@/lib/server/cookies", () => ({ + setLanguageCookie: vi.fn(), +})); + +describe("setLanguageCookie", () => { + let setCookie: any; + + beforeEach(async () => { + vi.clearAllMocks(); + setCookie = vi.mocked((await import("@/lib/server/cookies")).setLanguageCookie); + }); + + test("sets a supported language", async () => { + await setLanguageCookie("de"); + + expect(setCookie).toHaveBeenCalledWith("de"); + }); + + test("ignores a value that is not a supported language", async () => { + await setLanguageCookie("de; Path=/evil"); + + expect(setCookie).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/language.ts b/auth/ui/v2/apps/login/src/lib/actions/language.ts new file mode 100644 index 0000000..375798a --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/language.ts @@ -0,0 +1,12 @@ +"use server"; + +import { LANGS } from "@/lib/i18n"; +import { setLanguageCookie as setLanguageCookieValue } from "@/lib/server/cookies"; + +export async function setLanguageCookie(language: string) { + if (!LANGS.some((lang) => lang.code === language)) { + return; + } + + await setLanguageCookieValue(language); +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/loginname.test.ts b/auth/ui/v2/apps/login/src/lib/actions/loginname.test.ts new file mode 100644 index 0000000..e845dc0 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/loginname.test.ts @@ -0,0 +1,1738 @@ +import { sendLoginname } from "@/lib/actions/loginname"; +import { createIdpFlowProof, isIdpFlowProofValid } from "@/lib/server/idp-flow-proof"; +import { getIDPByID } from "@/lib/server/zitadel"; +import { PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { UserState } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +// Mock all the dependencies +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("@zitadel/client", () => ({ + create: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/idp", () => ({ + idpTypeToIdentityProviderType: vi.fn(), + idpTypeToSlug: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + getActiveIdentityProviders: vi.fn(), + getIDPByID: vi.fn(), + getLoginSettings: vi.fn(), + getOrgsByDomain: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), + listIDPLinks: vi.fn(), + searchUsers: vi.fn(), + startIdentityProviderFlow: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/server/fingerprint", () => ({ + addIdpFlowProof: vi.fn(), +})); + +vi.mock("@/lib/server/host", () => ({ + getInstanceHost: vi.fn(), + getPublicHost: vi.fn(), +})); + +vi.mock("@/lib/server/verification-email", () => ({ + trySendVerification: vi.fn(() => Promise.resolve(false)), +})); + +// this returns the key itself that can be checked not the translated value +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +describe("sendLoginname", () => { + // Mock modules + let mockHeaders: any; + let mockCreate: any; + let mockGetServiceUrlFromHeaders: any; + let mockGetLoginSettings: any; + let mockSearchUsers: any; + let mockCreateSessionAndUpdateCookie: any; + let mockListAuthenticationMethodTypes: any; + let mockListIDPLinks: any; + let mockGetInstanceHost: any; + let mockGetPublicHost: any; + let mockStartIdentityProviderFlow: any; + let mockGetActiveIdentityProviders: any; + let mockGetIDPByID: any; + let mockIdpTypeToSlug: any; + let mockGetOrgsByDomain: any; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + + // Import mocked modules + const { headers } = await import("next/headers"); + const { create } = await import("@zitadel/client"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { + getLoginSettings, + searchUsers, + listAuthenticationMethodTypes, + listIDPLinks, + startIdentityProviderFlow, + getActiveIdentityProviders, + getOrgsByDomain, + } = await import("@/lib/server/zitadel"); + const { createSessionAndUpdateCookie } = await import("@/lib/server/session-cookie"); + const { getInstanceHost, getPublicHost } = await import("@/lib/server/host"); + const { idpTypeToSlug } = await import("@/lib/idp"); + const { addIdpFlowProof } = await import("@/lib/server/fingerprint"); + + // Setup mocks + mockHeaders = vi.mocked(headers); + mockCreate = vi.mocked(create); + mockGetServiceUrlFromHeaders = vi.mocked(getServiceConfig); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockSearchUsers = vi.mocked(searchUsers); + mockCreateSessionAndUpdateCookie = vi.mocked(createSessionAndUpdateCookie); + mockListAuthenticationMethodTypes = vi.mocked(listAuthenticationMethodTypes); + mockListIDPLinks = vi.mocked(listIDPLinks); + mockGetInstanceHost = vi.mocked(getInstanceHost); + mockGetPublicHost = vi.mocked(getPublicHost); + mockStartIdentityProviderFlow = vi.mocked(startIdentityProviderFlow); + mockGetActiveIdentityProviders = vi.mocked(getActiveIdentityProviders); + mockGetIDPByID = vi.mocked(getIDPByID); + mockIdpTypeToSlug = vi.mocked(idpTypeToSlug); + mockGetOrgsByDomain = vi.mocked(getOrgsByDomain); + + // Default mock implementations + mockHeaders.mockResolvedValue({} as any); + mockGetServiceUrlFromHeaders.mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } }); + // the real helper reads the binding id cookie, here the browser binding id is "fp123" + vi.mocked(addIdpFlowProof).mockImplementation(async (params, linkToSessionId) => { + params.set("flowFingerprint", createIdpFlowProof("fp123", linkToSessionId)); + }); + mockGetInstanceHost.mockReturnValue("example.com"); + mockGetPublicHost.mockReturnValue("example.com"); + mockIdpTypeToSlug.mockReturnValue("google"); + mockGetIDPByID.mockResolvedValue({ + id: "idp123", + name: "Google", + type: "GOOGLE", + }); + // Default: org discovery returns empty result + mockGetOrgsByDomain.mockResolvedValue({ result: [] }); + // Default: no active identity providers + mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + describe("Error cases", () => { + test("should return error when login settings cannot be retrieved", async () => { + mockGetLoginSettings.mockResolvedValue(null); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "errors.couldNotGetLoginSettings" }); + }); + + test("should return error when user search fails", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: true }); + mockSearchUsers.mockResolvedValue({ error: "Search failed" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "Search failed" }); + }); + + test("should return error when search result has no result field", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: true }); + mockSearchUsers.mockResolvedValue({}); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "errors.couldNotSearchUsers" }); + }); + + test("should return error when more than one user found", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: true }); + mockSearchUsers.mockResolvedValue({ + result: [ + { userId: "user1", preferredLoginName: "user1@example.com" }, + { userId: "user2", preferredLoginName: "user2@example.com" }, + ], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "errors.moreThanOneUserFound" }); + }); + }); + + describe("Single user found - authentication method handling", () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + beforeEach(() => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: true }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + }); + + test("should redirect to verify without codeSent when user has no authentication methods and email is unverified", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + organization: "org123", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/verify\?/); + expect((result as any).redirect).toContain("loginName=user%40example.com"); + expect((result as any).redirect).toContain("invite=true"); + expect((result as any).redirect).toContain("requestId=req123"); + }); + + test("should redirect to verify when user has no authentication methods and email is already verified", async () => { + const verifiedEmailUser = { + ...mockUser, + type: { case: "human", value: { email: { email: "user@example.com", isVerified: true } } }, + }; + mockSearchUsers.mockResolvedValue({ result: [verifiedEmailUser] }); + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + organization: "org123", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/verify\?/); + expect((result as any).redirect).toContain("loginName=user%40example.com"); + expect((result as any).redirect).toContain("invite=true"); + expect((result as any).redirect).toContain("requestId=req123"); + }); + + describe("Single authentication method", () => { + test("should redirect to password when user has only password method and it's allowed", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + expect((result as any).redirect).toContain("loginName=user%40example.com"); + expect((result as any).redirect).toContain("requestId=req123"); + }); + + test("should attempt IDP redirect when password is not allowed but user has IDP links", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth" }); + expect(mockListIDPLinks).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + userId: "user123", + }); + }); + + test("should pass the login name to the user's IDP as a login hint", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + await sendLoginname({ + loginName: "user@example.com", + }); + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith( + expect.objectContaining({ + urls: expect.objectContaining({ loginHint: "user@example.com" }), + }), + ); + }); + + test("should prefer the username known by the linked IDP over the login name as a login hint", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123", userName: "user.name@idp.example.com" }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + await sendLoginname({ + loginName: "user@example.com", + }); + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith( + expect.objectContaining({ + urls: expect.objectContaining({ loginHint: "user.name@idp.example.com" }), + }), + ); + }); + + test("should add the suffix back to the login hint when the user only typed the local part", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + await sendLoginname({ + loginName: "user", + suffix: "example.com", + }); + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith( + expect.objectContaining({ + urls: expect.objectContaining({ loginHint: "user@example.com" }), + }), + ); + }); + + test("should return error when password not allowed and no IDP links available", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ result: [] }); + mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ + error: "errors.localAuthenticationNotAllowed", + }); + }); + + test("should redirect to organization IDP when password not allowed, no user IDP links, but organization has active IDP", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ result: [] }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "org-idp-123", type: 0, options: { isAutoCreation: true } }], + }); + mockIdpTypeToSlug.mockReturnValue("google"); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://org-idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ redirect: "https://org-idp.example.com/auth" }); + expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + orgId: "org123", // User's organization from resourceOwner + }); + }); + + test("should pass the login name to the organization's single active IDP as a login hint", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ result: [] }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "org-idp-123", type: 0, options: { isAutoCreation: true } }], + }); + mockIdpTypeToSlug.mockReturnValue("google"); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://org-idp.example.com/auth" }); + + await sendLoginname({ + loginName: "user@example.com", + }); + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith( + expect.objectContaining({ + urls: expect.objectContaining({ loginHint: "user@example.com" }), + }), + ); + }); + + test.each([ + ["the user's linked IDP", [{ idpId: "idp123" }], []], + ["the organization's single active IDP", [], [{ id: "org-idp-123", type: 0, options: { isAutoCreation: true } }]], + ])("should bind the flow to this browser when redirecting to %s", async (_name, idpLinks, activeIdps) => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ result: idpLinks }); + mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: activeIdps }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + await sendLoginname({ + loginName: "user@example.com", + }); + + const successUrl = new URL(mockStartIdentityProviderFlow.mock.calls[0][0].urls.successUrl); + expect(successUrl.pathname).toMatch(/\/idp\/google\/process$/); + expect(isIdpFlowProofValid(successUrl.searchParams.get("flowFingerprint") ?? undefined, "fp123")).toBe(true); + expect(isIdpFlowProofValid(successUrl.searchParams.get("flowFingerprint") ?? undefined, "other-fp")).toBe(false); + }); + + test("should redirect to passkey when user has only passkey method and it's allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ passkeysType: PasskeysType.ALLOWED, allowLocalAuthentication: true }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/passkey\?/); + expect((result as any).redirect).toContain("loginName=user%40example.com"); + expect((result as any).redirect).toContain("requestId=req123"); + }); + + test("should return error when passkeys are not allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ passkeysType: PasskeysType.NOT_ALLOWED, allowLocalAuthentication: true }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ + error: "errors.passkeysNotAllowed", + }); + }); + + test("should return error when passkeys are allowed but allowLocalAuthentication is false", async () => { + mockGetLoginSettings.mockResolvedValue({ + passkeysType: PasskeysType.ALLOWED, + allowLocalAuthentication: false, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ + error: "errors.passkeysNotAllowed", + }); + }); + + test("should redirect to IDP when user has only IDP method", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.IDP], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth" }); + }); + + test("should redirect to IDP selection when user has only IDP method with multiple IDP links", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.IDP], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }, { idpId: "idp456" }], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "oidc_req123", + }); + + expect(mockStartIdentityProviderFlow).not.toHaveBeenCalled(); + expect(result).toEqual({ redirect: "/idp?requestId=oidc_req123&organization=org123" }); + }); + + test("should NOT create session when ignoreUnknownUsernames is true", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: true, + ignoreUnknownUsernames: true, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + }); + + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + expect((result as any).redirect).toContain("loginName=user%40example.com"); + }); + }); + + describe("Multiple authentication methods", () => { + test("should prefer passkey when multiple methods available", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD, AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/passkey\?/); + expect((result as any).redirect).toContain("altPassword=true"); // password is allowed + }); + + test("should return error when allowLocalAuthentication is false (disabling both password and passkey)", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD, AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ + error: "errors.localAuthenticationNotAllowed", + }); + }); + + test("should redirect to IDP when no passkey but IDP available", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD, AuthenticationMethodType.IDP], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth" }); + }); + + test("should fall back to password when user has password and multiple IDP links", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD, AuthenticationMethodType.IDP], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }, { idpId: "idp456" }], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "oidc_req123", + }); + + expect(mockStartIdentityProviderFlow).not.toHaveBeenCalled(); + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + }); + + test("should redirect to IDP selection when user has password and multiple IDP links but local authentication is not allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD, AuthenticationMethodType.IDP], + }); + mockListIDPLinks.mockResolvedValue({ + result: [{ idpId: "idp123" }, { idpId: "idp456" }], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "oidc_req123", + }); + + expect(mockStartIdentityProviderFlow).not.toHaveBeenCalled(); + expect(result).toEqual({ redirect: "/idp?requestId=oidc_req123&organization=org123" }); + }); + + test("should redirect to password when no passkey or IDP, only password available and allowed", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toMatch(/^\/password\?/); + }); + + test("should return error when password is only method in multi-method scenario but not allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ result: [] }); + mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ + error: "errors.localAuthenticationNotAllowed", + }); + }); + }); + }); + + describe("User not found scenarios", () => { + beforeEach(() => { + mockSearchUsers.mockResolvedValue({ result: [] }); + }); + + test("should redirect to single IDP when register allowed but password not allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: true, + allowLocalAuthentication: false, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp123", type: "OIDC", options: { isAutoCreation: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth" }); + }); + + test("should redirect to register when both register and password allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + organization: "org123", + requestId: "req123", + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toMatch(/^\/register\?/); + expect(result?.redirect).toContain("organization=org123"); + expect(result?.redirect).toContain("requestId=req123"); + expect(result?.redirect).toContain("email=user%40example.com"); + }); + + test("should redirect to password when ignoreUnknownUsernames is true", async () => { + mockGetLoginSettings.mockResolvedValue({ + ignoreUnknownUsernames: true, + allowLocalAuthentication: true, + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + organization: "org123", + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toMatch(/^\/password\?/); + expect(result?.redirect).toContain("loginName=user%40example.com"); + expect(result?.redirect).toContain("requestId=req123"); + expect(result?.redirect).toContain("organization=org123"); + }); + + test("should redirect to IDP via domain discovery for IdP-only org even when ignoreUnknownUsernames is true", async () => { + // Regression test: enumeration protection must not divert unknown users of + // an IdP-only org (allowLocalAuthentication: false) to the decoy password + // screen — known users of that org are auto-redirected to the IdP, so the + // redirect is the indistinguishable (and functional) behavior. + mockGetLoginSettings + .mockResolvedValueOnce({ + // context (instance default) settings + ignoreUnknownUsernames: true, + allowLocalAuthentication: true, + }) + .mockResolvedValueOnce({ + // discovered org settings: IdP-only + allowDomainDiscovery: true, + allowRegister: false, + allowLocalAuthentication: false, + ignoreUnknownUsernames: true, + }); + + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-sso", name: "Enterprise Org" }], + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp-entra", type: "OIDC", options: { isCreationAllowed: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://entra.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "newuser@enterprise.com", + requestId: "req123", + }); + + expect(result).toEqual({ redirect: "https://entra.example.com/auth" }); + + expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + orgId: "discovered-org-sso", + }); + }); + + test("should keep decoy password screen when ignoreUnknownUsernames is true and discovered org allows local authentication", async () => { + // With local authentication enabled, known (password) users see the + // password screen, so the decoy is what keeps unknown users + // indistinguishable — the discovery-based IdP redirect stays gated. + mockGetLoginSettings + .mockResolvedValueOnce({ + // context (instance default) settings + ignoreUnknownUsernames: true, + allowLocalAuthentication: true, + }) + .mockResolvedValueOnce({ + // discovered org settings: local auth enabled + allowDomainDiscovery: true, + allowRegister: false, + allowLocalAuthentication: true, + ignoreUnknownUsernames: true, + }); + + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-local", name: "Password Org" }], + }); + + const result = await sendLoginname({ + loginName: "newuser@company.com", + requestId: "req123", + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toMatch(/^\/password\?/); + expect(result?.redirect).toContain("loginName=newuser%40company.com"); + expect(result?.redirect).toContain("organization=discovered-org-local"); + expect(mockStartIdentityProviderFlow).not.toHaveBeenCalled(); + }); + + test("should return error when user not found and no registration allowed", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: false, + allowLocalAuthentication: true, + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "errors.userNotFound" }); + }); + + test("should redirect to IDP when allowRegister: false, allowLocalAuthentication: false and a single active IDP exists", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: false, + allowLocalAuthentication: false, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp123", type: "OIDC", options: { isAutoCreation: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth" }); + }); + + test("should not redirect to IDP when single active IDP does not allow creation", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: false, + allowLocalAuthentication: false, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp123", type: "OIDC", options: { isAutoCreation: false, isCreationAllowed: false } }], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "errors.userNotFound" }); + }); + + test("should redirect to IDP when allowRegister: false, allowLocalAuthentication: true and discovered org has single active IDP", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: false, + allowLocalAuthentication: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp123", type: "OIDC", options: { isAutoCreation: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + organization: "org123", + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth" }); + }); + + test("should redirect to IDP via domain discovery when allowRegister: false, allowLocalAuthentication: true", async () => { + mockGetLoginSettings + .mockResolvedValueOnce({ + allowRegister: false, + allowLocalAuthentication: true, + }) + .mockResolvedValueOnce({ + allowDomainDiscovery: true, + allowRegister: false, + allowLocalAuthentication: true, + }); + + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-789", name: "Company Org" }], + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp456", type: "OIDC", options: { isAutoCreation: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://company-idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@company.com", + requestId: "req123", + }); + + expect(result).toEqual({ redirect: "https://company-idp.example.com/auth" }); + + expect(mockGetOrgsByDomain).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + domain: "company.com", + }); + + expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + orgId: "discovered-org-789", + }); + }); + + test("should redirect to IDP when allowRegister: true, allowLocalAuthentication: true and discovered org has single active IDP", async () => { + mockGetLoginSettings + .mockResolvedValueOnce({ + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }) + .mockResolvedValueOnce({ + allowDomainDiscovery: true, + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }); + + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-101", name: "Example Org" }], + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp789", type: "OIDC", options: { isAutoCreation: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://example-idp.example.com/auth" }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + }); + + expect(result).toEqual({ redirect: "https://example-idp.example.com/auth" }); + }); + + test("should return error when allowRegister: false, allowLocalAuthentication: true, discovered org but no active IDP", async () => { + mockGetLoginSettings + .mockResolvedValueOnce({ + allowRegister: false, + allowLocalAuthentication: true, + }) + .mockResolvedValueOnce({ + allowDomainDiscovery: true, + allowRegister: false, + allowLocalAuthentication: true, + }); + + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-empty", name: "No IDP Org" }], + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [], + }); + + const result = await sendLoginname({ + loginName: "user@noidp.com", + }); + + expect(result).toEqual({ error: "errors.userNotFound" }); + }); + + test("should discover organization from domain suffix when user not found without org context", async () => { + // Mock login settings for instance level (no org context) + mockGetLoginSettings + .mockResolvedValueOnce({ + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }) + // Mock login settings for discovered org - must include all necessary flags + .mockResolvedValueOnce({ + allowDomainDiscovery: true, + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }); + + // Mock org discovery to return one org with matching domain + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-123", name: "Example Org" }], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + requestId: "req123", + // No organization parameter - this is the key test scenario + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toMatch(/^\/register\?/); + expect(result?.redirect).toContain("organization=discovered-org-123"); + expect(result?.redirect).toContain("requestId=req123"); + expect(result?.redirect).toContain("email=user%40example.com"); + + // Verify org discovery was called with correct domain + expect(mockGetOrgsByDomain).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + domain: "example.com", + }); + }); + + test("should redirect to IDP with discovered org when user not found and only IDP allowed", async () => { + // Mock login settings for instance level (no org context) + mockGetLoginSettings + .mockResolvedValueOnce({ + allowRegister: true, + allowLocalAuthentication: false, + }) + // Mock login settings for discovered org - must include all necessary flags + .mockResolvedValueOnce({ + allowDomainDiscovery: true, + allowRegister: true, + allowLocalAuthentication: false, + }); + + // Mock org discovery to return one org with matching domain + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "discovered-org-456", name: "Example Org" }], + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp123", type: "OIDC", options: { isAutoCreation: true } }], + }); + mockStartIdentityProviderFlow.mockResolvedValue({ url: "https://idp.example.com/auth?org=discovered-org-456" }); + + const result = await sendLoginname({ + loginName: "user@company.com", + requestId: "req123", + // No organization parameter + }); + + expect(result).toEqual({ redirect: "https://idp.example.com/auth?org=discovered-org-456" }); + + // Verify org discovery was called + expect(mockGetOrgsByDomain).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + domain: "company.com", + }); + + // Verify IDP redirect was called with discovered org + expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://api.example.com" }, + orgId: "discovered-org-456", + }); + }); + + test("should not discover org if domain discovery is disabled", async () => { + mockGetLoginSettings + .mockResolvedValueOnce({ + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }) + // Mock login settings for org with domain discovery disabled + .mockResolvedValueOnce({ + allowDomainDiscovery: false, + }); + + mockGetOrgsByDomain.mockResolvedValue({ + result: [{ id: "10987654321", name: "Example Org" }], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + // No organization parameter + }); + + // Should return error since discovery is disabled and no org context + expect(result).toEqual({ error: "errors.userNotFound" }); + }); + + test("should not discover org if multiple orgs match the domain", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }); + + // Mock org discovery to return multiple orgs + mockGetOrgsByDomain.mockResolvedValue({ + result: [ + { id: "12345678910", name: "Example Org 1" }, + { id: "10987654321", name: "Example Org 2" }, + ], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + // No organization parameter + }); + + // Should return error since multiple orgs match + expect(result).toEqual({ error: "errors.userNotFound" }); + }); + + test("should use provided organization instead of discovering when org context exists", async () => { + mockGetLoginSettings.mockResolvedValue({ + allowRegister: true, + allowLocalAuthentication: true, + ignoreUnknownUsernames: false, + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + organization: "123456", + requestId: "req123", + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toMatch(/^\/register\?/); + expect(result?.redirect).toContain("organization=123456"); + + // Verify org discovery was NOT called since org was provided + expect(mockGetOrgsByDomain).not.toHaveBeenCalled(); + }); + + test("should redirect to password when ignoreUnknownUsernames is true, allowRegister is true, but allowLocalAuthentication is false (User not found)", async () => { + mockSearchUsers.mockResolvedValue({ result: [] }); + mockGetLoginSettings.mockResolvedValue({ + allowRegister: true, + allowLocalAuthentication: false, + ignoreUnknownUsernames: true, + }); + mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).not.toEqual({ error: "errors.userNotFound" }); + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + }); + + test("should redirect to password when ignoreUnknownUsernames is true, user found but rejected due to disableLoginWithEmail", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" }, phone: { phone: "123456" } } }, + state: UserState.ACTIVE, + }; + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithEmail: true, + ignoreUnknownUsernames: true, + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).not.toEqual({ error: "errors.userNotFound" }); + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + }); + + test("should allow login with email when disableLoginWithPhone is true and preferred login name differs from email", async () => { + // Regression test for: https://github.com/zitadel/zitadel/issues/11518 + // When preferredLoginName (e.g. username@org-domain) differs from the user's email, logging + // in with the email while disableLoginWithPhone=true must NOT be blocked. + const mockUser = { + userId: "user123", + preferredLoginName: "user@orgdomain.com", // org-domain scoped login name + details: { resourceOwner: "org123" }, + type: { + case: "human", + value: { email: { email: "user@test.com" }, phone: { phone: "+1234567890" } }, + }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@orgdomain.com", + organizationId: "org123", + }, + }, + }; + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithPhone: true, + allowLocalAuthentication: true, + }); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "user@test.com", // logging in with email, not phone + }); + + // Must NOT return "User not found" — email-based login must be allowed when only phone is disabled + expect(result).not.toEqual({ error: "errors.userNotFound" }); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); + + test("should allow login with a differently cased login name when email and phone login are disabled", async () => { + // Regression test for: https://github.com/zitadel/zitadel/issues/12025 + // The user search matches case insensitively, so the follow up check that verifies + // the user was found by login name must not reject "Jackson@Example.com". + const mockUser = { + userId: "user123", + preferredLoginName: "jackson@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "jackson@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { user: { id: "user123", loginName: "jackson@example.com", organizationId: "org123" } }, + }; + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithEmail: true, + disableLoginWithPhone: true, + allowLocalAuthentication: true, + }); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "Jackson@Example.com", + }); + + expect(result).not.toEqual({ error: "errors.userNotFound" }); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); + + test("should allow login with a differently cased email when disableLoginWithPhone is true", async () => { + // Regression test for: https://github.com/zitadel/zitadel/issues/12025 + const mockUser = { + userId: "user123", + preferredLoginName: "jackson@orgdomain.com", + details: { resourceOwner: "org123" }, + type: { + case: "human", + value: { email: { email: "jackson@example.com" }, phone: { phone: "+1234567890" } }, + }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { user: { id: "user123", loginName: "jackson@orgdomain.com", organizationId: "org123" } }, + }; + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithPhone: true, + allowLocalAuthentication: true, + }); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "Jackson@Example.com", + }); + + expect(result).not.toEqual({ error: "errors.userNotFound" }); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); + + test("should block login with phone number when disableLoginWithPhone is true", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@orgdomain.com", + details: { resourceOwner: "org123" }, + type: { + case: "human", + value: { email: { email: "user@example.com" }, phone: { phone: "+1234567890" } }, + }, + state: UserState.ACTIVE, + }; + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithPhone: true, + }); + + const result = await sendLoginname({ + loginName: "+1234567890", // logging in with phone — must be blocked + }); + + expect(result).toEqual({ error: "errors.userNotFound" }); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("should redirect to password when ignoreUnknownUsernames is true and more than one user found", async () => { + mockGetLoginSettings.mockResolvedValue({ + ignoreUnknownUsernames: true, + }); + mockSearchUsers.mockResolvedValue({ + result: [ + { userId: "user1", preferredLoginName: "user1@example.com" }, + { userId: "user2", preferredLoginName: "user2@example.com" }, + ], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).not.toEqual({ error: "errors.moreThanOneUserFound" }); + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + }); + + test("should return generic error when user not active and ignoreUnknownUsernames is true", async () => { + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user1", + state: UserState.ACTIVE, + preferredLoginName: "user1", + type: { case: "human", value: { email: { isVerified: true } } }, + }, + ], + }); + mockGetLoginSettings.mockResolvedValue({ + ignoreUnknownUsernames: true, + allowLocalAuthentication: true, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + // Mock createSessionAndUpdateCookie to fail with user not active error + mockCreateSessionAndUpdateCookie.mockRejectedValue({ + rawMessage: "Errors.User.NotActive (SESSION-Gj4ko)", + }); + + const result = await sendLoginname({ loginName: "user1" }); + + expect(result).toEqual({ redirect: "/password?loginName=user1" }); + // With ignoreUnknownUsernames: true, we skip session creation, so this mock is NOT called + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("should NOT create session and return redirect when ignoreUnknownUsernames is true and user is valid", async () => { + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user1", + state: UserState.ACTIVE, + preferredLoginName: "user1", + type: { case: "human", value: { email: { isVerified: true } } }, + }, + ], + }); + mockGetLoginSettings.mockResolvedValue({ + ignoreUnknownUsernames: true, + allowLocalAuthentication: true, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ loginName: "user1" }); + + expect(result).toEqual({ redirect: "/password?loginName=user1" }); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("should redirect to password when ignoreUnknownUsernames is true and password not allowed", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: false, + ignoreUnknownUsernames: true, + }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockListIDPLinks.mockResolvedValue({ result: [] }); + mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).not.toEqual({ error: "errors.localAuthenticationNotAllowed" }); + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + }); + + test("should redirect to password when ignoreUnknownUsernames is true and passkeys not allowed", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ + passkeysType: PasskeysType.NOT_ALLOWED, + ignoreUnknownUsernames: true, + }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).not.toEqual({ error: "errors.passkeysNotAllowed" }); + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/password\?/); + }); + }); + + describe("Edge cases", () => { + test("should handle initial user state", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.INITIAL, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: true }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + + const result = await sendLoginname({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "errors.initialUserNotSupported" }); + }); + + test("should handle organization parameter in all redirects", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: true }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "user@example.com", + organization: "custom-org", + requestId: "req123", + }); + + expect(result).toBeDefined(); + expect(result?.redirect).toContain("organization=custom-org"); + expect(result?.redirect).toContain("requestId=req123"); + }); + + test("should redirect to password with INPUT loginName when ignoreUnknownUsernames is true, even if user preferredLoginName is different", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: true, + ignoreUnknownUsernames: true, + }); + // Mock search result returns a user with resolved/different loginName + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + // INPUT login name is just "user" + const result = await sendLoginname({ + loginName: "user", + }); + + expect(result).toHaveProperty("redirect"); + // Expect redirect to contain input "user" not resolved "user@example.com" + expect((result as any).redirect).toContain("loginName=user"); + expect((result as any).redirect).not.toContain("loginName=user%40example.com"); + }); + + test("should redirect to passkey with INPUT loginName when ignoreUnknownUsernames is true", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ + passkeysType: PasskeysType.ALLOWED, + allowLocalAuthentication: true, + ignoreUnknownUsernames: true, + }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSKEY], + }); + + const result = await sendLoginname({ + loginName: "user", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/passkey\?/); + expect((result as any).redirect).toContain("loginName=user"); + expect((result as any).redirect).not.toContain("loginName=user%40example.com"); + }); + + test("should redirect to passkey with INPUT loginName when ignoreUnknownUsernames is true (multi-method)", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "org123" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "org123", + }, + }, + }; + + mockGetLoginSettings.mockResolvedValue({ + passkeysType: PasskeysType.ALLOWED, + allowLocalAuthentication: true, + ignoreUnknownUsernames: true, + }); + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSKEY, AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "user", + }); + + expect(result).toHaveProperty("redirect"); + expect((result as any).redirect).toMatch(/^\/passkey\?/); + expect((result as any).redirect).toContain("loginName=user"); + expect((result as any).redirect).not.toContain("loginName=user%40example.com"); + }); + test("should use CONTEXT settings to HIDE username even if USER settings would show it", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "user-org" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "user-org", + }, + }, + }; + + // Mock implementation to return different settings based on organization + mockGetLoginSettings.mockImplementation(async (args: any) => { + if (args.organization === "context-org") { + return { allowLocalAuthentication: true, ignoreUnknownUsernames: true }; + } + if (args.organization === "user-org") { + return { allowLocalAuthentication: true, ignoreUnknownUsernames: false }; + } + return {}; + }); + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "input-name", + organization: "context-org", // Context has ignore=true + }); + + expect(result).toHaveProperty("redirect"); + // Should result in input-name because context says HIDE + expect((result as any).redirect).toContain("loginName=input-name"); + expect((result as any).redirect).not.toContain("loginName=user%40example.com"); + }); + + test("should use CONTEXT settings to SHOW username even if USER settings would hide it", async () => { + const mockUser = { + userId: "user123", + preferredLoginName: "user@example.com", + details: { resourceOwner: "user-org" }, + type: { case: "human", value: { email: { email: "user@example.com" } } }, + state: UserState.ACTIVE, + }; + + const mockSession = { + factors: { + user: { + id: "user123", + loginName: "user@example.com", + organizationId: "user-org", + }, + }, + }; + + mockGetLoginSettings.mockImplementation(async (args: any) => { + if (args.organization === "context-org") { + return { allowLocalAuthentication: true, ignoreUnknownUsernames: false }; + } + if (args.organization === "user-org") { + return { allowLocalAuthentication: true, ignoreUnknownUsernames: true }; + } + return {}; + }); + + mockSearchUsers.mockResolvedValue({ result: [mockUser] }); + mockCreate.mockReturnValue({}); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ session: mockSession, sessionCookie: {} }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + const result = await sendLoginname({ + loginName: "input-name", + organization: "context-org", // Context has ignore=false + }); + + expect(result).toHaveProperty("redirect"); + // Should result in resolved name because context says SHOW + expect((result as any).redirect).toContain("loginName=user%40example.com"); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/loginname.ts b/auth/ui/v2/apps/login/src/lib/actions/loginname.ts new file mode 100644 index 0000000..331e7ee --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/loginname.ts @@ -0,0 +1,664 @@ +"use server"; + +import { idpTypeToIdentityProviderType, idpTypeToSlug } from "@/lib/idp"; +import { equalsIgnoreCase } from "@/lib/server/auth-utils"; +import { addIdpFlowProof } from "@/lib/server/fingerprint"; +import { isClassifiedError } from "@/lib/server/grpc/interceptors/error-classification"; +import { createLogger } from "@/lib/server/logger"; +import { create } from "@zitadel/client"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +import { getPublicHost } from "@/lib/server/host"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { createSessionAndUpdateCookie } from "@/lib/server/session-cookie"; +import { trySendVerification } from "@/lib/server/verification-email"; +import { + getActiveIdentityProviders, + getIDPByID, + getLoginSettings, + getOrgsByDomain, + listAuthenticationMethodTypes, + listIDPLinks, + searchUsers, + SearchUsersCommand, + startIdentityProviderFlow, +} from "@/lib/server/zitadel"; +import { PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { IDPLink } from "@zitadel/proto/zitadel/user/v2/idp_pb"; +import { UserState } from "@zitadel/proto/zitadel/user/v2/user_pb"; + +const logger = createLogger("loginname"); + +export type SendLoginnameCommand = { + loginName: string; + requestId?: string; + organization?: string; + defaultOrganization?: string; + suffix?: string; +}; + +const ORG_SUFFIX_REGEX = /(?<=@)(.+)/; + +export async function sendLoginname(command: SendLoginnameCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const t = await getTranslations("loginname"); + + const loginSettingsByContext = await getLoginSettings({ serviceConfig, organization: command.organization }); + + if (!loginSettingsByContext) { + return { error: t("errors.couldNotGetLoginSettings") }; + } + + // Single source of truth for enumeration protection, derived server-side from the + // request-context login settings (sendLoginname is a public server action, so a + // client-supplied flag must not be trusted). It gates session creation and the + // loginName exposed in redirect URLs, keeping known and unknown users + // indistinguishable while protection applies. + const ignoreUnknownUsernames = !!loginSettingsByContext.ignoreUnknownUsernames; + + let searchUsersRequest: SearchUsersCommand = { + serviceConfig, + searchValue: command.loginName, + organizationId: command.organization, + loginSettings: loginSettingsByContext, + suffix: command.suffix, + }; + + const searchResult = await searchUsers(searchUsersRequest); + + // Safety check: ensure searchResult is defined + if (!searchResult) { + logger.error("searchUsers returned undefined or null"); + return { error: t("errors.couldNotSearchUsers") }; + } + + if ("error" in searchResult && searchResult.error) { + logger.debug("searchUsers returned error, returning early", { error: searchResult.error }); + return searchResult; + } + + if (!("result" in searchResult)) { + logger.debug("searchUsers has no result field"); + return { error: t("errors.couldNotSearchUsers") }; + } + + const { result: potentialUsers } = searchResult; + + // Additional safety check: treat undefined result as empty array + const users = potentialUsers ?? []; + + if (users.length === 0) { + logger.debug("No users found, will proceed with org discovery"); + } + + const preventUserEnumeration = (organization: string | undefined) => { + if (ignoreUnknownUsernames) { + logger.debug("ignoreUnknownUsernames is true, redirecting to password"); + const paramsPasswordDefault = new URLSearchParams({ + loginName: command.loginName, + }); + + if (command.requestId) { + paramsPasswordDefault.append("requestId", command.requestId); + } + + if (organization) { + paramsPasswordDefault.append("organization", organization); + } + + return { redirect: "/password?" + paramsPasswordDefault }; + } + + return { error: t("errors.userNotFound") }; + }; + + // With an org domain suffix the user types only the local part, so put the + // login name back together for the checks below and for the IdP login hint. + const concatLoginname = command.suffix ? `${command.loginName}@${command.suffix}` : command.loginName; + + const redirectUserToIDP = async (userId?: string, organization?: string) => { + // If userId is provided, check for user-specific IDP links first + let identityProviders: IDPLink[] = []; + if (userId) { + identityProviders = await listIDPLinks({ serviceConfig, userId }).then((resp) => { + return resp.result; + }); + } + + // If no IDP links exist for the user (or no userId provided), try to get active IDPs from the organization + if (identityProviders.length === 0) { + const activeIdps = await getActiveIdentityProviders({ serviceConfig, orgId: organization }).then((resp) => { + return resp.identityProviders.filter((idp) => idp.options?.isAutoCreation || idp.options?.isCreationAllowed); + }); + + // If exactly one active IDP exists in the organization, redirect to it + if (activeIdps.length === 1) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const host = getPublicHost(_headers); + + const identityProviderType = activeIdps[0].type; + const provider = idpTypeToSlug(identityProviderType); + + const params = new URLSearchParams(); + + if (userId) { + params.set("userId", userId); + } + + if (command.requestId) { + params.set("requestId", command.requestId); + } + + if (organization) { + params.set("organization", organization); + } + + await addIdpFlowProof(params); + + const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; + + const response = await startIdentityProviderFlow({ + serviceConfig, + idpId: activeIdps[0].id, + urls: { + successUrl: + `${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/process?` + + new URLSearchParams(params), + failureUrl: + `${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` + + new URLSearchParams(params), + loginHint: concatLoginname, + }, + }); + + if (!response || !response.url) { + return { error: t("errors.couldNotStartIDPFlow") }; + } + + if (response.fields) { + return { samlData: { url: response.url, fields: response.fields } }; + } + + return { redirect: response.url }; + } + } + + if (identityProviders.length === 1) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const host = getPublicHost(_headers); + + const identityProviderId = identityProviders[0].idpId; + + const idp = await getIDPByID({ serviceConfig, id: identityProviderId }); + + const idpType = idp?.type; + + if (!idp || !idpType) { + throw new Error(t("errors.couldNotFindIdentityProvider")); + } + + const identityProviderType = idpTypeToIdentityProviderType(idpType); + const provider = idpTypeToSlug(identityProviderType); + + const params = new URLSearchParams(); + + if (userId) { + params.set("userId", userId); + } + + if (command.requestId) { + params.set("requestId", command.requestId); + } + + if (organization) { + params.set("organization", organization); + } + + await addIdpFlowProof(params); + + const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; + + const response = await startIdentityProviderFlow({ + serviceConfig, + idpId: idp.id, + urls: { + successUrl: + `${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/process?` + + new URLSearchParams(params), + failureUrl: + `${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` + + new URLSearchParams(params), + // The user is already linked to this IdP, so prefer the username the + // IdP knows the user by over the ZITADEL login name (same as Login V1). + loginHint: identityProviders[0].userName || concatLoginname, + }, + }); + + if (!response || !response.url) { + return { error: t("errors.couldNotStartIDPFlow") }; + } + + if (response.fields) { + return { samlData: { url: response.url, fields: response.fields } }; + } + + return { redirect: response.url }; + } + }; + + // Used when the user has more than one identity provider and none can be picked automatically. + const redirectToIDPSelection = (organization?: string) => { + const params = new URLSearchParams(); + + if (command.requestId) { + params.set("requestId", command.requestId); + } + + if (organization) { + params.set("organization", organization); + } + + return { redirect: "/idp?" + params }; + }; + + if (users.length > 1) { + logger.debug("multiple users found, returning error"); + if (ignoreUnknownUsernames) { + return preventUserEnumeration(command.organization); + } + return { error: t("errors.moreThanOneUserFound") }; + } else if (users.length == 1 && users[0].userId) { + const user = users[0]; + const userId = users[0].userId; + + const userLoginSettings = await getLoginSettings({ serviceConfig, organization: user.details?.resourceOwner }); + + const humanUser = users[0].type.case === "human" ? users[0].type.value : undefined; + + // recheck login settings after user discovery, as the search might have been done without org scope + if (userLoginSettings?.disableLoginWithEmail && userLoginSettings?.disableLoginWithPhone) { + if (!equalsIgnoreCase(user.preferredLoginName, concatLoginname)) { + return preventUserEnumeration(command.organization); + } + } else if (userLoginSettings?.disableLoginWithEmail) { + if ( + !equalsIgnoreCase(user.preferredLoginName, concatLoginname) && + !equalsIgnoreCase(humanUser?.phone?.phone, command.loginName) + ) { + return preventUserEnumeration(command.organization); + } + } else if (userLoginSettings?.disableLoginWithPhone) { + if ( + !equalsIgnoreCase(user.preferredLoginName, concatLoginname) && + !equalsIgnoreCase(humanUser?.email?.email, command.loginName) + ) { + return preventUserEnumeration(command.organization); + } + } + + // Only create a session (and its cookie) when enumeration protection does not + // apply: with protection on, known and unknown users must be indistinguishable, + // and the /password page must not be able to tell the difference either. + let session; + if (!ignoreUnknownUsernames) { + const checks = create(ChecksSchema, { + user: { search: { case: "userId", value: userId } }, + }); + + const sessionOrError = await createSessionAndUpdateCookie({ + checks, + requestId: command.requestId, + }).catch((error) => { + if (isClassifiedError(error) && error.message?.includes("Errors.User.NotActive")) { + return { error: t("errors.userNotActive") }; + } + throw error; + }); + + if ("error" in sessionOrError) { + return sessionOrError; + } + + session = sessionOrError.session; + } + + if (session && !session.factors?.user?.id) { + return { error: t("errors.couldNotCreateSession") }; + } + + // LoginName to expose in redirect URLs: while enumeration protection applies, + // echo the raw input so known and unknown users stay indistinguishable; otherwise + // use the session's loginName so the next page can match the session cookie + // (falling back to the user's preferred login name). + const redirectLoginName = ignoreUnknownUsernames + ? command.loginName + : (session?.factors?.user?.loginName ?? user.preferredLoginName); + + // TODO: check if handling of userstate INITIAL is needed + if (user.state === UserState.INITIAL) { + if (ignoreUnknownUsernames) { + return preventUserEnumeration(command.organization); + } + return { error: t("errors.initialUserNotSupported") }; + } + + // Resolve organization from command or session + let organization = command.organization ?? session?.factors?.user?.organizationId ?? user.details?.resourceOwner; + + if (ignoreUnknownUsernames) { + organization = command.organization; + if (!organization && ORG_SUFFIX_REGEX.test(command.loginName)) { + const matched = ORG_SUFFIX_REGEX.exec(command.loginName); + const suffix = matched?.[1] ?? ""; + const orgs = await getOrgsByDomain({ serviceConfig, domain: suffix }); + + if (orgs.result && orgs.result.length === 1) { + const orgToCheckForDiscovery = orgs.result[0].id; + const orgLoginSettings = await getLoginSettings({ serviceConfig, organization: orgToCheckForDiscovery }); + + if (orgLoginSettings?.allowDomainDiscovery) { + organization = orgToCheckForDiscovery; + } + } + } + } + + const methods = await listAuthenticationMethodTypes({ + serviceConfig, + userId: session?.factors?.user?.id ?? userId, + }); + + const hasPrimaryMethod = + methods.authMethodTypes?.some( + (m: AuthenticationMethodType) => + m === AuthenticationMethodType.PASSWORD || + m === AuthenticationMethodType.PASSKEY || + m === AuthenticationMethodType.IDP, + ) ?? false; + + // always resend invite or setup email if user has no primary auth method set + if (!hasPrimaryMethod) { + logger.debug("humanUser.email?.isVerified", { + isVerified: humanUser?.email?.isVerified, + }); + + // If the user's email is not verified, they likely already have a code from the + // initial verification email. Auto-sending a new one here invalidates their existing code + // and causes confusion. Only auto-send if the email is already verified. + const shouldSend = humanUser?.email?.isVerified === true; + + const codeSent = shouldSend + ? await trySendVerification({ + userId: session?.factors?.user?.id ?? user.userId, + isInvite: true, + requestId: command.requestId, + }) + : false; + + const params = new URLSearchParams({ + loginName: (session?.factors?.user?.loginName ?? user.preferredLoginName) as string, + invite: "true", // always send invite code if user has no primary auth method + }); + + if (codeSent) { + params.append("codeSent", "true"); + } + + if (command.requestId) { + params.append("requestId", command.requestId); + } + + if (organization) { + params.append("organization", organization); + } + + return { redirect: `/verify?` + params }; + } + + if (methods.authMethodTypes.length == 1) { + const method = methods.authMethodTypes[0]; + switch (method) { + case AuthenticationMethodType.PASSWORD: // user has only password as auth method + if (!userLoginSettings?.allowLocalAuthentication) { + // Check if user has IDPs available as alternative, that could eventually be used to register/link. + const idpResp = await redirectUserToIDP(userId, organization); + if (idpResp?.redirect) { + return idpResp; + } + + if (ignoreUnknownUsernames) { + return preventUserEnumeration(command.organization); + } + + return { + error: t("errors.localAuthenticationNotAllowed"), + }; + } + + { + const paramsPassword = new URLSearchParams({ + loginName: redirectLoginName, + }); + + if (organization) { + paramsPassword.append("organization", organization); + } + + if (command.requestId) { + paramsPassword.append("requestId", command.requestId); + } + + return { + redirect: "/password?" + paramsPassword, + }; + } + + case AuthenticationMethodType.PASSKEY: // AuthenticationMethodType.AUTHENTICATION_METHOD_TYPE_PASSKEY + if (userLoginSettings?.passkeysType === PasskeysType.NOT_ALLOWED || !userLoginSettings?.allowLocalAuthentication) { + if (ignoreUnknownUsernames) { + return preventUserEnumeration(command.organization); + } + return { + error: t("errors.passkeysNotAllowed"), + }; + } + + { + const paramsPasskey = new URLSearchParams({ + loginName: redirectLoginName, + }); + if (command.requestId) { + paramsPasskey.append("requestId", command.requestId); + } + + if (organization) { + paramsPasskey.append("organization", organization); + } + + return { redirect: "/passkey?" + paramsPasskey }; + } + + case AuthenticationMethodType.IDP: { + const resp = await redirectUserToIDP(userId, organization); + + if (resp?.error) { + return { error: resp.error }; + } + + // no single identity provider could be resolved, let the user choose one + return resp ?? redirectToIDPSelection(organization); + } + } + } else { + // prefer passkey in favor of other methods + if ( + methods.authMethodTypes.includes(AuthenticationMethodType.PASSKEY) && + userLoginSettings?.passkeysType !== PasskeysType.NOT_ALLOWED && + userLoginSettings?.allowLocalAuthentication + ) { + const passkeyParams = new URLSearchParams({ + loginName: redirectLoginName, + altPassword: `${methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD) && userLoginSettings?.allowLocalAuthentication}`, // show alternative password option only if allowed + }); + + if (command.requestId) { + passkeyParams.append("requestId", command.requestId); + } + + if (organization) { + passkeyParams.append("organization", organization); + } + + return { redirect: "/passkey?" + passkeyParams }; + } + + if (methods.authMethodTypes.includes(AuthenticationMethodType.IDP)) { + const resp = await redirectUserToIDP(userId, organization); + if (resp) { + return resp; + } + // no single identity provider could be resolved, continue with the remaining methods + } + + if ( + methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD) && + userLoginSettings?.allowLocalAuthentication + ) { + // user has no passkey setup and login settings allow passwords + const paramsPasswordDefault = new URLSearchParams({ + loginName: redirectLoginName, + }); + + if (command.requestId) { + paramsPasswordDefault.append("requestId", command.requestId); + } + + if (organization) { + paramsPasswordDefault.append("organization", organization); + } + + return { + redirect: "/password?" + paramsPasswordDefault, + }; + } + + if (methods.authMethodTypes.includes(AuthenticationMethodType.IDP)) { + return redirectToIDPSelection(organization); + } + + if (methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD)) { + // password authentication is not allowed + if (ignoreUnknownUsernames) { + return preventUserEnumeration(command.organization); + } + return { + error: t("errors.localAuthenticationNotAllowed"), + }; + } + } + } + + logger.debug("User not found (0 potential users), checking registration options"); + + // user not found, perform organization discovery if no org context provided + let discoveredOrganization = command.organization; + let effectiveLoginSettings = loginSettingsByContext; + + if (!command.organization && command.defaultOrganization) { + const defaultLoginSettings = await getLoginSettings({ serviceConfig, organization: command.defaultOrganization }); + if (defaultLoginSettings) { + effectiveLoginSettings = defaultLoginSettings; + } + } + + if (!discoveredOrganization && command.loginName && ORG_SUFFIX_REGEX.test(command.loginName)) { + const matched = ORG_SUFFIX_REGEX.exec(command.loginName); + const suffix = matched?.[1] ?? ""; + + // this just returns orgs where the suffix is set as the Organization Domain + const orgs = await getOrgsByDomain({ serviceConfig, domain: suffix }); + + const orgToCheckForDiscovery = orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined; + + if (orgToCheckForDiscovery) { + const orgLoginSettings = await getLoginSettings({ serviceConfig, organization: orgToCheckForDiscovery }); + + if (orgLoginSettings?.allowDomainDiscovery) { + logger.debug("Org discovery successful", { organization: orgToCheckForDiscovery }); + discoveredOrganization = orgToCheckForDiscovery; + // Use the discovered organization's login settings for subsequent checks + effectiveLoginSettings = orgLoginSettings; + } else { + logger.debug("Org does not allow domain discovery"); + } + } else { + logger.debug("No single org found for discovery"); + } + } + + // When a user is not found, try to redirect to an external IdP if: + // - local authentication is disabled, OR + // - domain discovery resolved an organization (regardless of allowRegister) + // Registration policy (allowRegister) controls local account creation only + // and must not prevent authentication via an external IdP. + // Fixes: https://github.com/zitadel/zitadel/issues/12021 + // Fixes: https://github.com/zitadel/zitadel/issues/12023 + // + // Enumeration protection (ignoreUnknownUsernames) must NOT gate the redirect + // when local authentication is disabled: in an IdP-only org, known users are + // auto-redirected to the IdP, so sending unknown usernames to the very same + // IdP is what keeps them indistinguishable. Diverting unknown users to the + // decoy password screen instead would both break silent SSO for first-time + // users (the IdP is meant to create the account on first login) and act as an + // enumeration oracle (redirect = user exists, password screen = unknown). + // Conversely, when local authentication is enabled, the decoy password screen + // is what known (password) users see, so enumeration protection keeps gating + // the discovery-based redirect there. + + if (!effectiveLoginSettings?.allowLocalAuthentication || (discoveredOrganization && !ignoreUnknownUsernames)) { + const resp = await redirectUserToIDP(undefined, discoveredOrganization); + if (resp) { + logger.debug("Redirecting to IDP", { organization: discoveredOrganization }); + return resp; + } + + // If local auth is disabled, there is no fallback — return error + if (!effectiveLoginSettings?.allowLocalAuthentication) { + logger.debug("IDP redirect failed and local auth not allowed, returning user not found"); + return preventUserEnumeration(discoveredOrganization); + } + } + + if (effectiveLoginSettings?.allowRegister && effectiveLoginSettings?.allowLocalAuthentication) { + logger.debug("register and password both allowed"); + // do not register user if ignoreUnknownUsernames is set + if (discoveredOrganization && !effectiveLoginSettings?.ignoreUnknownUsernames) { + logger.debug("Redirecting to registration page", { organization: discoveredOrganization }); + const params = new URLSearchParams({ organization: discoveredOrganization }); + + if (command.requestId) { + params.set("requestId", command.requestId); + } + + if (command.loginName) { + params.set("email", command.loginName); + } + + return { redirect: "/register?" + params }; + } else { + logger.debug("Not redirecting to register", { + hasDiscoveredOrg: !!discoveredOrganization, + ignoreUnknownUsernames: effectiveLoginSettings?.ignoreUnknownUsernames, + }); + } + } + + return preventUserEnumeration(discoveredOrganization); +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/oidc.test.ts b/auth/ui/v2/apps/login/src/lib/actions/oidc.test.ts new file mode 100644 index 0000000..33daeb7 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/oidc.test.ts @@ -0,0 +1,116 @@ +import { getDeviceAuthorizationRequest } from "@/lib/actions/oidc"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@/lib/server/zitadel", () => ({ + getDeviceAuthorizationRequest: vi.fn(), + listSessions: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getAllSessions: vi.fn(), +})); + +vi.mock("@/lib/server/device-code-check", () => ({ + setDeviceCodeCheckCookie: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +const deviceAuthorizationRequest = { id: "encrypted-device-code", appName: "TV", clientId: "client-1" }; + +describe("getDeviceAuthorizationRequest", () => { + let zitadelGetDeviceAuthorizationRequest: any; + let listSessions: any; + let getAllSessions: any; + let setDeviceCodeCheckCookie: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const zitadel = await import("@/lib/server/zitadel"); + const cookies = await import("@/lib/server/cookies"); + const deviceCodeCheck = await import("@/lib/server/device-code-check"); + + zitadelGetDeviceAuthorizationRequest = vi.mocked(zitadel.getDeviceAuthorizationRequest); + listSessions = vi.mocked(zitadel.listSessions); + getAllSessions = vi.mocked(cookies.getAllSessions); + setDeviceCodeCheckCookie = vi.mocked(deviceCodeCheck.setDeviceCodeCheckCookie); + + zitadelGetDeviceAuthorizationRequest.mockResolvedValue({ deviceAuthorizationRequest }); + getAllSessions.mockResolvedValue([]); + }); + + test("does not set the check cookie or look up sessions when the lookup returns no request", async () => { + zitadelGetDeviceAuthorizationRequest.mockResolvedValue({ deviceAuthorizationRequest: undefined }); + + const result = await getDeviceAuthorizationRequest("ABCD-1234"); + + expect(result).toEqual({ deviceAuthorizationRequest: undefined, nextUrl: undefined }); + expect(setDeviceCodeCheckCookie).not.toHaveBeenCalled(); + expect(getAllSessions).not.toHaveBeenCalled(); + expect(listSessions).not.toHaveBeenCalled(); + }); + + test("does not set the check cookie when the lookup fails", async () => { + zitadelGetDeviceAuthorizationRequest.mockRejectedValue(new Error("not found")); + + await expect(getDeviceAuthorizationRequest("ABCD-1234")).rejects.toThrow("not found"); + expect(setDeviceCodeCheckCookie).not.toHaveBeenCalled(); + expect(listSessions).not.toHaveBeenCalled(); + }); + + test("continues to /loginname without session cookies and does not call listSessions", async () => { + const result = await getDeviceAuthorizationRequest("ABCD-1234"); + + expect(setDeviceCodeCheckCookie).toHaveBeenCalledWith("ABCD-1234"); + expect(listSessions).not.toHaveBeenCalled(); + expect(result).toEqual({ + deviceAuthorizationRequest, + nextUrl: "/loginname?requestId=device_ABCD-1234", + }); + }); + + test("continues to /accounts when the browser has a live session", async () => { + getAllSessions.mockResolvedValue([{ id: "session-1" }, { id: "" }, { id: "session-2" }]); + listSessions.mockResolvedValue({ sessions: [{ id: "session-1" }] }); + + const result = await getDeviceAuthorizationRequest("ABCD-1234"); + + expect(listSessions).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://example.com" }, + ids: ["session-1", "session-2"], + }); + expect(setDeviceCodeCheckCookie).toHaveBeenCalledWith("ABCD-1234"); + expect(result.nextUrl).toBe("/accounts?requestId=device_ABCD-1234"); + }); + + test("continues to /loginname when all session cookies point to ended sessions", async () => { + getAllSessions.mockResolvedValue([{ id: "session-1" }]); + listSessions.mockResolvedValue({ sessions: [] }); + + const result = await getDeviceAuthorizationRequest("ABCD-1234"); + + expect(result.nextUrl).toBe("/loginname?requestId=device_ABCD-1234"); + }); + + test("continues to /loginname and does not throw when listSessions fails", async () => { + getAllSessions.mockResolvedValue([{ id: "session-1" }]); + listSessions.mockRejectedValue(new Error("unavailable")); + + const result = await getDeviceAuthorizationRequest("ABCD-1234"); + + expect(setDeviceCodeCheckCookie).toHaveBeenCalledWith("ABCD-1234"); + expect(result.nextUrl).toBe("/loginname?requestId=device_ABCD-1234"); + }); + + test("builds the next url only from the user code", async () => { + const result = await getDeviceAuthorizationRequest("AB&next=https://evil.example"); + + expect(result.nextUrl).toBe("/loginname?requestId=device_AB%26next%3Dhttps%3A%2F%2Fevil.example"); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/oidc.ts b/auth/ui/v2/apps/login/src/lib/actions/oidc.ts new file mode 100644 index 0000000..3a73aae --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/oidc.ts @@ -0,0 +1,51 @@ +"use server"; + +import { getAllSessions } from "@/lib/server/cookies"; +import { setDeviceCodeCheckCookie } from "@/lib/server/device-code-check"; +import { createLogger } from "@/lib/server/logger"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { + listSessions, + ServiceConfig, + getDeviceAuthorizationRequest as zitadelGetDeviceAuthorizationRequest, +} from "@/lib/server/zitadel"; +import { headers } from "next/headers"; + +const logger = createLogger("device-code"); + +// Same rule as flow-initiation.ts for OIDC/SAML: offer the account picker only if +// this browser has at least one live session, otherwise start at /loginname. +async function hasLiveSession(serviceConfig: ServiceConfig): Promise { + const ids = (await getAllSessions()).map((s) => s.id).filter((id) => !!id); + + if (!ids.length) { + return false; + } + + try { + const response = await listSessions({ serviceConfig, ids }); + return (response?.sessions?.length ?? 0) > 0; + } catch (error) { + logger.warn("Failed to load sessions for device flow, falling back to loginname", { error }); + return false; + } +} + +export async function getDeviceAuthorizationRequest(userCode: string) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { deviceAuthorizationRequest } = await zitadelGetDeviceAuthorizationRequest({ serviceConfig, userCode }); + + if (!deviceAuthorizationRequest) { + return { deviceAuthorizationRequest: undefined, nextUrl: undefined }; + } + + await setDeviceCodeCheckCookie(userCode); + + // authenticate first (picker or loginname), consent is asked for afterwards on /device/consent + const path = (await hasLiveSession(serviceConfig)) ? "/accounts" : "/loginname"; + const nextUrl = `${path}?` + new URLSearchParams({ requestId: `device_${userCode}` }); + + return { deviceAuthorizationRequest, nextUrl }; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/otp.test.ts b/auth/ui/v2/apps/login/src/lib/actions/otp.test.ts new file mode 100644 index 0000000..6af070c --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/otp.test.ts @@ -0,0 +1,153 @@ +import { addOTP } from "@/lib/actions/otp"; +import { ClassifiedConnectError } from "@/lib/server/grpc/interceptors/error-classification"; +import { Code, ConnectError } from "@connectrpc/connect"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@/lib/server/zitadel", () => ({ + getSession: vi.fn(), + addOTPEmail: vi.fn(), + addOTPSMS: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), +})); + +vi.mock("@/lib/server/enrollment-guard", () => ({ + getEnrollmentAuthorizationError: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +const session = { + session: { id: "session-1", factors: { user: { id: "user-1", loginName: "user@example.com" } } }, +}; + +describe("addOTP", () => { + let getSessionCookieById: any; + let getSession: any; + let addOTPEmail: any; + let addOTPSMS: any; + let getEnrollmentAuthorizationError: any; + + beforeEach(async () => { + vi.clearAllMocks(); + getSessionCookieById = vi.mocked((await import("@/lib/server/cookies")).getSessionCookieById); + getSession = vi.mocked((await import("@/lib/server/zitadel")).getSession); + addOTPEmail = vi.mocked((await import("@/lib/server/zitadel")).addOTPEmail); + addOTPSMS = vi.mocked((await import("@/lib/server/zitadel")).addOTPSMS); + getEnrollmentAuthorizationError = vi.mocked( + (await import("@/lib/server/enrollment-guard")).getEnrollmentAuthorizationError, + ); + + getSessionCookieById.mockResolvedValue({ id: "session-1", token: "token-1" }); + getSession.mockResolvedValue(session); + getEnrollmentAuthorizationError.mockResolvedValue(null); + }); + + test("returns an error without a session cookie", async () => { + getSessionCookieById.mockResolvedValue(undefined); + + const result = await addOTP({ method: "email", sessionId: "session-1" }); + + expect(result).toEqual({ error: "errors.couldNotGetSession" }); + expect(addOTPEmail).not.toHaveBeenCalled(); + }); + + test("returns an error when the session has no user", async () => { + getSession.mockResolvedValue({ session: { id: "session-1", factors: {} } }); + + const result = await addOTP({ method: "email", sessionId: "session-1" }); + + expect(result).toEqual({ error: "errors.couldNotGetSession" }); + expect(addOTPEmail).not.toHaveBeenCalled(); + }); + + test("rejects an unauthorized (identify-only) session without adding the factor", async () => { + getEnrollmentAuthorizationError.mockResolvedValue("You have to authenticate or have a valid User Verification Check"); + + const result = await addOTP({ method: "sms", sessionId: "session-1" }); + + expect(result).toEqual({ error: "You have to authenticate or have a valid User Verification Check" }); + expect(getEnrollmentAuthorizationError).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://example.com" }, + session: session.session, + userId: "user-1", + }); + expect(addOTPSMS).not.toHaveBeenCalled(); + }); + + test("adds OTP via email for the user of the session", async () => { + addOTPEmail.mockResolvedValue({}); + + const result = await addOTP({ method: "email", sessionId: "session-1" }); + + expect(result).toEqual({ success: true }); + expect(addOTPEmail).toHaveBeenCalledWith({ serviceConfig: { baseUrl: "https://example.com" }, userId: "user-1" }); + expect(addOTPSMS).not.toHaveBeenCalled(); + }); + + test("adds OTP via SMS for the user of the session", async () => { + addOTPSMS.mockResolvedValue({}); + + const result = await addOTP({ method: "sms", sessionId: "session-1" }); + + expect(result).toEqual({ success: true }); + expect(addOTPSMS).toHaveBeenCalledWith({ serviceConfig: { baseUrl: "https://example.com" }, userId: "user-1" }); + expect(addOTPEmail).not.toHaveBeenCalled(); + }); + + test.each([ + ["email", "addOTPEmail"], + ["sms", "addOTPSMS"], + ] as const)("treats an already added OTP via %s as success", async (method, fn) => { + const add = fn === "addOTPEmail" ? addOTPEmail : addOTPSMS; + add.mockRejectedValue(new ClassifiedConnectError(new ConnectError("already ready", Code.AlreadyExists))); + + const result = await addOTP({ method, sessionId: "session-1" }); + + expect(result).toEqual({ success: true }); + }); + + test.each([ + ["email", "addOTPEmail", "errors.emailNotVerified"], + ["sms", "addOTPSMS", "errors.phoneNotVerified"], + ] as const)("asks to verify first when OTP via %s is not ready", async (method, fn, expected) => { + const add = fn === "addOTPEmail" ? addOTPEmail : addOTPSMS; + add.mockRejectedValue(new ClassifiedConnectError(new ConnectError("not ready", Code.FailedPrecondition))); + + const result = await addOTP({ method, sessionId: "session-1" }); + + expect(result).toEqual({ error: expected }); + }); + + test.each([ + ["email", "addOTPEmail", "errors.couldNotAddEmail"], + ["sms", "addOTPSMS", "errors.couldNotAddSms"], + ] as const)("returns an error when the backend rejects adding OTP via %s", async (method, fn, expected) => { + const add = fn === "addOTPEmail" ? addOTPEmail : addOTPSMS; + add.mockRejectedValue(new ClassifiedConnectError(new ConnectError("denied", Code.PermissionDenied))); + + const result = await addOTP({ method, sessionId: "session-1" }); + + expect(result).toEqual({ error: expected }); + }); + + test("rejects an unknown method", async () => { + const result = await addOTP({ method: "time-based" as any, sessionId: "session-1" }); + + expect(result).toEqual({ error: "errors.invalidMethod" }); + expect(addOTPEmail).not.toHaveBeenCalled(); + expect(addOTPSMS).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/otp.ts b/auth/ui/v2/apps/login/src/lib/actions/otp.ts new file mode 100644 index 0000000..e1297df --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/otp.ts @@ -0,0 +1,73 @@ +"use server"; + +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { isClassifiedError } from "@/lib/server/grpc/interceptors/error-classification"; +import { createLogger } from "@/lib/server/logger"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { addOTPEmail, addOTPSMS, getSession } from "@/lib/server/zitadel"; +import { Code } from "@connectrpc/connect"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +const logger = createLogger("otp"); + +type AddOTPCommand = { + method: "email" | "sms"; + sessionId: string; +}; + +/** + * Adds OTP via email or SMS as second factor of the user of the session. + * This must only be called from an explicit user action (never while rendering a page), + * so that a link alone can't change the authentication methods of a signed-in user. + */ +export async function addOTP(command: AddOTPCommand): Promise<{ error: string } | { success: true }> { + const { serviceConfig } = getServiceConfig(await headers()); + const t = await getTranslations("otp"); + + const sessionCookie = await getSessionCookieById({ + sessionId: command.sessionId, + }); + + if (!sessionCookie) { + return { error: t("errors.couldNotGetSession") }; + } + + const session = await getSession({ serviceConfig, sessionId: sessionCookie.id, sessionToken: sessionCookie.token }); + const userId = session?.session?.factors?.user?.id; + + if (!session?.session || !userId) { + return { error: t("errors.couldNotGetSession") }; + } + + // Enrollment must be authorized: a bare identify-only session (only the user factor set) + // must not be able to attach a new authenticator to the account (GHSA-45f2-5q3r-xgg6). + const enrollmentError = await getEnrollmentAuthorizationError({ serviceConfig, session: session.session, userId }); + if (enrollmentError) { + return { error: enrollmentError }; + } + + try { + if (command.method === "email") { + await addOTPEmail({ serviceConfig, userId }); + } else if (command.method === "sms") { + await addOTPSMS({ serviceConfig, userId }); + } else { + return { error: t("errors.invalidMethod") }; + } + } catch (error) { + // the user asked for the factor and already has it (e.g. when coming back to this page) + if (isClassifiedError(error) && error.code === Code.AlreadyExists) { + return { success: true }; + } + // the email address or phone number has to be verified first + if (isClassifiedError(error) && error.code === Code.FailedPrecondition) { + return { error: t(command.method === "email" ? "errors.emailNotVerified" : "errors.phoneNotVerified") }; + } + logger.warn("Could not add OTP", { method: command.method, error }); + return { error: t(command.method === "email" ? "errors.couldNotAddEmail" : "errors.couldNotAddSms") }; + } + + return { success: true }; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/passkeys.test.ts b/auth/ui/v2/apps/login/src/lib/actions/passkeys.test.ts new file mode 100644 index 0000000..0d2f8f5 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/passkeys.test.ts @@ -0,0 +1,721 @@ +import { registerPasskeyLink, sendPasskey } from "@/lib/actions/passkeys"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +// Mock all the dependencies +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("@zitadel/client", () => ({ + create: vi.fn((_schema: unknown, data: unknown) => data), + Duration: vi.fn(), + Timestamp: vi.fn(), + timestampDate: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + getLoginSettings: vi.fn(), + getSession: vi.fn(), + getUserByID: vi.fn(), + listUsers: vi.fn(), + createPasskeyRegistrationLink: vi.fn(), + registerPasskey: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + setSessionAndUpdateCookie: vi.fn(), + createSessionAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), + getSessionCookieByLoginName: vi.fn(), + getMostRecentSessionCookie: vi.fn(), +})); + +vi.mock("@/lib/server/verify-helper", () => ({ + checkEmailVerification: vi.fn(), + checkUserVerification: vi.fn(), +})); + +vi.mock("@/lib/server/host", () => ({ + getPublicHost: vi.fn(), + getPublicHostWithProtocol: vi.fn(() => "https://test.com"), +})); + +vi.mock("@/lib/actions/flow", () => ({ + completeFlowOrGetUrl: vi.fn(), +})); + +// Mock translations - returns the key itself for testing +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +describe("sendPasskey", () => { + let mockHeaders: any; + let mockGetServiceUrlFromHeaders: any; + let mockGetLoginSettings: any; + let mockGetUserByID: any; + let mockListUsers: any; + let mockSetSessionAndUpdateCookie: any; + let mockCreateSessionAndUpdateCookie: any; + let mockGetSessionCookieById: any; + let mockGetSessionCookieByLoginName: any; + let mockGetMostRecentSessionCookie: any; + let mockCheckEmailVerification: any; + let mockCompleteFlowOrGetUrl: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Import mocked modules + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getLoginSettings, getUserByID, listUsers } = await import("@/lib/server/zitadel"); + const { setSessionAndUpdateCookie, createSessionAndUpdateCookie } = await import("@/lib/server/session-cookie"); + const { getSessionCookieById, getSessionCookieByLoginName, getMostRecentSessionCookie } = + await import("@/lib/server/cookies"); + const { checkEmailVerification } = await import("@/lib/server/verify-helper"); + const { completeFlowOrGetUrl } = await import("@/lib/actions/flow"); + const { getPublicHost } = await import("@/lib/server/host"); + + // Setup mocks + mockHeaders = vi.mocked(headers); + mockGetServiceUrlFromHeaders = vi.mocked(getServiceConfig); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockGetUserByID = vi.mocked(getUserByID); + mockListUsers = vi.mocked(listUsers); + mockSetSessionAndUpdateCookie = vi.mocked(setSessionAndUpdateCookie); + mockCreateSessionAndUpdateCookie = vi.mocked(createSessionAndUpdateCookie); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { id: "new-session", factors: { user: { id: "user-1", loginName: "user" } } } as any, + sessionCookie: { id: "new-session", token: "token", loginName: "user" }, + }); + mockGetSessionCookieById = vi.mocked(getSessionCookieById); + mockGetSessionCookieByLoginName = vi.mocked(getSessionCookieByLoginName); + mockGetMostRecentSessionCookie = vi.mocked(getMostRecentSessionCookie); + mockCheckEmailVerification = vi.mocked(checkEmailVerification); + mockCompleteFlowOrGetUrl = vi.mocked(completeFlowOrGetUrl); + vi.mocked(getPublicHost).mockReturnValue("test.com"); + + // Default mock implementations + const headersList = new Headers(); + headersList.set("host", "test.com"); + mockHeaders.mockResolvedValue(headersList); + mockGetServiceUrlFromHeaders.mockReturnValue({ + serviceUrl: "https://example.com", + }); + mockGetLoginSettings.mockResolvedValue({ + multiFactorCheckLifetime: { + seconds: BigInt(300), + nanos: 0, + }, + }); + }); + + describe("Session Cookie Retrieval", () => { + test("should return error when session cookie not found by sessionId", async () => { + mockGetSessionCookieById.mockResolvedValue(null); + + const result = await sendPasskey({ + sessionId: "test-session-id", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "couldNotFindSession", + }); + expect(mockGetSessionCookieById).toHaveBeenCalledWith({ + sessionId: "test-session-id", + }); + }); + + test("should return error when session cookie is not found by loginName", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); // Not found + mockCreateSessionAndUpdateCookie.mockRejectedValue(new Error("Creation failed")); // Force creation failure + + const result = await sendPasskey({ + loginName: "test@example.com", + organization: "org-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "couldNotFindSession", + }); + expect(mockGetSessionCookieByLoginName).toHaveBeenCalledWith({ + loginName: "test@example.com", + organization: "org-123", + }); + }); + + test("should return error when no session cookie found (most recent fallback)", async () => { + mockGetMostRecentSessionCookie.mockResolvedValue(null); + + const result = await sendPasskey({ + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "couldNotFindSession", + }); + expect(mockGetMostRecentSessionCookie).toHaveBeenCalled(); + }); + }); + + describe("Session Update Failures", () => { + beforeEach(() => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "test@example.com", + }); + }); + + test("should return error when setSessionAndUpdateCookie fails", async () => { + mockSetSessionAndUpdateCookie.mockResolvedValue({ + error: "Failed to update session", + }); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "couldNotUpdateSession", + }); + }); + + test("should return error when setSessionAndUpdateCookie returns undefined", async () => { + mockSetSessionAndUpdateCookie.mockResolvedValue(undefined as any); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "couldNotUpdateSession", + }); + }); + + test("should fallback to createSessionAndUpdateCookie when setSessionAndUpdateCookie fails and checks are present", async () => { + mockSetSessionAndUpdateCookie.mockRejectedValue(new Error("session already terminated")); + + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-123", + factors: { + user: { + id: "user-123", + loginName: "test@example.com", + }, + }, + }, + sessionCookie: { + id: "new-session-123", + token: "new-token", + }, + }); + + mockListUsers.mockResolvedValue({ + details: { totalResult: BigInt(1) }, + result: [{ userId: "user-123" }], + }); + + mockGetUserByID.mockResolvedValue({ + user: { + id: "user-123", + type: { + case: "human", + value: { email: { isVerified: true } }, + }, + }, + }); + + mockCheckEmailVerification.mockResolvedValue(true); + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/dashboard" }); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + // It should succeed with the new session + expect(result).toEqual({ + redirect: "/dashboard", + }); + + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); + }); + + describe("User Validation", () => { + beforeEach(() => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "test@example.com", + }); + mockSetSessionAndUpdateCookie.mockResolvedValue({ + sessionId: "session-123", + sessionToken: "new-token", + factors: { + user: { + id: "user-123", + }, + }, + }); + }); + + test("should return error when getUserByID fails", async () => { + mockGetUserByID.mockRejectedValue(new Error("User not found")); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "verify.errors.couldNotGetUser", + }); + }); + }); + + describe("Successful Passkey Verification", () => { + beforeEach(() => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "test@example.com", + }); + mockSetSessionAndUpdateCookie.mockResolvedValue({ + id: "session-123", + factors: { + user: { + id: "user-123", + loginName: "test@example.com", + }, + }, + }); + mockGetUserByID.mockResolvedValue({ + user: { + id: "user-123", + type: { + case: "human", + value: { + email: { + isVerified: true, + }, + }, + }, + }, + }); + mockCheckEmailVerification.mockResolvedValue(true); + }); + + test("should redirect on successful verification without requestId", async () => { + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/dashboard" }); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + redirect: "/dashboard", + }); + }); + + test("should redirect on successful verification with requestId", async () => { + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/auth/callback" }); + + const result = await sendPasskey({ + sessionId: "session-123", + requestId: "request-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + redirect: "/auth/callback", + }); + }); + + test("should redirect for email verification when required", async () => { + mockCheckEmailVerification.mockReturnValue({ redirect: "/verify" }); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toHaveProperty("redirect"); + if ("redirect" in result) { + expect(result.redirect).toContain("/verify"); + } + }); + }); + + describe("Fallback Error Handling - Critical Fix", () => { + beforeEach(() => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "test@example.com", + }); + mockSetSessionAndUpdateCookie.mockResolvedValue({ + id: "session-123", + factors: { + user: { + id: "user-123", + loginName: "test@example.com", + }, + }, + }); + mockGetUserByID.mockResolvedValue({ + user: { + id: "user-123", + type: { + case: "human", + value: { + email: { + isVerified: true, + }, + }, + }, + }, + }); + mockCheckEmailVerification.mockResolvedValue(true); + }); + + test("should return fallback error when completeFlowOrGetUrl returns undefined", async () => { + mockCompleteFlowOrGetUrl.mockResolvedValue(undefined); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "verify.errors.couldNotDetermineRedirect", + }); + }); + + test("should return fallback error when completeFlowOrGetUrl returns empty string", async () => { + mockCompleteFlowOrGetUrl.mockResolvedValue(""); + + const result = await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(result).toEqual({ + error: "verify.errors.couldNotDetermineRedirect", + }); + }); + }); + + describe("Custom Lifetime Handling", () => { + beforeEach(() => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "test@example.com", + }); + mockSetSessionAndUpdateCookie.mockResolvedValue({ + id: "session-123", + factors: { + user: { + id: "user-123", + loginName: "test@example.com", + }, + }, + }); + mockGetUserByID.mockResolvedValue({ + user: { + id: "user-123", + type: { + case: "human", + value: { + email: { + isVerified: true, + }, + }, + }, + }, + }); + mockCheckEmailVerification.mockResolvedValue(true); + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/dashboard" }); + }); + + test("should ignore a caller-supplied lifetime and use the login policy", async () => { + await sendPasskey({ + sessionId: "session-123", + // not part of the command type any more, but a direct POST to the action can still send it + lifetime: { seconds: BigInt(10 * 365 * 24 * 60 * 60), nanos: 0 }, + checks: { webAuthN: { credentialAssertionData: {} } }, + } as any); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalledWith( + expect.objectContaining({ + lifetime: expect.objectContaining({ + seconds: BigInt(300), + }), + }), + ); + }); + + test("should use default lifetime from login settings when not provided", async () => { + await sendPasskey({ + sessionId: "session-123", + checks: { webAuthN: { credentialAssertionData: {} } } as any, + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalledWith( + expect.objectContaining({ + lifetime: expect.objectContaining({ + seconds: BigInt(300), + }), + }), + ); + }); + }); +}); + +describe("registerPasskeyLink", () => { + let mockHeaders: any; + let mockGetServiceConfig: any; + let mockGetSession: any; + let mockGetSessionCookieById: any; + let mockCreatePasskeyRegistrationLink: any; + let mockRegisterPasskey: any; + let mockListAuthenticationMethodTypes: any; + let mockGetPublicHost: any; + let mockCheckUserVerification: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getSession, createPasskeyRegistrationLink, registerPasskey, listAuthenticationMethodTypes } = + await import("@/lib/server/zitadel"); + const { getSessionCookieById } = await import("@/lib/server/cookies"); + const { getPublicHost } = await import("@/lib/server/host"); + const { checkUserVerification } = await import("@/lib/server/verify-helper"); + + mockHeaders = vi.mocked(headers); + mockGetServiceConfig = vi.mocked(getServiceConfig); + mockGetSession = vi.mocked(getSession); + mockGetSessionCookieById = vi.mocked(getSessionCookieById); + mockCreatePasskeyRegistrationLink = vi.mocked(createPasskeyRegistrationLink); + mockRegisterPasskey = vi.mocked(registerPasskey); + mockListAuthenticationMethodTypes = vi.mocked(listAuthenticationMethodTypes); + mockGetPublicHost = vi.mocked(getPublicHost); + mockCheckUserVerification = vi.mocked(checkUserVerification); + + const headersList = new Headers(); + headersList.set("host", "test.com"); + mockHeaders.mockResolvedValue(headersList); + mockGetServiceConfig.mockReturnValue({ serviceConfig: { baseUrl: "https://example.com" } }); + mockGetPublicHost.mockReturnValue("test.com"); + }); + + test("should return error when neither sessionId nor userId is provided", async () => { + const result = await registerPasskeyLink({}); + expect(result).toEqual({ error: "Either sessionId or userId must be provided" }); + }); + + test("should return error when session cookie is not found", async () => { + mockGetSessionCookieById.mockResolvedValue(null); + + const result = await registerPasskeyLink({ sessionId: "session-123" }); + expect(result).toEqual({ error: "Could not get session cookie" }); + }); + + describe("IDP-authenticated session", () => { + const sessionCookie = { + id: "session-123", + token: "session-token", + loginName: "max@zitadel.com", + }; + + const idpSession = { + session: { + id: "session-123", + factors: { + user: { id: "user-123", loginName: "max@zitadel.com" }, + intent: { + verifiedAt: { seconds: BigInt(1700000000), nanos: 0 }, + }, + }, + }, + }; + + test("should succeed for session authenticated via IDP intent", async () => { + mockGetSessionCookieById.mockResolvedValue(sessionCookie); + mockGetSession.mockResolvedValue(idpSession); + mockCreatePasskeyRegistrationLink.mockResolvedValue({ + code: { id: "code-id", code: "code-value" }, + }); + mockRegisterPasskey.mockResolvedValue({ + passkeyId: "passkey-123", + publicKeyCredentialCreationOptions: {}, + }); + + const result = await registerPasskeyLink({ sessionId: "session-123" }); + + expect(result).toHaveProperty("passkeyId"); + expect(mockRegisterPasskey).toHaveBeenCalledWith( + expect.objectContaining({ + userId: "user-123", + domain: "test.com", + }), + ); + }); + + test("should not require user verification or auth method check when IDP session is valid", async () => { + mockGetSessionCookieById.mockResolvedValue(sessionCookie); + mockGetSession.mockResolvedValue(idpSession); + mockCreatePasskeyRegistrationLink.mockResolvedValue({ + code: { id: "code-id", code: "code-value" }, + }); + mockRegisterPasskey.mockResolvedValue({ + passkeyId: "passkey-123", + publicKeyCredentialCreationOptions: {}, + }); + + await registerPasskeyLink({ sessionId: "session-123" }); + + // Should NOT call listAuthenticationMethodTypes or checkUserVerification + // because the session is already valid via IDP intent + expect(mockListAuthenticationMethodTypes).not.toHaveBeenCalled(); + expect(mockCheckUserVerification).not.toHaveBeenCalled(); + }); + }); + + describe("password-authenticated session", () => { + test("should succeed for session authenticated via password", async () => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "max@zitadel.com", + }); + mockGetSession.mockResolvedValue({ + session: { + id: "session-123", + factors: { + user: { id: "user-123", loginName: "max@zitadel.com" }, + password: { + verifiedAt: { seconds: BigInt(1700000000), nanos: 0 }, + }, + }, + }, + }); + mockCreatePasskeyRegistrationLink.mockResolvedValue({ + code: { id: "code-id", code: "code-value" }, + }); + mockRegisterPasskey.mockResolvedValue({ + passkeyId: "passkey-123", + publicKeyCredentialCreationOptions: {}, + }); + + const result = await registerPasskeyLink({ sessionId: "session-123" }); + + expect(result).toHaveProperty("passkeyId"); + }); + }); + + describe("session with no valid factors", () => { + test("should return error when session has no verified factors and user has auth methods", async () => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "max@zitadel.com", + }); + mockGetSession.mockResolvedValue({ + session: { + id: "session-123", + factors: { + user: { id: "user-123", loginName: "max@zitadel.com" }, + // No password, no webAuthN, no intent + }, + }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [1], // has at least one auth method + }); + + const result = await registerPasskeyLink({ sessionId: "session-123" }); + + expect(result).toEqual({ + error: "You have to authenticate or have a valid User Verification Check", + }); + }); + + test("should check user verification when session has no factors and user has no auth methods", async () => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "max@zitadel.com", + }); + mockGetSession.mockResolvedValue({ + session: { + id: "session-123", + factors: { + user: { id: "user-123", loginName: "max@zitadel.com" }, + }, + }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [], + }); + mockCheckUserVerification.mockResolvedValue(false); + + const result = await registerPasskeyLink({ sessionId: "session-123" }); + + expect(result).toEqual({ + error: "User Verification Check has to be done", + }); + expect(mockCheckUserVerification).toHaveBeenCalledWith("user-123"); + }); + + test("should proceed when session has no factors but user verification passes", async () => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session-123", + token: "session-token", + loginName: "max@zitadel.com", + }); + mockGetSession.mockResolvedValue({ + session: { + id: "session-123", + factors: { + user: { id: "user-123", loginName: "max@zitadel.com" }, + }, + }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [], + }); + mockCheckUserVerification.mockResolvedValue(true); + mockCreatePasskeyRegistrationLink.mockResolvedValue({ + code: { id: "code-id", code: "code-value" }, + }); + mockRegisterPasskey.mockResolvedValue({ + passkeyId: "passkey-123", + publicKeyCredentialCreationOptions: {}, + }); + + const result = await registerPasskeyLink({ sessionId: "session-123" }); + + expect(result).toHaveProperty("passkeyId"); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/passkeys.ts b/auth/ui/v2/apps/login/src/lib/actions/passkeys.ts new file mode 100644 index 0000000..79c4929 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/passkeys.ts @@ -0,0 +1,317 @@ +"use server"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { updateOrCreateSession } from "@/lib/actions/session"; +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { getPublicHost } from "@/lib/server/host"; +import { createLogger } from "@/lib/server/logger"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { createSessionAndUpdateCookie } from "@/lib/server/session-cookie"; +import { checkEmailVerification } from "@/lib/server/verify-helper"; +import { + createPasskeyRegistrationLink, + getLoginSettings, + getSession, + getUserByID, + registerPasskey, + verifyPasskeyRegistration as zitadelVerifyPasskeyRegistration, +} from "@/lib/server/zitadel"; +import { create } from "@zitadel/client"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { Checks, ChecksSchema, GetSessionResponse } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { + RegisterPasskeyResponse, + VerifyPasskeyRegistrationRequestSchema, +} from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; +import { userAgent } from "next/server"; + +const logger = createLogger("passkeys"); + +type VerifyPasskeyCommand = { + passkeyId: string; + passkeyName?: string; + publicKeyCredential: any; + sessionId?: string; + userId?: string; +}; + +type RegisterPasskeyCommand = { + sessionId?: string; + userId?: string; + code?: string; + codeId?: string; +}; + +export async function registerPasskeyLink( + command: RegisterPasskeyCommand, +): Promise { + if (!command.sessionId && !command.userId) { + return { error: "Either sessionId or userId must be provided" }; + } + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const host = getPublicHost(_headers); + + let session: GetSessionResponse | undefined; + let createdSession: Session | undefined; + let currentUserId: string | undefined = undefined; + let registerCode: { id: string; code: string } | undefined = undefined; + + if (command.sessionId) { + // Session-based flow (existing logic) + const sessionCookie = await getSessionCookieById({ sessionId: command.sessionId }); + + if (!sessionCookie) { + return { error: "Could not get session cookie" }; + } + + session = await getSession({ serviceConfig, sessionId: sessionCookie.id, sessionToken: sessionCookie.token }); + + if (!session?.session?.factors?.user?.id) { + return { error: "Could not determine user from session" }; + } + + currentUserId = session.session.factors.user.id; + + const enrollmentError = await getEnrollmentAuthorizationError({ + serviceConfig, + session: session.session, + userId: currentUserId, + }); + + if (enrollmentError) { + return { error: enrollmentError }; + } + + // Generate registration code if not provided + if (command.code && command.codeId) { + registerCode = { + id: command.codeId, + code: command.code, + }; + } else { + const codeResponse = await createPasskeyRegistrationLink({ serviceConfig, userId: currentUserId }); + + if (!codeResponse?.code?.code) { + return { error: "Could not create registration link" }; + } + + registerCode = codeResponse.code; + } + } else if (command.userId && command.code && command.codeId) { + currentUserId = command.userId; + registerCode = { + id: command.codeId, + code: command.code, + }; + + // Check if user exists + const userResponse = await getUserByID({ serviceConfig, userId: currentUserId }); + + if (!userResponse || !userResponse.user) { + return { error: "User not found" }; + } + + // Create a session for the user to continue the flow after passkey registration + const checks = create(ChecksSchema, { + user: { + search: { + case: "loginName", + value: userResponse.user.preferredLoginName, + }, + }, + }); + + const result = await createSessionAndUpdateCookie({ + checks, + requestId: undefined, // No requestId in passkey registration context, TODO: consider if needed + }); + createdSession = result.session; + + if (!createdSession) { + return { error: "Could not create session" }; + } + } + + if (!registerCode) { + throw new Error("Missing code in response"); + } + + const [hostname] = host.split(":"); + + if (!hostname) { + throw new Error("Could not get hostname"); + } + + if (!currentUserId) { + throw new Error("Could not determine user"); + } + + return registerPasskey({ serviceConfig, userId: currentUserId, code: registerCode, domain: hostname }); +} + +export async function verifyPasskeyRegistration(command: VerifyPasskeyCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + if (!command.sessionId && !command.userId) { + throw new Error("Either sessionId or userId must be provided"); + } + + // if no name is provided, try to generate one from the user agent + let passkeyName = command.passkeyName; + if (!passkeyName) { + const headersList = await headers(); + const userAgentStructure = { headers: headersList }; + const { browser, device, os } = userAgent(userAgentStructure); + + passkeyName = `${device.vendor ?? ""} ${device.model ?? ""}${ + device.vendor || device.model ? ", " : "" + }${os.name}${os.name ? ", " : ""}${browser.name}`; + } + + let loginName: string | undefined; + let currentUserId: string; + + if (command.sessionId) { + // Session-based flow + const sessionCookie = await getSessionCookieById({ + sessionId: command.sessionId, + }); + + if (!sessionCookie) { + throw new Error("Could not get session cookie"); + } + + const session = await getSession({ serviceConfig, sessionId: sessionCookie.id, sessionToken: sessionCookie.token }); + const userId = session?.session?.factors?.user?.id; + + if (!userId) { + throw new Error("Could not get session"); + } + + currentUserId = userId; + loginName = session?.session?.factors?.user?.loginName; + } else { + // UserId-based flow + currentUserId = command.userId!; + + // Verify user exists + const userResponse = await getUserByID({ serviceConfig, userId: currentUserId }); + + if (!userResponse || !userResponse.user) { + throw new Error("User not found"); + } + + loginName = userResponse.user.preferredLoginName; + } + + const response = await zitadelVerifyPasskeyRegistration({ + serviceConfig, + request: create(VerifyPasskeyRegistrationRequestSchema, { + passkeyId: command.passkeyId, + publicKeyCredential: command.publicKeyCredential, + passkeyName, + userId: currentUserId, + }), + }); + + return { ...response, loginName }; +} + +type SendPasskeyCommand = { + loginName?: string; + sessionId?: string; + organization?: string; + checks?: Checks; + requestId?: string; +}; + +export async function sendPasskey(command: SendPasskeyCommand) { + let { loginName, sessionId, organization, checks, requestId } = command; + + const t = await getTranslations("passkey"); + + const result = await updateOrCreateSession({ + loginName, + sessionId, + organization, + checks, + requestId, + }); + + if (result.error) { + // try to interpret validation errors as translation keys if possible, or fallback to generic + // For now returning the error string directly as key or default + return { error: result.error }; + } + + // transformation to partial session for compatibility + const session = { + id: result.sessionId, + factors: result.factors, + // @ts-ignore + challenges: result.challenges, + }; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const loginSettings = await getLoginSettings({ serviceConfig, organization }); + + const userId = session?.factors?.user?.id; + if (!userId) { + return { error: t("verify.errors.couldNotFindSession") }; + } + + let userResponse; + try { + userResponse = await getUserByID({ serviceConfig, userId }); + } catch (error) { + logger.error("Error fetching user by ID:", { error }); + return { error: t("verify.errors.couldNotGetUser") }; + } + + if (!userResponse.user) { + return { error: t("verify.errors.userNotFound") }; + } + + const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined; + + const emailVerificationCheck = await checkEmailVerification(session as any, humanUser, organization, requestId); + + if (emailVerificationCheck?.redirect) { + return emailVerificationCheck; + } + + let redirectResult; + if (requestId && session.id) { + redirectResult = await completeFlowOrGetUrl( + { + sessionId: session.id, + requestId: requestId, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + } else if (session?.factors?.user?.loginName) { + redirectResult = await completeFlowOrGetUrl( + { + loginName: session.factors.user.loginName, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + } + + // Check if we got a valid redirect result + if (redirectResult && typeof redirectResult === "object") { + return redirectResult; + } + + // Fallback error if we couldn't determine where to redirect + return { error: t("verify.errors.couldNotDetermineRedirect") }; +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/password-send.test.ts b/auth/ui/v2/apps/login/src/lib/actions/password-send.test.ts new file mode 100644 index 0000000..bb19deb --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/password-send.test.ts @@ -0,0 +1,345 @@ +import { sendPassword } from "@/lib/actions/password"; +import { create } from "@zitadel/client"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { UserState } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +// Mock dependencies +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("@zitadel/client", () => ({ + create: vi.fn((schema, data) => data), + ConnectError: class extends Error { + code: number; + constructor(msg: string, code: number) { + super(msg); + this.code = code; + } + }, + timestampDate: (ts: any) => new Date(ts.seconds * 1000), +})); + +vi.mock("@zitadel/client/v2", () => ({ + createUserServiceClient: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + getLoginSettings: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), + getSession: vi.fn(), + setPassword: vi.fn(), + createServerTransport: vi.fn(), + listUsers: vi.fn(), + getLockoutSettings: vi.fn(), + getPasswordExpirySettings: vi.fn(), + getUserByID: vi.fn(), + searchUsers: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieByLoginName: vi.fn(), + getSessionCookieById: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + completeFlowOrGetUrl: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), + setSessionAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/server/verify-helper", () => ({ + checkPasswordChangeRequired: vi.fn(), + checkEmailVerification: vi.fn(), + checkMFAFactors: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +vi.mock("@/lib/server/metrics", () => ({ + recordAuthAttempt: vi.fn(), + recordAuthFailure: vi.fn(), + recordAuthSuccess: vi.fn(), +})); + +describe("sendPassword", () => { + let mockHeaders: any; + let mockGetServiceConfig: any; + let mockGetSessionCookieByLoginName: any; + let mockSearchUsers: any; + let mockGetLoginSettings: any; + let mockCreateSessionAndUpdateCookie: any; + let mockCompleteFlowOrGetUrl: any; + let mockListAuthenticationMethodTypes: any; + let mockCheckMFAFactors: any; + let mockSetSessionAndUpdateCookie: any; + let mockGetUserByID: any; + let mockRecordAuthFailure: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getSessionCookieByLoginName } = await import("@/lib/server/cookies"); + const { getLoginSettings, listAuthenticationMethodTypes, searchUsers, getUserByID } = + await import("@/lib/server/zitadel"); + const { createSessionAndUpdateCookie, setSessionAndUpdateCookie } = await import("@/lib/server/session-cookie"); + const { completeFlowOrGetUrl } = await import("@/lib/actions/flow"); + const { checkMFAFactors } = await import("@/lib/server/verify-helper"); + + mockHeaders = vi.mocked(headers); + mockGetServiceConfig = vi.mocked(getServiceConfig); + mockGetSessionCookieByLoginName = vi.mocked(getSessionCookieByLoginName); + mockSearchUsers = vi.mocked(searchUsers); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockCreateSessionAndUpdateCookie = vi.mocked(createSessionAndUpdateCookie); + mockCompleteFlowOrGetUrl = vi.mocked(completeFlowOrGetUrl); + mockListAuthenticationMethodTypes = vi.mocked(listAuthenticationMethodTypes); + mockCheckMFAFactors = vi.mocked(checkMFAFactors); + mockSetSessionAndUpdateCookie = vi.mocked(setSessionAndUpdateCookie); + mockGetUserByID = vi.mocked(getUserByID); + mockRecordAuthFailure = vi.mocked((await import("@/lib/server/metrics")).recordAuthFailure); + + mockHeaders.mockResolvedValue({}); + mockGetServiceConfig.mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } }); + }); + + test("should create session and verify password when no session exists", async () => { + // 1. No existing session + mockGetSessionCookieByLoginName.mockResolvedValue(null); + + // 2. User exists + mockSearchUsers.mockResolvedValue({ + result: [{ userId: "user123", type: { case: "human", value: {} }, state: UserState.ACTIVE }], + }); + + // 3. Login settings + mockGetLoginSettings.mockResolvedValue({ + passwordCheckLifetime: { seconds: BigInt(86400) }, + allowLocalAuthentication: true, + }); + + // 4. Create session success + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-id", + factors: { + user: { id: "user123", loginName: "testuser", organizationId: "org123" }, + password: { verifiedAt: { seconds: 100 } }, + }, + }, + sessionCookie: { + id: "new-session-id", + token: "token123", + organization: "org123", + }, + }); + + // 5. Auth methods (no MFA) + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + // 6. MFA check passes + mockCheckMFAFactors.mockResolvedValue(null); + + // 7. Redirect + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/next-page" }); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + // Verification + expect(mockSearchUsers).toHaveBeenCalledWith(expect.objectContaining({ searchValue: "testuser" })); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + expect(mockCompleteFlowOrGetUrl).toHaveBeenCalled(); + expect(result).toEqual({ redirect: "/next-page" }); + }); + + const existingCookie = { id: "session-id", token: "token123", loginName: "testuser", organization: "orgB" }; + + test("refuses password when existing session cookie belongs to an org with local auth disabled", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(existingCookie); + mockGetLoginSettings.mockResolvedValue({ + passwordCheckLifetime: { seconds: BigInt(86400) }, + allowLocalAuthentication: false, + }); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ error: "errors.localAuthenticationNotAllowed" }); + expect(mockSetSessionAndUpdateCookie).not.toHaveBeenCalled(); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("updates existing session when the cookie org allows local auth", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(existingCookie); + mockGetLoginSettings.mockResolvedValue({ + passwordCheckLifetime: { seconds: BigInt(86400) }, + allowLocalAuthentication: true, + }); + mockSetSessionAndUpdateCookie.mockResolvedValue({ + id: "session-id", + factors: { + user: { id: "user123", loginName: "testuser", organizationId: "orgB" }, + password: { verifiedAt: { seconds: 100 } }, + }, + }); + mockGetUserByID.mockResolvedValue({ + user: { userId: "user123", type: { case: "human", value: {} }, state: UserState.ACTIVE }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockCheckMFAFactors.mockResolvedValue(null); + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/next-page" }); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalled(); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + expect(result).toEqual({ redirect: "/next-page" }); + }); + + function mockNoSessionUserInOrgB(contextSettings: Record, userOrgSettings: unknown) { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user123", + preferredLoginName: "testuser", + type: { case: "human", value: {} }, + state: UserState.ACTIVE, + details: { resourceOwner: "orgB" }, + }, + ], + }); + mockGetLoginSettings.mockImplementation(async ({ organization }: { organization?: string }) => + organization === "orgB" ? userOrgSettings : contextSettings, + ); + } + + test("refuses password when no session and the user's org has local auth disabled (context org allows)", async () => { + mockNoSessionUserInOrgB({ allowLocalAuthentication: true }, { allowLocalAuthentication: false }); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ error: "errors.localAuthenticationNotAllowed" }); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("masks the refusal when context org ignores unknown usernames", async () => { + mockNoSessionUserInOrgB( + { allowLocalAuthentication: true, ignoreUnknownUsernames: true }, + { allowLocalAuthentication: false }, + ); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticateNoLimit" }); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("fails closed when the user's org login settings cannot be loaded", async () => { + mockNoSessionUserInOrgB({ allowLocalAuthentication: true }, undefined); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ error: "errors.couldNotVerifyPassword" }); + expect(mockRecordAuthFailure).toHaveBeenCalledWith("password", "settings_unavailable", undefined); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("masks the failure to load the user's org settings when context org ignores unknown usernames", async () => { + mockNoSessionUserInOrgB({ allowLocalAuthentication: true, ignoreUnknownUsernames: true }, undefined); + + const result = await sendPassword({ + loginName: "testuser", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticateNoLimit" }); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("records the failure when the context org has local auth disabled", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockGetLoginSettings.mockResolvedValue({ allowLocalAuthentication: false }); + + const result = await sendPassword({ + loginName: "testuser", + organization: "orgA", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ error: "errors.localAuthenticationNotAllowed" }); + expect(mockRecordAuthFailure).toHaveBeenCalledWith("password", "local_auth_not_allowed", "orgA"); + expect(mockSearchUsers).not.toHaveBeenCalled(); + }); + + test("uses the user's org login settings for the later checks", async () => { + const userOrgSettings = { allowLocalAuthentication: true }; + mockNoSessionUserInOrgB({ allowLocalAuthentication: true }, userOrgSettings); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-id", + factors: { + user: { id: "user123", loginName: "testuser", organizationId: "orgB" }, + password: { verifiedAt: { seconds: 100 } }, + }, + }, + sessionCookie: { id: "new-session-id", token: "token123", organization: "orgB" }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + mockCheckMFAFactors.mockResolvedValue(null); + mockCompleteFlowOrGetUrl.mockResolvedValue({ redirect: "/next-page" }); + + const result = await sendPassword({ + loginName: "testuser", + organization: "orgA", + checks: create(ChecksSchema, { password: { password: "password123" } }), + }); + + expect(result).toEqual({ redirect: "/next-page" }); + expect(mockGetLoginSettings).toHaveBeenCalledTimes(2); + expect(mockCheckMFAFactors).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + userOrgSettings, + expect.anything(), + "orgA", + undefined, + ); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/password.test.ts b/auth/ui/v2/apps/login/src/lib/actions/password.test.ts new file mode 100644 index 0000000..b377396 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/password.test.ts @@ -0,0 +1,787 @@ +import { changePassword, checkSessionAndSetPassword, resetPassword, sendPassword } from "@/lib/actions/password"; +import { ClassifiedConnectError } from "@/lib/server/grpc/interceptors/error-classification"; +import { Code, ConnectError } from "@connectrpc/connect"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +// Mock dependencies +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("@zitadel/client", () => ({ + create: vi.fn(), + Code: { FailedPrecondition: 9 }, + ConnectError: class extends Error { + code: number; + constructor(msg: string, code: number) { + super(msg); + this.code = code; + } + }, + timestampDate: (ts: any) => new Date(ts.seconds * 1000), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + getLoginSettings: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), + getSession: vi.fn(), + setPassword: vi.fn(), + createServerTransport: vi.fn(), + getLockoutSettings: vi.fn(), + passwordReset: vi.fn(), + getUserByID: vi.fn(), + setUserPassword: vi.fn(), + getPasswordExpirySettings: vi.fn(), + searchUsers: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), + setSessionAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), + getSessionCookieByLoginName: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +vi.mock("@/lib/server/verify-helper", () => ({ + checkEmailVerification: vi.fn(), + checkMFAFactors: vi.fn(), + checkPasswordChangeRequired: vi.fn(), + checkUserVerification: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + completeFlowOrGetUrl: vi.fn(), +})); + +describe("checkSessionAndSetPassword", () => { + let mockHeaders: any; + let mockGetServiceConfig: any; + let mockGetSessionCookieById: any; + let mockGetSession: any; + let mockListAuthenticationMethodTypes: any; + let mockGetLoginSettings: any; + let mockGetLockoutSettings: any; + let mockSetPassword: any; + let mockSetSessionAndUpdateCookie: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getSessionCookieById } = await import("@/lib/server/cookies"); + const { getSession, listAuthenticationMethodTypes, getLoginSettings, getLockoutSettings, setPassword } = + await import("@/lib/server/zitadel"); + const { setSessionAndUpdateCookie } = await import("@/lib/server/session-cookie"); + + mockHeaders = vi.mocked(headers); + mockGetServiceConfig = vi.mocked(getServiceConfig); + mockGetSessionCookieById = vi.mocked(getSessionCookieById); + mockGetSession = vi.mocked(getSession); + mockListAuthenticationMethodTypes = vi.mocked(listAuthenticationMethodTypes); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockGetLockoutSettings = vi.mocked(getLockoutSettings); + mockSetPassword = vi.mocked(setPassword); + mockSetSessionAndUpdateCookie = vi.mocked(setSessionAndUpdateCookie); + + mockHeaders.mockResolvedValue({}); + mockGetServiceConfig.mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } }); + + // Default session setup + mockGetSessionCookieById.mockResolvedValue({ id: "session123", token: "token123", organization: "org123" }); + mockGetSession.mockResolvedValue({ + session: { + factors: { + user: { id: "user123", organizationId: "org123" }, + password: { verifiedAt: { seconds: Math.floor(Date.now() / 1000) } }, + }, + }, + }); + + // Default: Only password method + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [AuthenticationMethodType.PASSWORD], + }); + + // Default: login settings with password check lifetime + mockGetLoginSettings.mockResolvedValue({ + forceMfa: false, + allowLocalAuthentication: true, + passwordCheckLifetime: { seconds: BigInt(60 * 60 * 24), nanos: 0 }, + }); + + // Default: current password verification succeeds + mockSetSessionAndUpdateCookie.mockResolvedValue({}); + + mockSetPassword.mockResolvedValue({}); + }); + + test("should verify current password and set new password", async () => { + await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalledWith( + expect.objectContaining({ + recentCookie: expect.objectContaining({ id: "session123" }), + }), + ); + expect(mockSetPassword).toHaveBeenCalled(); + }); + + test("should return error when current password is incorrect", async () => { + mockSetSessionAndUpdateCookie.mockRejectedValue(new Error("invalid password")); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "wrongpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "change.errors.currentPasswordInvalid" }); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should return generic error when current password is incorrect and ignoreUnknownUsernames is true", async () => { + mockGetLoginSettings.mockResolvedValue({ + forceMfa: false, + allowLocalAuthentication: true, + passwordCheckLifetime: { seconds: BigInt(60 * 60 * 24), nanos: 0 }, + ignoreUnknownUsernames: true, + }); + mockSetSessionAndUpdateCookie.mockRejectedValue(new Error("invalid password")); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "wrongpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "change.errors.couldNotVerifyPassword" }); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should refuse when the user's org does not allow local authentication", async () => { + mockGetLoginSettings.mockResolvedValue({ + passwordCheckLifetime: { seconds: BigInt(60 * 60 * 24), nanos: 0 }, + allowLocalAuthentication: false, + }); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "errors.localAuthenticationNotAllowed" }); + expect(mockGetLoginSettings).toHaveBeenCalledWith(expect.objectContaining({ organization: "org123" })); + expect(mockSetSessionAndUpdateCookie).not.toHaveBeenCalled(); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should pass requestId from session cookie to setSessionAndUpdateCookie", async () => { + mockGetSessionCookieById.mockResolvedValue({ + id: "session123", + token: "token123", + organization: "org123", + requestId: "oidc-request-456", + }); + + await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalledWith( + expect.objectContaining({ + requestId: "oidc-request-456", + }), + ); + }); + + test("should return lockout error with attempt counts when failedAttempts error is thrown", async () => { + mockSetSessionAndUpdateCookie.mockRejectedValue({ failedAttempts: 3 }); + mockGetLockoutSettings.mockResolvedValue({ maxPasswordAttempts: BigInt(5) }); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "wrongpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticate" }); + expect(mockGetLockoutSettings).toHaveBeenCalled(); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should return generic error for failedAttempts when ignoreUnknownUsernames is true", async () => { + mockGetLoginSettings.mockResolvedValue({ + forceMfa: false, + allowLocalAuthentication: true, + passwordCheckLifetime: { seconds: BigInt(60 * 60 * 24), nanos: 0 }, + ignoreUnknownUsernames: true, + }); + mockSetSessionAndUpdateCookie.mockRejectedValue({ failedAttempts: 3 }); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "wrongpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticateNoLimit" }); + expect(mockGetLockoutSettings).not.toHaveBeenCalled(); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should return error when session cookie not found", async () => { + mockGetSessionCookieById.mockResolvedValue(null); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "Could not load session cookie" }); + expect(mockSetSessionAndUpdateCookie).not.toHaveBeenCalled(); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should return error when session has no user", async () => { + mockGetSession.mockResolvedValue({ + session: { factors: {} }, + }); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "errors.couldNotLoadSession" }); + expect(mockSetPassword).not.toHaveBeenCalled(); + }); + + test("should use default lifetime when login settings have no passwordCheckLifetime", async () => { + mockGetLoginSettings.mockResolvedValue({ forceMfa: false, allowLocalAuthentication: true }); + + await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalledWith( + expect.objectContaining({ + lifetime: expect.objectContaining({ seconds: BigInt(60 * 60 * 24) }), + }), + ); + expect(mockSetPassword).toHaveBeenCalled(); + }); + + test("should handle setPassword failure with failed precondition", async () => { + // Use real ConnectError + ClassifiedConnectError to match runtime behavior + // where the error-classification interceptor wraps transport errors. + const classifiedError = new ClassifiedConnectError( + new ConnectError("User is not yet initialized", Code.FailedPrecondition), + ); + mockSetPassword.mockRejectedValue(classifiedError); + + const result = await checkSessionAndSetPassword({ + sessionId: "session123", + currentPassword: "oldpassword", + password: "newpassword", + }); + + expect(result).toEqual({ error: "errors.failedPrecondition" }); + }); +}); + +describe("sendPassword", () => { + let mockHeaders: any; + let mockGetServiceConfig: any; + let mockGetSessionCookieByLoginName: any; + let mockSearchUsers: any; + let mockGetLoginSettings: any; + let mockCreateSessionAndUpdateCookie: any; + let mockSetSessionAndUpdateCookie: any; + let mockGetLockoutSettings: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getSessionCookieByLoginName } = await import("@/lib/server/cookies"); + const { getLoginSettings, getLockoutSettings, searchUsers } = await import("@/lib/server/zitadel"); + const { createSessionAndUpdateCookie, setSessionAndUpdateCookie } = await import("@/lib/server/session-cookie"); + + mockHeaders = vi.mocked(headers); + mockGetServiceConfig = vi.mocked(getServiceConfig); + mockGetSessionCookieByLoginName = vi.mocked(getSessionCookieByLoginName); + mockSearchUsers = vi.mocked(searchUsers); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockCreateSessionAndUpdateCookie = vi.mocked(createSessionAndUpdateCookie); + mockSetSessionAndUpdateCookie = vi.mocked(setSessionAndUpdateCookie); + mockCreateSessionAndUpdateCookie = vi.mocked(createSessionAndUpdateCookie); + mockSetSessionAndUpdateCookie = vi.mocked(setSessionAndUpdateCookie); + mockGetLockoutSettings = vi.mocked(getLockoutSettings); + + const { completeFlowOrGetUrl } = await import("@/lib/actions/flow"); + vi.mocked(completeFlowOrGetUrl).mockResolvedValue({ redirect: "https://example.com" }); + + const verifyHelper = await import("@/lib/server/verify-helper"); + vi.mocked(verifyHelper.checkPasswordChangeRequired).mockReturnValue(undefined); + vi.mocked(verifyHelper.checkEmailVerification).mockReturnValue(undefined); + vi.mocked(verifyHelper.checkMFAFactors).mockResolvedValue(undefined); + + mockHeaders.mockResolvedValue({}); + mockGetServiceConfig.mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } }); + }); + + test("should return generic error when user not found and ignoreUnknownUsernames is true", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ result: [] }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: true, allowLocalAuthentication: true }); + + const result = await sendPassword({ + loginName: "unknown@example.com", + checks: { password: { password: "password" } } as any, + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticateNoLimit" }); + }); + + test("should return specific error when user not found and ignoreUnknownUsernames is false", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ result: [] }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: false, allowLocalAuthentication: true }); + + const result = await sendPassword({ + loginName: "unknown@example.com", + checks: { password: { password: "password" } } as any, + }); + + expect(result).toEqual({ error: "errors.couldNotVerifyPassword" }); + }); + + test("should return generic error when password verification fails and ignoreUnknownUsernames is true", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [{ userId: "user123", type: { case: "human", value: {} }, state: 1 }], + }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: true, allowLocalAuthentication: true }); + mockCreateSessionAndUpdateCookie.mockRejectedValue({ failedAttempts: 1 }); + + const result = await sendPassword({ + loginName: "user@example.com", + checks: { password: { password: "wrong" } } as any, + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticateNoLimit" }); + }); + + test("should return generic error when session creation fails with unknown error and ignoreUnknownUsernames is true", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [{ userId: "user123", type: { case: "human", value: {} }, state: 1 }], + }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: true, allowLocalAuthentication: true }); + // Simulate an error that is NOT a failed attempt error (e.g. database error) + mockCreateSessionAndUpdateCookie.mockRejectedValue(new Error("Some internal error")); + + const result = await sendPassword({ + loginName: "user@example.com", + checks: { password: { password: "correct" } } as any, + }); + + expect(result).toEqual({ error: "errors.failedToAuthenticateNoLimit" }); + }); + + // Regression tests for: https://github.com/zitadel/zitadel/issues/12025 + // User discovery is case insensitive, so the post-discovery check that verifies *which* + // identifier the user was found by must ignore case too. Otherwise "Jackson@Example.com" + // resolves the user and is then rejected as unknown. + test("should accept a differently cased login name when login with email and phone are disabled", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user123", + preferredLoginName: "jackson@example.com", + type: { case: "human", value: {} }, + state: 1, + }, + ], + }); + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: true, + disableLoginWithEmail: true, + disableLoginWithPhone: true, + }); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { factors: { user: { id: "user123" } } }, + sessionCookie: { id: "session123" }, + }); + + const result = await sendPassword({ + loginName: "Jackson@Example.com", + checks: { password: { password: "password" } } as any, + }); + + expect(result).toEqual({ redirect: "https://example.com" }); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); + + test("should accept a differently cased email when login with email is disabled", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user123", + preferredLoginName: "jackson", + type: { case: "human", value: { phone: { phone: "+41791234567" } } }, + state: 1, + }, + ], + }); + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: true, + disableLoginWithPhone: true, + }); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { factors: { user: { id: "user123" } } }, + sessionCookie: { id: "session123" }, + }); + + const result = await sendPassword({ + loginName: "Jackson", + checks: { password: { password: "password" } } as any, + }); + + expect(result).toEqual({ redirect: "https://example.com" }); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); + + test("should still reject a login name that does not match the discovered user", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user123", + preferredLoginName: "jackson@example.com", + type: { case: "human", value: {} }, + state: 1, + }, + ], + }); + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: true, + disableLoginWithEmail: true, + disableLoginWithPhone: true, + }); + + const result = await sendPassword({ + loginName: "someone-else@example.com", + checks: { password: { password: "password" } } as any, + }); + + expect(result).toEqual({ error: "errors.couldNotVerifyPassword" }); + expect(mockCreateSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("should return specific error with lockout info when password verification fails and ignoreUnknownUsernames is false", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue(null); + mockSearchUsers.mockResolvedValue({ + result: [{ userId: "user123", type: { case: "human", value: {} }, state: 1 }], + }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: false, allowLocalAuthentication: true }); + mockCreateSessionAndUpdateCookie.mockRejectedValue({ failedAttempts: 1 }); + mockGetLockoutSettings.mockResolvedValue({ maxPasswordAttempts: BigInt(5) }); + + const result = await sendPassword({ + loginName: "user@example.com", + checks: { password: { password: "wrong" } } as any, + }); + + expect(result).toEqual({ + error: "errors.failedToAuthenticate", + }); + }); + + test("should forward only the password check when updating an existing session", async () => { + const { create } = await import("@zitadel/client"); + vi.mocked(create).mockImplementation((_schema: any, value: any) => value); + + mockGetSessionCookieByLoginName.mockResolvedValue({ + id: "session123", + token: "token123", + organization: "org123", + }); + mockGetLoginSettings.mockResolvedValue({ + allowLocalAuthentication: true, + passwordCheckLifetime: { seconds: BigInt(864000), nanos: 0 }, + }); + mockSetSessionAndUpdateCookie.mockResolvedValue({ + factors: { user: { id: "user123", loginName: "user@example.com" } }, + }); + const { getUserByID } = await import("@/lib/server/zitadel"); + vi.mocked(getUserByID).mockResolvedValue({} as any); + + // a direct POST can send any checks next to the password + await sendPassword({ + loginName: "user@example.com", + checks: { + password: { password: "password" }, + totp: { code: "123456" }, + user: { search: { case: "userId", value: "other-user" } }, + } as any, + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalledWith( + expect.objectContaining({ + checks: { password: { password: "password" } }, + lifetime: { seconds: BigInt(864000), nanos: 0 }, + }), + ); + }); + + test("should recreate session when session verification fails with keys/session terminated error and ignoreUnknownUsernames is true", async () => { + mockGetSessionCookieByLoginName.mockResolvedValue({ + id: "session123", + token: "token123", + organization: "org123", + }); + + const terminatedError = { message: "session already terminated" }; + mockSetSessionAndUpdateCookie.mockRejectedValue(terminatedError); + + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: true, allowLocalAuthentication: true }); + + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user123", + type: { + case: "human", + value: { + email: { email: "user@example.com", isVerified: true }, + phone: { phone: "+1234567890", isVerified: true }, + }, + }, + state: 1, // Active + preferredLoginName: "user@example.com", + }, + ], + }); + + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { factors: { user: { id: "user123", loginName: "user@example.com" } } }, + sessionCookie: { id: "newSession", token: "newToken" }, + }); + + // Execute + await sendPassword({ + loginName: "user@example.com", + checks: { password: { password: "password" } } as any, + }); + + expect(mockSetSessionAndUpdateCookie).toHaveBeenCalled(); + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + }); +}); +describe("resetPassword", () => { + let mockHeaders: any; + let mockGetServiceConfig: any; + let mockSearchUsers: any; + let mockGetLoginSettings: any; + let mockPasswordReset: any; + let mockGetTranslations: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { headers } = await import("next/headers"); + const { getTranslations } = await import("next-intl/server"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getLoginSettings, passwordReset, searchUsers } = await import("@/lib/server/zitadel"); + + mockHeaders = vi.mocked(headers); + mockGetTranslations = vi.mocked(getTranslations); + mockGetServiceConfig = vi.mocked(getServiceConfig); + mockSearchUsers = vi.mocked(searchUsers); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockPasswordReset = vi.mocked(passwordReset); + + mockHeaders.mockResolvedValue({ get: vi.fn(() => "example.com") }); + mockGetTranslations.mockResolvedValue((key: string) => key); + mockGetServiceConfig.mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } }); + }); + + test("should return translated password reset not allowed error when hidePasswordReset is true", async () => { + mockGetLoginSettings.mockResolvedValue({ hidePasswordReset: true }); + mockGetTranslations.mockResolvedValue((key: string) => { + if (key === "errors.passwordResetNotAllowed") { + return "translated-password-reset-not-allowed"; + } + return key; + }); + + const result = await resetPassword({ + loginName: "user@example.com", + }); + + expect(result).toEqual({ error: "translated-password-reset-not-allowed" }); + expect(mockSearchUsers).not.toHaveBeenCalled(); + expect(mockPasswordReset).not.toHaveBeenCalled(); + }); + + test("should return generic success when user not found and ignoreUnknownUsernames is true", async () => { + mockSearchUsers.mockResolvedValue({ result: [] }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: true }); + + const result = await resetPassword({ + loginName: "unknown@example.com", + }); + + expect(result).toEqual({}); + expect(mockPasswordReset).not.toHaveBeenCalled(); + }); + + test("should return specific error when user not found and ignoreUnknownUsernames is false", async () => { + mockSearchUsers.mockResolvedValue({ result: [] }); + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: false }); + + const result = await resetPassword({ + loginName: "unknown@example.com", + }); + + expect(result).toEqual({ error: "errors.couldNotSendResetLink" }); + expect(mockPasswordReset).not.toHaveBeenCalled(); + }); + + // Regression tests for: https://github.com/zitadel/zitadel/issues/12025 + // See the equivalent sendPassword tests above; the same post-discovery check guards the reset link. + test("should send the reset link for a differently cased login name when login with email and phone are disabled", async () => { + mockSearchUsers.mockResolvedValue({ + result: [{ userId: "user123", preferredLoginName: "jackson@example.com", type: { case: "human", value: {} } }], + }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithEmail: true, + disableLoginWithPhone: true, + }); + mockPasswordReset.mockResolvedValue({}); + + const result = await resetPassword({ + loginName: "Jackson@Example.com", + }); + + expect(result).toEqual({}); + expect(mockPasswordReset).toHaveBeenCalledWith(expect.objectContaining({ userId: "user123" })); + }); + + test("should send the reset link for a differently cased email when login with phone is disabled", async () => { + mockSearchUsers.mockResolvedValue({ + result: [ + { + userId: "user123", + preferredLoginName: "jackson", + type: { case: "human", value: { email: { email: "jackson@example.com" } } }, + }, + ], + }); + mockGetLoginSettings.mockResolvedValue({ disableLoginWithPhone: true }); + mockPasswordReset.mockResolvedValue({}); + + const result = await resetPassword({ + loginName: "Jackson@Example.com", + }); + + expect(result).toEqual({}); + expect(mockPasswordReset).toHaveBeenCalledWith(expect.objectContaining({ userId: "user123" })); + }); + + test("should still reject a login name that does not match the discovered user", async () => { + mockSearchUsers.mockResolvedValue({ + result: [{ userId: "user123", preferredLoginName: "jackson@example.com", type: { case: "human", value: {} } }], + }); + mockGetLoginSettings.mockResolvedValue({ + disableLoginWithEmail: true, + disableLoginWithPhone: true, + }); + + const result = await resetPassword({ + loginName: "someone-else@example.com", + }); + + expect(result).toEqual({ error: "errors.couldNotSendResetLink" }); + expect(mockPasswordReset).not.toHaveBeenCalled(); + }); +}); + +describe("changePassword", () => { + let mockHeaders: any; + let mockGetServiceConfig: any; + let mockGetUserByID: any; + let mockGetLoginSettings: any; + let mockSetUserPassword: any; + + beforeEach(async () => { + vi.clearAllMocks(); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { getUserByID, getLoginSettings, setUserPassword } = await import("@/lib/server/zitadel"); + + mockHeaders = vi.mocked(headers); + mockGetServiceConfig = vi.mocked(getServiceConfig); + mockGetUserByID = vi.mocked(getUserByID); + mockGetLoginSettings = vi.mocked(getLoginSettings); + mockSetUserPassword = vi.mocked(setUserPassword); + + mockHeaders.mockResolvedValue({ get: vi.fn(() => "example.com") }); + mockGetServiceConfig.mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } }); + }); + + test("should return generic error when user not found and ignoreUnknownUsernames is true", async () => { + mockGetUserByID.mockResolvedValue({}); // User not found + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: true }); + + const result = await changePassword({ + userId: "unknown", + password: "newpassword", + }); + + expect(result).toEqual({ error: "set.errors.couldNotSetPassword" }); + expect(mockSetUserPassword).not.toHaveBeenCalled(); + }); + + test("should return specific error when user not found and ignoreUnknownUsernames is false", async () => { + mockGetUserByID.mockResolvedValue({}); // User not found + mockGetLoginSettings.mockResolvedValue({ ignoreUnknownUsernames: false }); + + const result = await changePassword({ + userId: "unknown", + password: "newpassword", + }); + + expect(result).toEqual({ error: "errors.couldNotSendResetLink" }); + expect(mockSetUserPassword).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/password.ts b/auth/ui/v2/apps/login/src/lib/actions/password.ts new file mode 100644 index 0000000..0d03048 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/password.ts @@ -0,0 +1,640 @@ +"use server"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { equalsIgnoreCase } from "@/lib/server/auth-utils"; +import { getSessionCookieById, getSessionCookieByLoginName } from "@/lib/server/cookies"; +import { isClassifiedError } from "@/lib/server/grpc/interceptors/error-classification"; +import { getPublicHostWithProtocol } from "@/lib/server/host"; +import { createLogger } from "@/lib/server/logger"; +import { recordAuthAttempt, recordAuthFailure, recordAuthSuccess } from "@/lib/server/metrics"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { createSessionAndUpdateCookie, setSessionAndUpdateCookie } from "@/lib/server/session-cookie"; +import { + checkEmailVerification, + checkMFAFactors, + checkPasswordChangeRequired, + checkUserVerification, +} from "@/lib/server/verify-helper"; +import { + getLockoutSettings, + getLoginSettings, + getPasswordExpirySettings, + getSession, + getUserByID, + listAuthenticationMethodTypes, + passwordReset, + searchUsers, + setPassword, + setUserPassword, +} from "@/lib/server/zitadel"; +import { Code, create, Duration } from "@zitadel/client"; +import { Checks, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { User, UserState } from "@zitadel/proto/zitadel/user/v2/user_pb"; +import { SetPasswordRequestSchema } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +const logger = createLogger("password"); + +type ResetPasswordCommand = { + loginName: string; + organization?: string; + defaultOrganization?: string; + requestId?: string; +}; + +export async function resetPassword(command: ResetPasswordCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const t = await getTranslations("password"); + + // Get the original host that the user sees with protocol + const hostWithProtocol = await getPublicHostWithProtocol(_headers); + + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: command.organization ?? command.defaultOrganization, + }); + + if (!loginSettings) { + return { error: t("errors.couldNotSendResetLink") }; + } + + if (loginSettings.hidePasswordReset) { + return { error: t("errors.passwordResetNotAllowed") }; + } + + const searchResult = await searchUsers({ + serviceConfig, + searchValue: command.loginName, + organizationId: command.organization, + loginSettings, + }); + + if ( + !searchResult || + !("result" in searchResult) || + !searchResult.result || + searchResult.result.length !== 1 || + !searchResult.result[0].userId + ) { + if (loginSettings?.ignoreUnknownUsernames) { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return {}; + } + return { error: t("errors.couldNotSendResetLink") }; + } + const user = searchResult.result[0]; + const humanUser = user.type.case === "human" ? user.type.value : undefined; + + const userLoginSettings = await getLoginSettings({ serviceConfig, organization: user.details?.resourceOwner }); + + if (userLoginSettings?.disableLoginWithEmail && userLoginSettings?.disableLoginWithPhone) { + if (!equalsIgnoreCase(user.preferredLoginName, command.loginName)) { + if (userLoginSettings?.ignoreUnknownUsernames) { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return {}; + } + return { error: t("errors.couldNotSendResetLink") }; + } + } else if (userLoginSettings?.disableLoginWithEmail) { + if ( + !equalsIgnoreCase(user.preferredLoginName, command.loginName) && + !equalsIgnoreCase(humanUser?.phone?.phone, command.loginName) + ) { + if (userLoginSettings?.ignoreUnknownUsernames) { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return {}; + } + return { error: t("errors.couldNotSendResetLink") }; + } + } else if (userLoginSettings?.disableLoginWithPhone) { + if ( + !equalsIgnoreCase(user.preferredLoginName, command.loginName) && + !equalsIgnoreCase(humanUser?.email?.email, command.loginName) + ) { + if (userLoginSettings?.ignoreUnknownUsernames) { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return {}; + } + return { error: t("errors.couldNotSendResetLink") }; + } + } + + const userId = user.userId; + const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; + + return passwordReset({ + serviceConfig, + userId, + urlTemplate: + `${hostWithProtocol}${basePath}/password/set?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` + + (command.requestId ? `&requestId=${command.requestId}` : ""), + }); +} + +export type UpdateSessionCommand = { + loginName: string; + organization?: string; + defaultOrganization?: string; + checks: Checks; + requestId?: string; +}; + +export async function sendPassword( + command: UpdateSessionCommand, +): Promise<{ error: string } | { redirect: string } | { samlData: { url: string; fields: Record } }> { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const t = await getTranslations("password"); + + recordAuthAttempt("password", command.organization); + + let sessionCookie = await getSessionCookieByLoginName({ + loginName: command.loginName, + organization: command.organization, + }); + + let session; + let user: User | undefined; + let loginSettingsByContext: LoginSettings | undefined; + let loginSettingsByUser: LoginSettings | undefined; + + // Perform policy check on context settings first if available, or fetch them if needed + if (!sessionCookie) { + if (!loginSettingsByContext) { + loginSettingsByContext = await getLoginSettings({ + serviceConfig, + organization: command.organization ?? command.defaultOrganization, + }); + } + + if (loginSettingsByContext && !loginSettingsByContext.allowLocalAuthentication) { + recordAuthFailure("password", "local_auth_not_allowed", command.organization); + return { error: t("errors.localAuthenticationNotAllowed") }; + } + } + + if (sessionCookie) { + try { + loginSettingsByUser = await getLoginSettings({ serviceConfig, organization: sessionCookie.organization }); + + if (loginSettingsByUser) { + if (!loginSettingsByUser.allowLocalAuthentication) { + recordAuthFailure("password", "local_auth_not_allowed", command.organization); + return { error: t("errors.localAuthenticationNotAllowed") }; + } + + let lifetime = loginSettingsByUser.passwordCheckLifetime; + + if (!lifetime || !lifetime.seconds) { + logger.warn("No password lifetime provided, defaulting to 24 hours"); + lifetime = { + seconds: BigInt(60 * 60 * 24), // default to 24 hours + nanos: 0, + } as Duration; + } + + session = await setSessionAndUpdateCookie({ + recentCookie: sessionCookie, + // Only the password check: any other check the caller sends would get the password check lifetime. + checks: create(ChecksSchema, { + password: { password: command.checks.password?.password }, + }), + requestId: command.requestId, + lifetime, + }); + } else { + // Force fallback if settings can't be loaded + throw new Error("Could not load login settings"); + } + } catch { + logger.warn("[Password] Could not update session"); + // If the session was terminated or any other error occurred during update, + // we fall back to creating a new session. + sessionCookie = undefined; + session = undefined; + } + } + + if (!sessionCookie) { + if (!loginSettingsByContext) { + loginSettingsByContext = await getLoginSettings({ + serviceConfig, + organization: command.organization ?? command.defaultOrganization, + }); + } + + // Force fallback if settings can't be loaded + if (!loginSettingsByContext) { + // this is a fake error message to hide that the user does not even exist + recordAuthFailure("password", "settings_unavailable", command.organization); + return { error: t("errors.couldNotVerifyPassword") }; + } + + const searchResult = await searchUsers({ + serviceConfig, + searchValue: command.loginName, + organizationId: command.organization, + loginSettings: loginSettingsByContext, + }); + + if ( + searchResult && + "result" in searchResult && + searchResult.result && + searchResult.result.length === 1 && + searchResult.result[0].userId + ) { + user = searchResult.result[0]; + const humanUser = user.type.case === "human" ? user.type.value : undefined; + + const userLoginSettings = await getLoginSettings({ serviceConfig, organization: user.details?.resourceOwner }); + + if (!userLoginSettings) { + recordAuthFailure("password", "settings_unavailable", command.organization); + return { + error: t( + loginSettingsByContext.ignoreUnknownUsernames + ? "errors.failedToAuthenticateNoLimit" + : "errors.couldNotVerifyPassword", + ), + }; + } + if (!userLoginSettings.allowLocalAuthentication) { + recordAuthFailure("password", "local_auth_not_allowed", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.localAuthenticationNotAllowed") }; + } + loginSettingsByUser = userLoginSettings; + + // recheck login settings after user discovery, as the search might have been done without org scope + if (userLoginSettings.disableLoginWithEmail && userLoginSettings.disableLoginWithPhone) { + if (!equalsIgnoreCase(user.preferredLoginName, command.loginName)) { + // emulate user not found to prevent enumeration (use context settings not user settings) + recordAuthFailure("password", "login_name_mismatch", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotVerifyPassword") }; + } + } else if (userLoginSettings.disableLoginWithEmail) { + if ( + !equalsIgnoreCase(user.preferredLoginName, command.loginName) && + !equalsIgnoreCase(humanUser?.phone?.phone, command.loginName) + ) { + recordAuthFailure("password", "login_name_mismatch", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotVerifyPassword") }; + } + } else if (userLoginSettings.disableLoginWithPhone) { + if ( + !equalsIgnoreCase(user.preferredLoginName, command.loginName) && + !equalsIgnoreCase(humanUser?.email?.email, command.loginName) + ) { + recordAuthFailure("password", "login_name_mismatch", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotVerifyPassword") }; + } + } + + const checks = create(ChecksSchema, { + user: { search: { case: "userId", value: user.userId } }, + password: { password: command.checks.password?.password }, + }); + + try { + const result = await createSessionAndUpdateCookie({ + checks, + requestId: command.requestId, + lifetime: loginSettingsByContext?.passwordCheckLifetime, + }); + session = result.session; + sessionCookie = result.sessionCookie; + } catch (error: any) { + if ("failedAttempts" in error && error.failedAttempts) { + recordAuthFailure("password", "invalid_password", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + const lockoutSettings = await getLockoutSettings({ serviceConfig, orgId: command.organization }); + + const hasLimit = + lockoutSettings?.maxPasswordAttempts !== undefined && lockoutSettings?.maxPasswordAttempts > BigInt(0); + const locked = hasLimit && error.failedAttempts >= lockoutSettings?.maxPasswordAttempts; + const messageKey = hasLimit ? "errors.failedToAuthenticate" : "errors.failedToAuthenticateNoLimit"; + + return { + error: t(messageKey, { + failedAttempts: error.failedAttempts, + maxPasswordAttempts: hasLimit ? String(lockoutSettings?.maxPasswordAttempts ?? 0) : "?", + lockoutMessage: locked ? t("errors.accountLockedContactAdmin") : "", + }), + }; + } + recordAuthFailure("password", "session_creation_failed", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotCreateSessionForUser") }; + } + } else { + // this is a fake error message to hide that the user does not even exist + recordAuthFailure("password", "user_not_found", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotVerifyPassword") }; + } + } + + if (!session?.factors?.user?.id) { + recordAuthFailure("password", "session_invalid", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotCreateSessionForUser") }; + } + + if (!user) { + const userResponse = await getUserByID({ serviceConfig, userId: session?.factors?.user?.id }); + if (!userResponse.user) { + recordAuthFailure("password", "user_not_found", command.organization); + return { error: t("errors.userNotFound") }; + } + user = userResponse.user; + } + + if (!session?.factors?.user?.id || !sessionCookie) { + recordAuthFailure("password", "session_invalid", command.organization); + if (loginSettingsByContext?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + return { error: t("errors.couldNotCreateSessionForUser") }; + } + + if (!loginSettingsByUser) { + loginSettingsByUser = await getLoginSettings({ + serviceConfig, + organization: command.organization ?? session.factors?.user?.organizationId ?? command.defaultOrganization, + }); + } + + const humanUser = user.type.case === "human" ? user.type.value : undefined; + + const expirySettings = await getPasswordExpirySettings({ + serviceConfig, + orgId: command.organization ?? session.factors?.user?.organizationId, + }); + + // check if the user has to change password first + const passwordChangedCheck = checkPasswordChangeRequired( + expirySettings, + session, + humanUser, + command.organization, + command.requestId, + ); + + if (passwordChangedCheck?.redirect) { + return passwordChangedCheck; + } + + // throw error if user is in initial state here and do not continue + if (user.state === UserState.INITIAL) { + recordAuthFailure("password", "user_initial_state", command.organization); + return { error: t("errors.initialUserNotSupported") }; + } + + // check to see if user was verified + const emailVerificationCheck = await checkEmailVerification(session, humanUser, command.organization, command.requestId); + + if (emailVerificationCheck?.redirect) { + return emailVerificationCheck; + } + + // if password, check if user has MFA methods + let authMethods; + if (command.checks && command.checks.password && session.factors?.user?.id) { + const response = await listAuthenticationMethodTypes({ serviceConfig, userId: session.factors.user.id }); + if (response.authMethodTypes && response.authMethodTypes.length) { + authMethods = response.authMethodTypes; + } + } + + if (!authMethods) { + recordAuthFailure("password", "no_auth_methods", command.organization); + return { error: t("errors.couldNotVerifyPassword") }; + } + + const mfaFactorCheck = await checkMFAFactors( + serviceConfig, + session, + loginSettingsByUser, + authMethods, + command.organization, + command.requestId, + ); + + if (mfaFactorCheck?.redirect) { + return mfaFactorCheck; + } + + let result: Awaited>; + + if (command.requestId && session.id) { + // OIDC/SAML flow + logger.info("Password auth: OIDC/SAML flow with requestId:", { requestId: command.requestId, sessionId: session.id }); + result = await completeFlowOrGetUrl( + { + sessionId: session.id, + requestId: command.requestId, + organization: command.organization ?? session.factors?.user?.organizationId, + }, + loginSettingsByUser?.defaultRedirectUri, + ); + } else { + // Regular flow (no requestId) + logger.info("Password auth: Regular flow with loginName:", { loginName: session.factors.user.loginName }); + result = await completeFlowOrGetUrl( + { + loginName: session.factors.user.loginName, + organization: session.factors?.user?.organizationId, + }, + loginSettingsByUser?.defaultRedirectUri, + ); + } + + if (result && typeof result === "object") { + if ("redirect" in result) { + recordAuthSuccess("password", command.organization); + } else if ("error" in result) { + recordAuthFailure("password", "flow_error", command.organization); + } + return result; + } + + recordAuthFailure("password", "navigation_failed", command.organization); + return { error: "Authentication completed but navigation failed" }; +} + +// this function lets users with code set a password or users with valid User Verification Check +export async function changePassword(command: { code?: string; userId: string; password: string; organization?: string }) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const t = await getTranslations("password"); + + // check for init state + const { user } = await getUserByID({ serviceConfig, userId: command.userId }); + + if (!user || user.userId !== command.userId) { + const loginSettings = await getLoginSettings({ serviceConfig, organization: command.organization }); + if (loginSettings?.ignoreUnknownUsernames) { + return { error: t("set.errors.couldNotSetPassword") }; + } + return { error: t("errors.couldNotSendResetLink") }; + } + const userId = user.userId; + + if (user.state === UserState.INITIAL) { + return { error: t("errors.userInitialStateNotSupported") }; + } + + // check if the user has no password set in order to set a password + if (!command.code) { + const authmethods = await listAuthenticationMethodTypes({ serviceConfig, userId }); + + // if the user has no authmethods set, we need to check if the user was verified + if (authmethods.authMethodTypes.length !== 0) { + return { + error: t("errors.codeOrVerificationRequired"), + }; + } + + // check if a verification was done earlier + const hasValidUserVerificationCheck = await checkUserVerification(user.userId); + + if (!hasValidUserVerificationCheck) { + return { error: t("errors.verificationRequired") }; + } + } + + return setUserPassword({ serviceConfig, userId, password: command.password, code: command.code }); +} + +type CheckSessionAndSetPasswordCommand = { + sessionId: string; + currentPassword: string; + password: string; +}; + +export async function checkSessionAndSetPassword({ + sessionId, + currentPassword, + password, +}: CheckSessionAndSetPasswordCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const t = await getTranslations("password"); + + const sessionCookie = await getSessionCookieById({ sessionId }); + + if (!sessionCookie) { + return { error: "Could not load session cookie" }; + } + + let session; + try { + const sessionResponse = await getSession({ + serviceConfig, + sessionId: sessionCookie.id, + sessionToken: sessionCookie.token, + }); + session = sessionResponse.session; + } catch (error) { + logger.error("Error getting session:", { error }); + return { error: "Could not load session" }; + } + + if (!session || !session.factors?.user?.id) { + return { error: t("errors.couldNotLoadSession") }; + } + + const loginSettings = await getLoginSettings({ + serviceConfig, + organization: sessionCookie.organization, + }); + + // the session cookie carries the user's organization, so these are the user's org settings + if (loginSettings && !loginSettings.allowLocalAuthentication) { + return { error: t("errors.localAuthenticationNotAllowed") }; + } + + let lifetime = loginSettings?.passwordCheckLifetime; + if (!lifetime || !lifetime.seconds) { + lifetime = { + seconds: BigInt(60 * 60 * 24), + nanos: 0, + } as Duration; + } + + const checks = create(ChecksSchema, { + password: { password: currentPassword }, + }); + + try { + await setSessionAndUpdateCookie({ + recentCookie: sessionCookie, + checks, + lifetime, + requestId: sessionCookie.requestId, + }); + } catch (error: any) { + if ("failedAttempts" in error && error.failedAttempts) { + if (loginSettings?.ignoreUnknownUsernames) { + return { error: t("errors.failedToAuthenticateNoLimit") }; + } + const lockoutSettings = await getLockoutSettings({ serviceConfig, orgId: sessionCookie.organization }); + + const hasLimit = + lockoutSettings?.maxPasswordAttempts !== undefined && lockoutSettings?.maxPasswordAttempts > BigInt(0); + const locked = hasLimit && error.failedAttempts >= lockoutSettings?.maxPasswordAttempts; + const messageKey = hasLimit ? "errors.failedToAuthenticate" : "errors.failedToAuthenticateNoLimit"; + + return { + error: t(messageKey, { + failedAttempts: error.failedAttempts, + maxPasswordAttempts: hasLimit ? String(lockoutSettings?.maxPasswordAttempts ?? 0) : "?", + lockoutMessage: locked ? t("errors.accountLockedContactAdmin") : "", + }), + }; + } + if (loginSettings?.ignoreUnknownUsernames) { + return { error: t("change.errors.couldNotVerifyPassword") }; + } + return { error: t("change.errors.currentPasswordInvalid") }; + } + + const payload = create(SetPasswordRequestSchema, { + userId: session.factors.user.id, + newPassword: { + password, + }, + }); + + return setPassword({ serviceConfig, payload }).catch((error) => { + // throw error if failed precondition (ex. User is not yet initialized) + if (isClassifiedError(error) && error.code === Code.FailedPrecondition && error.message) { + return { error: t("errors.failedPrecondition") }; + } + return { error: "Could not set password" }; + }); +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/register-idp-flow.test.ts b/auth/ui/v2/apps/login/src/lib/actions/register-idp-flow.test.ts new file mode 100644 index 0000000..25657c9 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/register-idp-flow.test.ts @@ -0,0 +1,129 @@ +import { registerUserAndLinkToIDP } from "@/lib/actions/register"; +import { createIdpFlowProof } from "@/lib/server/idp-flow-proof"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("next/headers", () => ({ + headers: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + addHumanUser: vi.fn(), + addIDPLink: vi.fn(), + getLoginSettings: vi.fn(), + getUserByID: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), + // vg5j: the identity to link is read from the intent + retrieveIDPIntent: vi.fn().mockResolvedValue({ + idpInformation: { idpId: "idp123", userId: "idp-user-123", userName: "testuser" }, + }), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), + createSessionForIdpAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + completeFlowOrGetUrl: vi.fn(), +})); + +vi.mock("@/lib/server/verify-helper", () => ({ + checkEmailVerification: vi.fn(), + checkMFAFactors: vi.fn(), +})); + +vi.mock("@/lib/server/verification-check", () => ({ + setUserVerificationCheckCookie: vi.fn(), +})); + +vi.mock("@/lib/server/fingerprint", () => ({ + getBindingIdCookie: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +describe("registerUserAndLinkToIDP", () => { + const command = { + email: "test@example.com", + firstName: "Test", + lastName: "User", + organization: "org123", + requestId: "req123", + idpIntent: { idpIntentId: "intent123", idpIntentToken: "token123" }, + idpUserName: "testuser", + }; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + + const { headers } = await import("next/headers"); + const { getServiceConfig } = await import("@/lib/server/service-url"); + const { addHumanUser, addIDPLink, getLoginSettings, listAuthenticationMethodTypes } = + await import("@/lib/server/zitadel"); + const { createSessionForIdpAndUpdateCookie } = await import("@/lib/server/session-cookie"); + const { completeFlowOrGetUrl } = await import("@/lib/actions/flow"); + const { getBindingIdCookie } = await import("@/lib/server/fingerprint"); + + vi.mocked(headers).mockResolvedValue({} as any); + vi.mocked(getServiceConfig).mockReturnValue({ serviceConfig: { baseUrl: "https://api.example.com" } } as any); + vi.mocked(getLoginSettings).mockResolvedValue({ allowRegister: true } as any); + vi.mocked(addHumanUser).mockResolvedValue({ userId: "user123" } as any); + vi.mocked(addIDPLink).mockResolvedValue({} as any); + vi.mocked(createSessionForIdpAndUpdateCookie).mockResolvedValue({ + id: "session123", + factors: { user: { id: "user123", loginName: "testuser", organizationId: "org123" } }, + } as any); + vi.mocked(listAuthenticationMethodTypes).mockResolvedValue({ authMethodTypes: [] } as any); + vi.mocked(completeFlowOrGetUrl).mockResolvedValue({ redirect: "https://app.example.com/success" } as any); + vi.mocked(getBindingIdCookie).mockResolvedValue({ name: "bindingId", value: "fp123" }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + test.each([ + ["a missing proof", () => undefined], + ["a proof for another browser", () => createIdpFlowProof("attacker-fp")], + ["a proof of a linking flow", () => createIdpFlowProof("fp123", "session123")], + ["a garbage value", () => "not-a-proof"], + ])("should reject %s without creating a user", async (_name, makeFlowFingerprint) => { + const { addHumanUser, addIDPLink } = await import("@/lib/server/zitadel"); + const { createSessionForIdpAndUpdateCookie } = await import("@/lib/server/session-cookie"); + + const result = await registerUserAndLinkToIDP({ ...command, flowFingerprint: makeFlowFingerprint() }); + + expect(result).toEqual({ error: "errors.sessionMismatch" }); + expect(addHumanUser).not.toHaveBeenCalled(); + expect(addIDPLink).not.toHaveBeenCalled(); + expect(createSessionForIdpAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("should reject a valid proof when the browser has no binding id cookie", async () => { + const { addHumanUser } = await import("@/lib/server/zitadel"); + const { getBindingIdCookie } = await import("@/lib/server/fingerprint"); + vi.mocked(getBindingIdCookie).mockResolvedValue(undefined); + + const result = await registerUserAndLinkToIDP({ ...command, flowFingerprint: createIdpFlowProof("fp123") }); + + expect(result).toEqual({ error: "errors.sessionMismatch" }); + expect(addHumanUser).not.toHaveBeenCalled(); + }); + + test("should register and link the user when the proof matches this browser", async () => { + const { addHumanUser } = await import("@/lib/server/zitadel"); + + const result = await registerUserAndLinkToIDP({ ...command, flowFingerprint: createIdpFlowProof("fp123") }); + + expect(addHumanUser).toHaveBeenCalled(); + expect(result).toEqual({ redirect: "https://app.example.com/success" }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/register.test.ts b/auth/ui/v2/apps/login/src/lib/actions/register.test.ts new file mode 100644 index 0000000..66a0627 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/register.test.ts @@ -0,0 +1,116 @@ +import { registerUserAndLinkToIDP } from "@/lib/actions/register"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@/lib/server/zitadel", () => ({ + addHumanUser: vi.fn(), + addIDPLink: vi.fn(), + getLoginSettings: vi.fn(), + getUserByID: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), + retrieveIDPIntent: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), + createSessionForIdpAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/actions/flow", () => ({ + completeFlowOrGetUrl: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("@/lib/server/verification-check", () => ({ + setUserVerificationCheckCookie: vi.fn(), +})); + +vi.mock("@/lib/server/verify-helper", () => ({ + checkEmailVerification: vi.fn(), + checkMFAFactors: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +// fphg: the registration must come from the browser that started the IdP flow +vi.mock("@/lib/server/fingerprint", () => ({ + getBindingIdCookie: vi.fn(async () => ({ value: "binding-id" })), +})); + +vi.mock("@/lib/server/idp-flow-proof", () => ({ + isIdpFlowProofValid: vi.fn(() => true), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +const command = { + email: "new@example.com", + firstName: "New", + lastName: "User", + organization: "org-1", + idpIntent: { idpIntentId: "intent-1", idpIntentToken: "intent-token-1" }, + idpUserName: "typed-name", +}; + +describe("registerUserAndLinkToIDP", () => { + let zitadel: any; + let cookieHelpers: any; + + beforeEach(async () => { + vi.clearAllMocks(); + zitadel = vi.mocked(await import("@/lib/server/zitadel")); + cookieHelpers = vi.mocked(await import("@/lib/server/session-cookie")); + + zitadel.getLoginSettings.mockResolvedValue({ allowRegister: true }); + zitadel.addHumanUser.mockResolvedValue({ userId: "new-user" }); + zitadel.addIDPLink.mockResolvedValue({}); + cookieHelpers.createSessionForIdpAndUpdateCookie.mockResolvedValue(undefined); + }); + + test("links the external identity from the intent, not identity fields from the request", async () => { + zitadel.retrieveIDPIntent.mockResolvedValue({ + idpInformation: { idpId: "idp-from-intent", userId: "external-user-from-intent", userName: "intent-name" }, + }); + + // a direct POST can still send the fields the action used to accept + await registerUserAndLinkToIDP({ ...command, idpId: "victim-idp", idpUserId: "victim-external-user" } as any); + + expect(zitadel.retrieveIDPIntent).toHaveBeenCalledWith( + expect.objectContaining({ id: "intent-1", token: "intent-token-1" }), + ); + expect(zitadel.addIDPLink).toHaveBeenCalledWith( + expect.objectContaining({ + idp: { id: "idp-from-intent", userId: "external-user-from-intent", userName: "intent-name" }, + userId: "new-user", + }), + ); + }); + + test("uses the typed user name only when the IDP provided none", async () => { + zitadel.retrieveIDPIntent.mockResolvedValue({ + idpInformation: { idpId: "idp-1", userId: "external-user", userName: "" }, + }); + + await registerUserAndLinkToIDP(command); + + expect(zitadel.addIDPLink).toHaveBeenCalledWith( + expect.objectContaining({ idp: { id: "idp-1", userId: "external-user", userName: "typed-name" } }), + ); + }); + + test("creates no user when the intent can't be retrieved", async () => { + zitadel.retrieveIDPIntent.mockRejectedValue(new Error("invalid intent token")); + + const res = await registerUserAndLinkToIDP(command); + + expect(res).toEqual({ error: "errors.couldNotLinkIDP" }); + expect(zitadel.addHumanUser).not.toHaveBeenCalled(); + expect(zitadel.addIDPLink).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/register.ts b/auth/ui/v2/apps/login/src/lib/actions/register.ts new file mode 100644 index 0000000..8276547 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/register.ts @@ -0,0 +1,339 @@ +"use server"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { getBindingIdCookie } from "@/lib/server/fingerprint"; +import { isIdpFlowProofValid } from "@/lib/server/idp-flow-proof"; +import { createLogger } from "@/lib/server/logger"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { createSessionAndUpdateCookie, createSessionForIdpAndUpdateCookie } from "@/lib/server/session-cookie"; +import { setUserVerificationCheckCookie } from "@/lib/server/verification-check"; +import { checkEmailVerification, checkMFAFactors } from "@/lib/server/verify-helper"; +import { + addHumanUser, + addIDPLink, + getLoginSettings, + getUserByID, + listAuthenticationMethodTypes, + retrieveIDPIntent, +} from "@/lib/server/zitadel"; +import { Code, ConnectError, Duration, create } from "@zitadel/client"; +import { Factors } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { Checks, ChecksJson, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +const logger = createLogger("register"); + +const MAX_SESSION_RETRIES = 3; +const RETRY_DELAYS_MS = [500, 1000, 2000]; + +/** + * After user creation, backend projections (users, login_names) may not be updated yet. + * This helper retries createSessionAndUpdateCookie on NotFound errors with increasing delays. + */ +async function createSessionWithRetry(command: { checks: Checks; requestId: string | undefined; lifetime?: Duration }) { + let lastError: unknown; + for (let attempt = 0; attempt < MAX_SESSION_RETRIES; attempt++) { + try { + return await createSessionAndUpdateCookie(command); + } catch (error) { + lastError = error; + const isNotFound = error instanceof ConnectError && error.code === Code.NotFound; + const isLastAttempt = attempt + 1 >= MAX_SESSION_RETRIES; + if (!isNotFound || isLastAttempt) { + throw error; + } + const delay = RETRY_DELAYS_MS[attempt] ?? 2000; + logger.warn( + `Session creation failed with NotFound (attempt ${attempt + 1}/${MAX_SESSION_RETRIES}), retrying in ${delay}ms...`, + ); + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + throw lastError; +} + +type RegisterUserCommand = { + email: string; + firstName: string; + lastName: string; + password?: string; + organization: string; + requestId?: string; +}; + +export type RegisterUserResponse = { + userId: string; + sessionId: string; + factors: Factors | undefined; +}; +export async function registerUser( + command: RegisterUserCommand, +): Promise<{ error: string } | { redirect: string } | { samlData: { url: string; fields: Record } }> { + const t = await getTranslations("register"); + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const loginSettings = await getLoginSettings({ serviceConfig, organization: command.organization }); + + if (!loginSettings) { + return { error: t("errors.couldNotGetLoginSettings") }; + } + + if (!loginSettings.allowRegister) { + return { error: t("errors.registerNotAllowed") }; + } + + if (command.password && !loginSettings.allowLocalAuthentication) { + return { error: t("errors.localAuthenticationNotAllowed") }; + } + + const addResponse = await addHumanUser({ + serviceConfig, + email: command.email, + firstName: command.firstName, + lastName: command.lastName, + password: command.password ? command.password : undefined, + organization: command.organization, + }).catch((error) => { + logger.error("Failed to create user", { error }); + return null; + }); + + if (!addResponse) { + return { error: t("errors.couldNotCreateUser") }; + } + + let checkPayload: any = { + user: { search: { case: "userId", value: addResponse.userId } }, + }; + + if (command.password) { + checkPayload = { + ...checkPayload, + password: { password: command.password }, + } as ChecksJson; + } + + const checks = create(ChecksSchema, checkPayload); + + const result = await createSessionWithRetry({ + checks, + requestId: command.requestId, + lifetime: command.password ? loginSettings?.passwordCheckLifetime : undefined, + }).catch((error) => { + logger.error("Failed to create session after user creation", { error }); + return null; + }); + + const session = result?.session; + + if (!session || !session.factors?.user) { + return { error: t("errors.couldNotCreateSession") }; + } + + if (!command.password) { + const params = new URLSearchParams({ + loginName: session.factors.user.loginName, + organization: session.factors.user.organizationId, + }); + + if (command.requestId) { + params.append("requestId", command.requestId); + } + + // Set verification cookie for users registering with passkey (no password) + // This allows them to proceed with passkey registration without additional verification + await setUserVerificationCheckCookie(session.factors.user.id); + + return { redirect: "/passkey/set?" + params }; + } else { + const userResponse = await getUserByID({ serviceConfig, userId: session?.factors?.user?.id }).catch((error) => { + logger.error("Failed to get user after session creation", { error }); + return null; + }); + + if (!userResponse?.user) { + return { error: t("errors.userNotFound") }; + } + + const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined; + + const emailVerificationCheck = await checkEmailVerification( + session, + humanUser, + session.factors.user.organizationId, + command.requestId, + ); + + if (emailVerificationCheck?.redirect) { + return emailVerificationCheck; + } + + return completeFlowOrGetUrl( + command.requestId && session.id + ? { + sessionId: session.id, + requestId: command.requestId, + organization: session.factors.user.organizationId, + } + : { + loginName: session.factors.user.loginName, + organization: session.factors.user.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); + } +} + +type RegisterUserAndLinkToIDPommand = { + email: string; + firstName: string; + lastName: string; + organization: string; + requestId?: string; + idpIntent: { + idpIntentId: string; + idpIntentToken: string; + }; + /** only used when the IDP did not provide a user name */ + idpUserName: string; + flowFingerprint?: string; +}; + +export type registerUserAndLinkToIDPResponse = { + userId: string; + sessionId: string; + factors: Factors | undefined; +}; +export async function registerUserAndLinkToIDP( + command: RegisterUserAndLinkToIDPommand, +): Promise<{ error: string } | { redirect: string } | { samlData: { url: string; fields: Record } }> { + const t = await getTranslations("register"); + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const loginSettings = await getLoginSettings({ serviceConfig, organization: command.organization }); + + if (!loginSettings) { + return { error: t("errors.couldNotGetLoginSettings") }; + } + + if (!loginSettings.allowRegister) { + return { error: t("errors.registerNotAllowed") }; + } + + // the intent must belong to an IdP flow started in this browser (login CSRF) + const bindingIdCookie = await getBindingIdCookie(); + if (!isIdpFlowProofValid(command.flowFingerprint, bindingIdCookie?.value)) { + logger.warn("IDP flow fingerprint missing or mismatch on registration"); + return { error: t("errors.sessionMismatch") }; + } + + // The external identity to link is read from the intent, which proves the user authenticated at + // the IDP. The browser only passes the intent id and token, so it can't link another identity. + const intent = await retrieveIDPIntent({ + serviceConfig, + id: command.idpIntent.idpIntentId, + token: command.idpIntent.idpIntentToken, + }).catch((error) => { + logger.warn("registerUserAndLinkToIDP: could not retrieve IDP intent", { error }); + return undefined; + }); + + const idpInformation = intent?.idpInformation; + + if (!idpInformation?.idpId || !idpInformation.userId) { + return { error: t("errors.couldNotLinkIDP") }; + } + + const addUserResponse = await addHumanUser({ + serviceConfig, + email: command.email, + firstName: command.firstName, + lastName: command.lastName, + organization: command.organization, + }); + + const idpLink = await addIDPLink({ + serviceConfig, + idp: { + id: idpInformation.idpId, + userId: idpInformation.userId, + userName: idpInformation.userName || command.idpUserName, + }, + userId: addUserResponse.userId, + }); + + if (!idpLink) { + return { error: t("errors.couldNotLinkIDP") }; + } + + const session = await createSessionForIdpAndUpdateCookie({ + requestId: command.requestId, + userId: addUserResponse.userId, // the user we just created + idpIntent: command.idpIntent, + lifetime: loginSettings?.externalLoginCheckLifetime, + }); + + if (!session || !session.factors?.user) { + return { error: t("errors.couldNotCreateSession") }; + } + + // const userResponse = await getUserByID({ + // serviceConfig.baseUrl, + // userId: session?.factors?.user?.id, + // }); + + // if (!userResponse.user) { + // return { error: "User not found in the system" }; + // } + + // const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined; + + // check to see if user was verified + // const emailVerificationCheck = checkEmailVerification(session, humanUser, command.organization, command.requestId); + + // if (emailVerificationCheck?.redirect) { + // return emailVerificationCheck; + // } + + // check if user has MFA methods + let authMethods; + if (session.factors?.user?.id) { + const response = await listAuthenticationMethodTypes({ serviceConfig, userId: session.factors.user.id }); + if (response.authMethodTypes && response.authMethodTypes.length) { + authMethods = response.authMethodTypes; + } + } + + // Always check MFA factors, even if no auth methods are configured + // This ensures that force MFA settings are respected + const mfaFactorCheck = await checkMFAFactors( + serviceConfig, + session, + loginSettings, + authMethods || [], // Pass empty array if no auth methods + command.organization, + command.requestId, + ); + + if (mfaFactorCheck?.redirect) { + return mfaFactorCheck; + } + + return completeFlowOrGetUrl( + command.requestId && session.id + ? { + sessionId: session.id, + requestId: command.requestId, + organization: session.factors.user.organizationId, + } + : { + loginName: session.factors.user.loginName, + organization: session.factors.user.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/session.test.ts b/auth/ui/v2/apps/login/src/lib/actions/session.test.ts new file mode 100644 index 0000000..aa716c9 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/session.test.ts @@ -0,0 +1,401 @@ +import { + clearSession, + continueWithSession, + skipMFAAndContinueWithNextUrl, + updateOrCreateSession, +} from "@/lib/actions/session"; +import { SessionUpdatedError } from "@/lib/server/challenges"; +import { Code } from "@connectrpc/connect"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@zitadel/client", async () => { + const { Code } = await import("@connectrpc/connect"); + return { Code, create: vi.fn((_schema: unknown, data: unknown) => data), Duration: {} }; +}); + +vi.mock("@/lib/server/zitadel", () => ({ + deleteSession: vi.fn(), + getLoginSettings: vi.fn(), + getSecuritySettings: vi.fn(), + humanMFAInitSkipped: vi.fn(), + listUsers: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), + setSessionAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getMostRecentSessionCookie: vi.fn(), + getSessionCookieById: vi.fn(), + getSessionCookieByLoginName: vi.fn(), + removeSessionFromCookie: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("@/lib/actions/flow", () => ({ + completeFlowOrGetUrl: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + isSessionValid: vi.fn(), + loadSession: vi.fn(), + hasVerifiedPrimaryFactor: vi.fn((session: any) => ({ valid: !!session?.factors?.password?.verifiedAt })), +})); + +vi.mock("@/lib/server/mfa-helper", () => ({ + shouldEnforceMFA: vi.fn(() => false), +})); + +vi.mock("@/lib/server/host", () => ({ + getPublicHost: vi.fn(() => "test.com"), + getPublicHostWithProtocol: vi.fn(() => "https://test.com"), +})); + +vi.mock("@/lib/actions/loginname", () => ({ + sendLoginname: vi.fn(), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(async () => (key: string) => key), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +vi.mock("@/lib/server/grpc/interceptors/error-classification", () => ({ + isClassifiedError: (error: unknown) => error !== null && typeof error === "object" && "code" in error, +})); + +const cookie = { id: "session-1", token: "token-1", loginName: "user@example.com" }; + +describe("clearSession", () => { + let deleteSession: any; + let getSecuritySettings: any; + let getSessionCookieById: any; + let removeSessionFromCookie: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const zitadel = await import("@/lib/server/zitadel"); + const cookies = await import("@/lib/server/cookies"); + deleteSession = vi.mocked(zitadel.deleteSession); + getSecuritySettings = vi.mocked(zitadel.getSecuritySettings); + getSessionCookieById = vi.mocked(cookies.getSessionCookieById); + removeSessionFromCookie = vi.mocked(cookies.removeSessionFromCookie); + + getSessionCookieById.mockResolvedValue(cookie); + getSecuritySettings.mockResolvedValue({ embeddedIframe: { enabled: true } }); + }); + + test("deletes the session and prunes the cookie entry on success", async () => { + deleteSession.mockResolvedValue({ details: {} }); + + const res = await clearSession({ sessionId: "session-1" }); + + expect(res).toBeUndefined(); + expect(deleteSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: "session-1", sessionToken: "token-1" })); + expect(removeSessionFromCookie).toHaveBeenCalledWith({ session: cookie, iFrameEnabled: true }); + }); + + test("prunes the cookie entry when the server rejects the cookie token (session gone or token stale)", async () => { + deleteSession.mockRejectedValue({ code: Code.PermissionDenied }); + + const res = await clearSession({ sessionId: "session-1" }); + + expect(res).toBeUndefined(); + expect(removeSessionFromCookie).toHaveBeenCalledWith({ session: cookie, iFrameEnabled: true }); + }); + + test("keeps the cookie entry and reports an error on any other failure", async () => { + deleteSession.mockRejectedValue({ code: Code.Unavailable }); + + const res = await clearSession({ sessionId: "session-1" }); + + expect(res).toEqual({ error: "couldNotClearSession" }); + expect(removeSessionFromCookie).not.toHaveBeenCalled(); + }); + + test("attempts the server-side delete even when security settings cannot be loaded", async () => { + deleteSession.mockResolvedValue({ details: {} }); + getSecuritySettings.mockRejectedValue(new Error("settings unavailable")); + + await expect(clearSession({ sessionId: "session-1" })).rejects.toThrow("settings unavailable"); + + expect(deleteSession).toHaveBeenCalledTimes(1); + expect(removeSessionFromCookie).not.toHaveBeenCalled(); + }); + + test("does nothing when the session id is not in the cookie", async () => { + getSessionCookieById.mockResolvedValue(undefined); + + const res = await clearSession({ sessionId: "unknown" }); + + expect(res).toBeUndefined(); + expect(deleteSession).not.toHaveBeenCalled(); + }); +}); + +// Server actions are public endpoints: these tests send what a direct POST could send, including +// fields that are not part of the command types. +describe("server actions resolve the session from the caller's cookie", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + const authenticatedSession = { + id: "session-1", + factors: { + user: { id: "user-1", loginName: "user@example.com", organizationId: "org-1" }, + password: { verifiedAt: { seconds: BigInt(1) } }, + }, + }; + + let zitadel: any; + let cookies: any; + let sessionLib: any; + let mfaHelper: any; + let cookieHelpers: any; + let client: any; + + beforeEach(async () => { + vi.clearAllMocks(); + zitadel = vi.mocked(await import("@/lib/server/zitadel")); + cookies = vi.mocked(await import("@/lib/server/cookies")); + sessionLib = vi.mocked(await import("@/lib/server/session")); + mfaHelper = vi.mocked(await import("@/lib/server/mfa-helper")); + cookieHelpers = vi.mocked(await import("@/lib/server/session-cookie")); + client = vi.mocked(await import("@/lib/actions/flow")); + + cookies.getSessionCookieById.mockResolvedValue({ ...cookie, organization: "org-1" }); + sessionLib.loadSession.mockResolvedValue(authenticatedSession); + zitadel.getLoginSettings.mockResolvedValue({}); + client.completeFlowOrGetUrl.mockResolvedValue({ redirect: "/signedin" }); + }); + + describe("skipMFAAndContinueWithNextUrl", () => { + test("marks the user of the caller's session, not a user id from the request", async () => { + const res = await skipMFAAndContinueWithNextUrl({ sessionId: "session-1", userId: "victim-user" } as any); + + expect(sessionLib.loadSession).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ token: "token-1" })); + expect(zitadel.humanMFAInitSkipped).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-1" })); + expect(res).toEqual({ redirect: "/signedin" }); + }); + + test("rejects a caller without a session cookie", async () => { + cookies.getSessionCookieById.mockResolvedValue(undefined); + + const res = await skipMFAAndContinueWithNextUrl({ sessionId: "victim-session", userId: "victim-user" } as any); + + expect(res).toEqual({ error: expect.any(String) }); + expect(zitadel.humanMFAInitSkipped).not.toHaveBeenCalled(); + }); + + test("rejects a session without a verified primary factor", async () => { + sessionLib.loadSession.mockResolvedValue({ + ...authenticatedSession, + factors: { user: authenticatedSession.factors.user }, + }); + + const res = await skipMFAAndContinueWithNextUrl({ sessionId: "session-1" }); + + expect(res).toEqual({ error: expect.any(String) }); + expect(zitadel.humanMFAInitSkipped).not.toHaveBeenCalled(); + }); + + test("rejects when the login policy enforces MFA", async () => { + mfaHelper.shouldEnforceMFA.mockReturnValue(true); + + const res = await skipMFAAndContinueWithNextUrl({ sessionId: "session-1" }); + + expect(res).toEqual({ error: expect.any(String) }); + expect(zitadel.humanMFAInitSkipped).not.toHaveBeenCalled(); + }); + }); + + describe("continueWithSession", () => { + test("validates the session loaded from ZITADEL, not a session object from the request", async () => { + sessionLib.isSessionValid.mockResolvedValue(true); + + await continueWithSession({ + sessionId: "session-1", + factors: { user: { id: "victim-user", loginName: "victim@example.com" } }, + } as any); + + expect(sessionLib.isSessionValid).toHaveBeenCalledWith(expect.objectContaining({ session: authenticatedSession })); + expect(client.completeFlowOrGetUrl).toHaveBeenCalledWith( + expect.objectContaining({ loginName: "user@example.com" }), + undefined, + ); + }); + + test("rejects a session id that is not in the caller's cookie", async () => { + cookies.getSessionCookieById.mockResolvedValue(undefined); + + const res = await continueWithSession({ sessionId: "victim-session" }); + + expect(res).toEqual({ error: "couldNotContinueSession" }); + expect(sessionLib.isSessionValid).not.toHaveBeenCalled(); + }); + }); + + describe("updateOrCreateSession", () => { + test("takes the lifetime from the user's login policy and drops primary checks", async () => { + zitadel.getLoginSettings.mockResolvedValue({ secondFactorCheckLifetime: { seconds: BigInt(300), nanos: 0 } }); + cookieHelpers.setSessionAndUpdateCookie.mockResolvedValue(authenticatedSession); + + await updateOrCreateSession({ + sessionId: "session-1", + organization: "org-with-a-longer-lifetime", + checks: { password: { password: "guess" }, otpEmail: { code: "123456" } }, + lifetime: { seconds: BigInt(10 * 365 * 24 * 60 * 60), nanos: 0 }, + } as any); + + expect(zitadel.getLoginSettings).toHaveBeenCalledWith(expect.objectContaining({ organization: "org-1" })); + + const [command] = cookieHelpers.setSessionAndUpdateCookie.mock.calls[0]; + expect(command.lifetime).toEqual({ seconds: BigInt(300), nanos: 0 }); + expect(command.checks).toEqual(expect.objectContaining({ otpEmail: { code: "123456" } })); + expect(command.checks.password).toBeUndefined(); + }); + + test("gives a TOTP check the second factor lifetime", async () => { + zitadel.getLoginSettings.mockResolvedValue({ + secondFactorCheckLifetime: { seconds: BigInt(300), nanos: 0 }, + multiFactorCheckLifetime: { seconds: BigInt(600), nanos: 0 }, + }); + cookieHelpers.setSessionAndUpdateCookie.mockResolvedValue(authenticatedSession); + + await updateOrCreateSession({ sessionId: "session-1", checks: { totp: { code: "123456" } } } as any); + + const [command] = cookieHelpers.setSessionAndUpdateCookie.mock.calls[0]; + expect(command.lifetime).toEqual({ seconds: BigInt(300), nanos: 0 }); + }); + + test("builds the OTP email link and the WebAuthN domain from the request host", async () => { + vi.stubEnv("NEXT_PUBLIC_BASE_PATH", "/ui/v2/login"); + cookieHelpers.setSessionAndUpdateCookie.mockResolvedValue(authenticatedSession); + + await updateOrCreateSession({ + sessionId: "session-1", + requestId: "oidc_123&evil=1", + challenges: { + otpEmail: { deliveryType: { case: "sendCode", value: { urlTemplate: "https://evil.example/?code={{.Code}}" } } }, + webAuthN: { domain: "evil.example", userVerificationRequirement: 1 }, + }, + } as any); + + const [command] = cookieHelpers.setSessionAndUpdateCookie.mock.calls[0]; + expect(command.challenges.otpEmail.deliveryType).toEqual({ + case: "sendCode", + value: { + urlTemplate: + "https://test.com/ui/v2/login/otp/email?code={{.Code}}&userId={{.UserID}}&sessionId={{.SessionID}}&requestId=oidc_123%26evil%3D1", + }, + }); + expect(command.challenges.webAuthN).toEqual({ domain: "test.com", userVerificationRequirement: 1 }); + }); + + test("binds the challenges of a new session to the request host too", async () => { + vi.stubEnv("NEXT_PUBLIC_BASE_PATH", "/ui/v2/login"); + cookies.getSessionCookieByLoginName.mockResolvedValue(undefined); + cookieHelpers.createSessionAndUpdateCookie.mockResolvedValue({ sessionCookie: cookie }); + cookieHelpers.setSessionAndUpdateCookie.mockResolvedValue(authenticatedSession); + + await updateOrCreateSession({ + loginName: "victim@example.com", + challenges: { + otpEmail: { deliveryType: { case: "sendCode", value: { urlTemplate: "https://evil.example/?code={{.Code}}" } } }, + }, + } as any); + + // the challenges are only requested once, on the update of the new session + const [createCommand] = cookieHelpers.createSessionAndUpdateCookie.mock.calls[0]; + expect(createCommand).not.toHaveProperty("challenges"); + const [setCommand] = cookieHelpers.setSessionAndUpdateCookie.mock.calls[0]; + expect(setCommand.challenges.otpEmail.deliveryType.value.urlTemplate).toMatch( + /^https:\/\/test\.com\/ui\/v2\/login\/otp\/email\?/, + ); + }); + }); +}); + +describe("updateOrCreateSession OTP SMS resend cooldown", () => { + let getSessionCookieById: any; + let createSessionAndUpdateCookie: any; + let setSessionAndUpdateCookie: any; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.useFakeTimers(); + vi.setSystemTime(1_000_000); + + const zitadel = vi.mocked(await import("@/lib/server/zitadel")); + const cookies = vi.mocked(await import("@/lib/server/cookies")); + const cookieHelpers = vi.mocked(await import("@/lib/server/session-cookie")); + getSessionCookieById = cookies.getSessionCookieById; + createSessionAndUpdateCookie = cookieHelpers.createSessionAndUpdateCookie; + setSessionAndUpdateCookie = cookieHelpers.setSessionAndUpdateCookie; + + zitadel.getLoginSettings.mockResolvedValue({ secondFactorCheckLifetime: { seconds: BigInt(60) } } as any); + setSessionAndUpdateCookie.mockResolvedValue({ id: "session-1", factors: {} }); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + test("refuses another OTP SMS within the cooldown without calling the API", async () => { + getSessionCookieById.mockResolvedValue({ ...cookie, otpSmsSentTs: `${1_000_000 - 10_000}` }); + + const res = await updateOrCreateSession({ sessionId: "session-1", challenges: { otpSms: {} } as any }); + + expect(res).toEqual({ retryAfterSeconds: 20 }); + expect(setSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("sends the OTP SMS once the cooldown has passed and returns the next cooldown", async () => { + getSessionCookieById.mockResolvedValue({ ...cookie, otpSmsSentTs: `${1_000_000 - 30_000}` }); + + const res = await updateOrCreateSession({ sessionId: "session-1", challenges: { otpSms: {} } as any }); + + expect(setSessionAndUpdateCookie).toHaveBeenCalledTimes(1); + expect(res).toEqual(expect.objectContaining({ sessionId: "session-1", retryAfterSeconds: 30 })); + }); + + test("requests the OTP SMS only once when it has to create the session first", async () => { + const cookies = vi.mocked(await import("@/lib/server/cookies")); + cookies.getSessionCookieByLoginName.mockResolvedValue(undefined); + createSessionAndUpdateCookie.mockResolvedValue({ sessionCookie: cookie }); + + await updateOrCreateSession({ loginName: "user@example.com", challenges: { otpSms: {} } as any }); + + expect(createSessionAndUpdateCookie.mock.calls[0][0]).not.toHaveProperty("challenges"); + expect(setSessionAndUpdateCookie).toHaveBeenCalledWith(expect.objectContaining({ challenges: { otpSms: {} } })); + }); + + test("does not send a second OTP SMS on a new session when the update failed after the code was sent", async () => { + getSessionCookieById.mockResolvedValue(cookie); + setSessionAndUpdateCookie.mockRejectedValue(new SessionUpdatedError(new Error("could not get session"))); + + await expect(updateOrCreateSession({ sessionId: "session-1", challenges: { otpSms: {} } as any })).rejects.toThrow( + SessionUpdatedError, + ); + + expect(createSessionAndUpdateCookie).not.toHaveBeenCalled(); + }); + + test("does not apply the cooldown to code checks", async () => { + getSessionCookieById.mockResolvedValue({ ...cookie, otpSmsSentTs: `${1_000_000}` }); + + const res = await updateOrCreateSession({ sessionId: "session-1", checks: { otpSms: { code: "123456" } } as any }); + + expect(setSessionAndUpdateCookie).toHaveBeenCalledTimes(1); + expect(res).toEqual(expect.objectContaining({ sessionId: "session-1", retryAfterSeconds: undefined })); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/session.ts b/auth/ui/v2/apps/login/src/lib/actions/session.ts new file mode 100644 index 0000000..cf9a645 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/session.ts @@ -0,0 +1,438 @@ +"use server"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { getOTPSMSResendCooldownSeconds, getOTPSMSRetryAfterSeconds, SessionUpdatedError } from "@/lib/server/challenges"; +import { + getMostRecentSessionCookie, + getSessionCookieById, + getSessionCookieByLoginName, + removeSessionFromCookie, +} from "@/lib/server/cookies"; +import { isClassifiedError } from "@/lib/server/grpc/interceptors/error-classification"; +import { getPublicHost, getPublicHostWithProtocol } from "@/lib/server/host"; +import { createLogger } from "@/lib/server/logger"; +import { shouldEnforceMFA } from "@/lib/server/mfa-helper"; +import { reauthenticate } from "@/lib/server/reauthenticate"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { hasVerifiedPrimaryFactor, isSessionValid, loadSession } from "@/lib/server/session"; +import { createSessionAndUpdateCookie, setSessionAndUpdateCookie } from "@/lib/server/session-cookie"; +import { + deleteSession, + getLoginSettings, + getSecuritySettings, + humanMFAInitSkipped, + listUsers, + ServiceConfig, +} from "@/lib/server/zitadel"; +import { Code, create, Duration } from "@zitadel/client"; +import { + Challenges, + RequestChallenges, + RequestChallenges_OTPEmail_SendCodeSchema, +} from "@zitadel/proto/zitadel/session/v2/challenge_pb"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { Checks, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +const logger = createLogger("session"); + +/** + * Server actions are public endpoints, so every argument is caller-controlled. The session an + * action acts on is therefore always resolved from the caller's own signed `sessions` cookie and + * loaded from ZITADEL with that cookie's token, never taken from the request body. + */ +async function loadCallerSession({ + serviceConfig, + sessionId, + loginName, + organization, +}: { + serviceConfig: ServiceConfig; + sessionId?: string; + loginName?: string; + organization?: string; +}): Promise { + const sessionCookie = sessionId + ? await getSessionCookieById({ sessionId }) + : loginName + ? await getSessionCookieByLoginName({ loginName, organization }) + : undefined; + + if (!sessionCookie) { + return undefined; + } + + return loadSession(serviceConfig, sessionCookie); +} + +export async function skipMFAAndContinueWithNextUrl({ + requestId, + loginName, + sessionId, + organization, +}: { + loginName?: string; + sessionId?: string; + requestId?: string; + organization?: string; +}): Promise<{ redirect: string } | { error: string } | { samlData: { url: string; fields: Record } }> { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const session = await loadCallerSession({ serviceConfig, sessionId, loginName, organization }); + const userId = session?.factors?.user?.id; + + // only a user who just authenticated may skip the MFA setup prompt, and only for themselves + if (!session || !userId || !hasVerifiedPrimaryFactor(session).valid) { + return { error: "Could not skip MFA and continue" }; + } + + const userLoginSettings = await getLoginSettings({ serviceConfig, organization: session.factors?.user?.organizationId }); + + if (shouldEnforceMFA(session, userLoginSettings)) { + return { error: "Could not skip MFA and continue" }; + } + + const loginSettings = await getLoginSettings({ serviceConfig, organization: organization }); + + await humanMFAInitSkipped({ serviceConfig, userId }); + + if (requestId && session.id) { + return completeFlowOrGetUrl( + { + sessionId: session.id, + requestId: requestId, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + } else if (session.factors?.user?.loginName) { + return completeFlowOrGetUrl( + { + loginName: session.factors.user.loginName, + organization: organization, + }, + loginSettings?.defaultRedirectUri, + ); + } + + return { error: "Could not skip MFA and continue" }; +} + +export type ContinueWithSessionCommand = { sessionId: string; requestId?: string }; + +export async function continueWithSession({ sessionId, requestId }: ContinueWithSessionCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const t = await getTranslations("error"); + + const session = await loadCallerSession({ serviceConfig, sessionId }); + + if (!session?.factors?.user) { + return { error: t("couldNotContinueSession") }; + } + + const loginSettings = await getLoginSettings({ serviceConfig, organization: session.factors.user.organizationId }); + + // Validate session (including MFA) before completing the flow + const valid = await isSessionValid({ serviceConfig, session }); + + if (!valid) { + logger.warn("continueWithSession: session is not valid (e.g. MFA not completed), redirecting to re-authenticate", { + sessionId: session.id, + }); + + // Redirect user to re-authenticate (will route to MFA page if password is still valid) + return (await reauthenticate(session, requestId)) ?? { error: t("couldNotContinueSession") }; + } + + if (requestId && session.id) { + return completeFlowOrGetUrl( + { + sessionId: session.id, + requestId: requestId, + organization: session.factors.user.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); + } + + return completeFlowOrGetUrl( + { + loginName: session.factors.user.loginName, + organization: session.factors.user.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); +} + +export type UpdateSessionCommand = { + loginName?: string; + sessionId?: string; + organization?: string; + checks?: Checks; + requestId?: string; + challenges?: RequestChallenges; +}; + +/** + * This action only completes second factors and passkeys. The primary checks (user, password, + * IDP intent) run through their own actions, which enforce the login policy first, so they are + * dropped here instead of being forwarded to the session API. + */ +function pickSecondFactorChecks(checks?: Checks): Checks | undefined { + if (!checks) { + return undefined; + } + + return create(ChecksSchema, { + webAuthN: checks.webAuthN, + totp: checks.totp, + otpSms: checks.otpSms, + otpEmail: checks.otpEmail, + }); +} + +/** + * The WebAuthN relying party and the link in the OTP email are always derived from the host this + * request was served on (the same host that is forwarded to and validated by ZITADEL), never taken + * from the caller. Otherwise anyone could make ZITADEL send a genuine OTP email whose link points + * to a host of their choice. + */ +function bindChallengesToHost( + challenges: RequestChallenges | undefined, + hostWithProtocol: string, + requestId?: string, +): RequestChallenges | undefined { + if (!challenges) { + return undefined; + } + + const bound = { ...challenges }; + + if (bound.webAuthN) { + bound.webAuthN = { ...bound.webAuthN, domain: new URL(hostWithProtocol).hostname }; + } + + if (bound.otpEmail) { + const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; + let urlTemplate = `${hostWithProtocol}${basePath}/otp/email?code={{.Code}}&userId={{.UserID}}&sessionId={{.SessionID}}`; + + if (requestId) { + urlTemplate += `&requestId=${encodeURIComponent(requestId)}`; + } + + bound.otpEmail = { + ...bound.otpEmail, + deliveryType: { case: "sendCode", value: create(RequestChallenges_OTPEmail_SendCodeSchema, { urlTemplate }) }, + }; + } + + return bound; +} + +export async function updateOrCreateSession(options: UpdateSessionCommand) { + const { loginName, sessionId, organization, requestId } = options; + const checks = pickSecondFactorChecks(options.checks); + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const host = getPublicHost(_headers); + + const t = await getTranslations("verify.errors"); + + if (!host) { + return { error: "Could not get host" }; // Technical error, maybe leave or translate if key exists + } + + const challenges = bindChallengesToHost(options.challenges, getPublicHostWithProtocol(_headers), requestId); + + let recentSession = sessionId + ? await getSessionCookieById({ sessionId }) + : loginName + ? await getSessionCookieByLoginName({ loginName, organization }) + : await getMostRecentSessionCookie(); + + if (!recentSession) { + if (!loginName) { + return { error: t("couldNotFindSession") }; + } + + const checks = create(ChecksSchema, { + user: { search: { case: "loginName", value: loginName } }, + }); + + // the challenges are requested by the setSession call below, requesting them here as well would send every code twice + const result = await createSessionAndUpdateCookie({ + checks, + requestId, + }).catch((error) => { + if (isClassifiedError(error) && error.isUserError) { + logger.warn("Could not create session (client error)", { grpcCode: error.code, httpStatus: error.httpStatus }); + } else { + logger.error("Could not create session (server error)", { error }); + } + return undefined; + }); + + if (result && "sessionCookie" in result) { + recentSession = result.sessionCookie; + } + + if (!recentSession) { + return { + error: t("couldNotFindSession"), + }; + } + } + + if (challenges?.otpSms) { + const retryAfterSeconds = getOTPSMSRetryAfterSeconds(recentSession.otpSmsSentTs); + if (retryAfterSeconds > 0) { + // no error message: the UI shows the countdown on the resend button instead + return { retryAfterSeconds }; + } + } + + // The lifetime always comes from the login policy of the session's user (the cookie entry is + // signed and its organization set from the session), never from the caller. + const loginSettings = await getLoginSettings({ serviceConfig, organization: recentSession.organization ?? organization }); + + let lifetime = checks?.webAuthN + ? loginSettings?.multiFactorCheckLifetime // TODO different lifetime for webauthn u2f/passkey + : checks?.totp || checks?.otpEmail || checks?.otpSms + ? loginSettings?.secondFactorCheckLifetime + : undefined; + + if (!lifetime || !lifetime.seconds) { + logger.warn("No lifetime provided for session, defaulting to 24 hours"); + lifetime = { + seconds: BigInt(60 * 60 * 24), // default to 24 hours + nanos: 0, + } as Duration; + } + + let session; + try { + session = await setSessionAndUpdateCookie({ + recentCookie: recentSession, + checks, + challenges, + requestId, + lifetime, + }); + } catch (error) { + // the code was already sent for this session: creating a new session with the same challenge would send + // a second code, and the first one could not be verified against the new session + if (error instanceof SessionUpdatedError && (challenges?.otpSms || challenges?.otpEmail)) { + throw error; + } + + const loginNameForCreation = options.loginName || recentSession?.loginName; + const orgForCreation = options.organization || recentSession?.organization; + + if (!loginNameForCreation) { + throw error; + } + + const users = await listUsers({ + serviceConfig, + loginName: loginNameForCreation, + organizationId: orgForCreation, + }); + + if (users.details?.totalResult === BigInt(1) && users.result[0].userId) { + const user = users.result[0]; + const newChecks = create(ChecksSchema, { + ...(checks || {}), + user: { search: { case: "userId", value: user.userId } } as any, + }); + + const result = await createSessionAndUpdateCookie({ + checks: newChecks, + requestId, + lifetime, + challenges, + }); + // @ts-ignore + session = { ...result.session, challenges: result.challenges }; + } else { + throw error; + } + } + + if (!session || ("error" in session && session.error)) { + return { error: t("couldNotUpdateSession") }; + } + + // @ts-ignore + const challengeResponse: Challenges | undefined = session.challenges; + + return { + sessionId: session.id, + factors: session.factors, + // Only the WebAuthN challenge may reach the browser. `sanitizeChallenges` already stops + // `returnCode` from being requested, so `otpSms`/`otpEmail` should always be unset here — + // keeping the projection explicit means no OTP code can leak through this boundary even + // if that ever regresses (GHSA-3gwm-5wx8-4gm6). + challenges: challengeResponse?.webAuthN ? { webAuthN: challengeResponse.webAuthN } : undefined, + // lets the UI count down until the next OTP SMS may be requested + retryAfterSeconds: challenges?.otpSms ? getOTPSMSResendCooldownSeconds() : undefined, + }; +} + +type ClearSessionOptions = { + sessionId: string; +}; + +export async function clearSession(options: ClearSessionOptions): Promise<{ error?: string } | void> { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const { sessionId } = options; + + const sessionCookie = await getSessionCookieById({ sessionId }); + + if (!sessionCookie) { + return; + } + + try { + const deleteResponse = await deleteSession({ + serviceConfig, + sessionId: sessionCookie.id, + sessionToken: sessionCookie.token, + }); + if (!deleteResponse) { + throw new Error("Could not delete session"); + } + } catch (error) { + // The backend verifies the cookie's token before it looks at the session + // state, so PermissionDenied is what a session that no longer exists answers + // (nothing to verify against). It is also what a live session with a stale + // cookie token would answer; we deliberately prune the cookie entry in that + // case too: the user explicitly asked to remove the account from this + // browser, and without its token the server-side session cannot be used by + // anyone and simply expires. Every other failure keeps the entry and is + // reported so the caller can show it. + // (A session terminated by an RP-initiated logout keeps its token id, so + // deleting it again succeeds and never reaches this branch.) + if (!isClassifiedError(error) || error.code !== Code.PermissionDenied) { + logger.error("clearSession: could not delete session", { sessionId: sessionCookie.id, error }); + const t = await getTranslations("error"); + return { error: t("couldNotClearSession") }; + } + + logger.warn("clearSession: session rejected the cookie token (gone or stale), pruning cookie entry", { + sessionId: sessionCookie.id, + }); + } + + // Only needed for the cookie rewrite, so it must not gate the delete above. + const securitySettings = await getSecuritySettings({ serviceConfig }); + const iFrameEnabled = !!securitySettings?.embeddedIframe?.enabled; + + await removeSessionFromCookie({ session: sessionCookie, iFrameEnabled }); +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/u2f.test.ts b/auth/ui/v2/apps/login/src/lib/actions/u2f.test.ts new file mode 100644 index 0000000..901221b --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/u2f.test.ts @@ -0,0 +1,148 @@ +import { addU2F, verifyU2F } from "@/lib/actions/u2f"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@zitadel/client", () => ({ + // `create(schema, data)` is only used to build the verify request — return the data. + create: vi.fn((_schema: unknown, data: unknown) => data), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + getSession: vi.fn(), + registerU2F: vi.fn(), + verifyU2FRegistration: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })), +})); + +vi.mock("@/lib/server/host", () => ({ + getPublicHost: vi.fn(() => "test.com"), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieById: vi.fn(), +})); + +vi.mock("@/lib/server/enrollment-guard", () => ({ + getEnrollmentAuthorizationError: vi.fn(), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(() => new Headers()), +})); + +vi.mock("next/server", () => ({ + userAgent: vi.fn(() => ({ browser: {}, device: {}, os: {} })), +})); + +const userOnlySession = { + session: { id: "session-1", factors: { user: { id: "victim-1", loginName: "victim@example.com" } } }, +}; + +describe("addU2F", () => { + let getSessionCookieById: any; + let getSession: any; + let registerU2F: any; + let getEnrollmentAuthorizationError: any; + + beforeEach(async () => { + vi.clearAllMocks(); + getSessionCookieById = vi.mocked((await import("@/lib/server/cookies")).getSessionCookieById); + getSession = vi.mocked((await import("@/lib/server/zitadel")).getSession); + registerU2F = vi.mocked((await import("@/lib/server/zitadel")).registerU2F); + getEnrollmentAuthorizationError = vi.mocked( + (await import("@/lib/server/enrollment-guard")).getEnrollmentAuthorizationError, + ); + + getSessionCookieById.mockResolvedValue({ id: "session-1", token: "token-1" }); + getSession.mockResolvedValue(userOnlySession); + }); + + test("rejects enrollment on an unauthenticated (identify-only) session without registering", async () => { + getEnrollmentAuthorizationError.mockResolvedValue("You have to authenticate or have a valid User Verification Check"); + + const result = await addU2F({ sessionId: "session-1" }); + + expect(result).toEqual({ error: "You have to authenticate or have a valid User Verification Check" }); + expect(getEnrollmentAuthorizationError).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://example.com" }, + session: userOnlySession.session, + userId: "victim-1", + }); + expect(registerU2F).not.toHaveBeenCalled(); + }); + + test("registers the credential when the session is authorized", async () => { + getEnrollmentAuthorizationError.mockResolvedValue(null); + registerU2F.mockResolvedValue({ u2fId: "u2f-1" }); + + const result = await addU2F({ sessionId: "session-1" }); + + expect(registerU2F).toHaveBeenCalledWith({ + serviceConfig: { baseUrl: "https://example.com" }, + userId: "victim-1", + domain: "test.com", + }); + expect(result).toEqual({ u2fId: "u2f-1" }); + }); + + test("returns error and never calls the guard when no session cookie exists", async () => { + getSessionCookieById.mockResolvedValue(undefined); + + const result = await addU2F({ sessionId: "missing" }); + + expect(result).toEqual({ error: "Could not get session" }); + expect(getEnrollmentAuthorizationError).not.toHaveBeenCalled(); + expect(registerU2F).not.toHaveBeenCalled(); + }); +}); + +describe("verifyU2F", () => { + let getSessionCookieById: any; + let getSession: any; + let verifyU2FRegistration: any; + let getEnrollmentAuthorizationError: any; + + beforeEach(async () => { + vi.clearAllMocks(); + getSessionCookieById = vi.mocked((await import("@/lib/server/cookies")).getSessionCookieById); + getSession = vi.mocked((await import("@/lib/server/zitadel")).getSession); + verifyU2FRegistration = vi.mocked((await import("@/lib/server/zitadel")).verifyU2FRegistration); + getEnrollmentAuthorizationError = vi.mocked( + (await import("@/lib/server/enrollment-guard")).getEnrollmentAuthorizationError, + ); + + getSessionCookieById.mockResolvedValue({ id: "session-1", token: "token-1" }); + getSession.mockResolvedValue(userOnlySession); + }); + + test("rejects verification on an unauthenticated session without persisting the credential", async () => { + getEnrollmentAuthorizationError.mockResolvedValue("User Verification Check has to be done"); + + const result = await verifyU2F({ + u2fId: "u2f-1", + passkeyName: "my key", + publicKeyCredential: {}, + sessionId: "session-1", + }); + + expect(result).toEqual({ error: "User Verification Check has to be done" }); + expect(verifyU2FRegistration).not.toHaveBeenCalled(); + }); + + test("verifies the registration when the session is authorized", async () => { + getEnrollmentAuthorizationError.mockResolvedValue(null); + verifyU2FRegistration.mockResolvedValue({ done: true }); + + const result = await verifyU2F({ + u2fId: "u2f-1", + passkeyName: "my key", + publicKeyCredential: {}, + sessionId: "session-1", + }); + + expect(verifyU2FRegistration).toHaveBeenCalledTimes(1); + expect(result).toEqual({ done: true }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/u2f.ts b/auth/ui/v2/apps/login/src/lib/actions/u2f.ts new file mode 100644 index 0000000..10db754 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/u2f.ts @@ -0,0 +1,105 @@ +"use server"; + +import { getSessionCookieById } from "@/lib/server/cookies"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { getPublicHost } from "@/lib/server/host"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { getSession, registerU2F, verifyU2FRegistration } from "@/lib/server/zitadel"; +import { create } from "@zitadel/client"; +import { VerifyU2FRegistrationRequestSchema } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { headers } from "next/headers"; +import { userAgent } from "next/server"; + +type RegisterU2FCommand = { + sessionId: string; +}; + +type VerifyU2FCommand = { + u2fId: string; + passkeyName?: string; + publicKeyCredential: any; + sessionId: string; +}; + +export async function addU2F(command: RegisterU2FCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const host = getPublicHost(_headers); + + const sessionCookie = await getSessionCookieById({ + sessionId: command.sessionId, + }); + + if (!sessionCookie) { + return { error: "Could not get session" }; + } + + const session = await getSession({ serviceConfig, sessionId: sessionCookie.id, sessionToken: sessionCookie.token }); + + const [hostname] = host.split(":"); + + if (!hostname) { + throw new Error("Could not get hostname"); + } + + const userId = session?.session?.factors?.user?.id; + + if (!session || !userId) { + return { error: "Could not get session" }; + } + + // Enrollment must be authorized: a bare identify-only session (only the user factor set) + // must not be able to attach a new authenticator to the account (GHSA-45f2-5q3r-xgg6). + const enrollmentError = await getEnrollmentAuthorizationError({ serviceConfig, session: session.session!, userId }); + if (enrollmentError) { + return { error: enrollmentError }; + } + + return registerU2F({ serviceConfig, userId, domain: hostname }); +} + +export async function verifyU2F(command: VerifyU2FCommand) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + let passkeyName = command.passkeyName; + if (!passkeyName) { + const headersList = await headers(); + const userAgentStructure = { headers: headersList }; + const { browser, device, os } = userAgent(userAgentStructure); + + passkeyName = `${device.vendor ?? ""} ${device.model ?? ""}${ + device.vendor || device.model ? ", " : "" + }${os.name}${os.name ? ", " : ""}${browser.name}`; + } + const sessionCookie = await getSessionCookieById({ + sessionId: command.sessionId, + }); + + if (!sessionCookie) { + return { error: "Could not get session cookie" }; + } + + const session = await getSession({ serviceConfig, sessionId: sessionCookie.id, sessionToken: sessionCookie.token }); + + const userId = session?.session?.factors?.user?.id; + + if (!userId) { + return { error: "Could not get session" }; + } + + // Enrollment must be authorized: only an authenticated session (or a valid onboarding + // verification) may finish registering a new authenticator (GHSA-45f2-5q3r-xgg6). + const enrollmentError = await getEnrollmentAuthorizationError({ serviceConfig, session: session.session!, userId }); + if (enrollmentError) { + return { error: enrollmentError }; + } + + const request = create(VerifyU2FRegistrationRequestSchema, { + u2fId: command.u2fId, + publicKeyCredential: command.publicKeyCredential, + tokenName: passkeyName, + userId, + }); + + return verifyU2FRegistration({ serviceConfig, request }); +} diff --git a/auth/ui/v2/apps/login/src/lib/actions/verify.test.ts b/auth/ui/v2/apps/login/src/lib/actions/verify.test.ts new file mode 100644 index 0000000..908c75d --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/verify.test.ts @@ -0,0 +1,421 @@ +import { sendVerification, verifyTOTP } from "@/lib/actions/verify"; +import { trySendVerification } from "@/lib/server/verification-email"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { getSessionCookieByLoginName } from "@/lib/server/cookies"; +import { createSessionAndUpdateCookie } from "@/lib/server/session-cookie"; +import { + createInviteCode, + getSession, + getUserByID, + listAuthenticationMethodTypes, + verifyEmail, + sendEmailCode as zitadelSendEmailCode, +} from "@/lib/server/zitadel"; +import { cookies } from "next/headers"; + +// Mock dependencies +vi.mock("@/lib/server/zitadel", () => ({ + verifyEmail: vi.fn(), + verifyInviteCode: vi.fn(), + getUserByID: vi.fn(), + getSession: vi.fn(), + listAuthenticationMethodTypes: vi.fn(), + getLoginSettings: vi.fn(), + sendEmailCode: vi.fn(), + createInviteCode: vi.fn(), + verifyTOTPRegistration: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + loadMostRecentSession: vi.fn(), +})); + +vi.mock("@/lib/server/enrollment-guard", () => ({ + getEnrollmentAuthorizationError: vi.fn(), +})); + +vi.mock("next/headers", () => ({ + headers: vi.fn(), + cookies: vi.fn(), +})); + +vi.mock("@/lib/server/cookies", () => ({ + getSessionCookieByLoginName: vi.fn(), +})); + +vi.mock("@/lib/server/session-cookie", () => ({ + createSessionAndUpdateCookie: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: {} })), +})); + +vi.mock("@/lib/server/verification-check", () => ({ + setUserVerificationCheckCookie: vi.fn(), +})); + +vi.mock("@/lib/server/host", () => ({ + getPublicHostWithProtocol: vi.fn(() => "https://example.com"), +})); + +vi.mock("next-intl/server", () => ({ + getTranslations: vi.fn(() => (key: string) => key), +})); + +describe("sendVerification", () => { + let mockVerifyEmail: any; + let mockGetUserByID: any; + let mockGetSession: any; + let mockListAuthenticationMethodTypes: any; + let mockGetSessionCookieByLoginName: any; + let mockCreateSessionAndUpdateCookie: any; + let mockCookies: any; + + beforeEach(() => { + mockVerifyEmail = verifyEmail; + mockGetUserByID = getUserByID; + mockGetSession = getSession; + mockListAuthenticationMethodTypes = listAuthenticationMethodTypes; + mockGetSessionCookieByLoginName = getSessionCookieByLoginName; + mockCreateSessionAndUpdateCookie = createSessionAndUpdateCookie; + mockCookies = cookies; + + // Default valid checking setup + mockVerifyEmail.mockResolvedValue({}); + mockGetUserByID.mockResolvedValue({ + user: { userId: "user-1", preferredLoginName: "test@example.com" }, + }); + mockCookies.mockResolvedValue({ + set: vi.fn(), + }); + }); + + test("should handle failing getSession when no auth methods exist (stale cookie scenario)", async () => { + // 1. Cookie exists + mockGetSessionCookieByLoginName.mockResolvedValue({ + id: "stale-session-id", + token: "stale-token", + }); + + // 2. getSession fails (throws or returns null/invalid) + // Simulating call returning nothing useful or throwing + mockGetSession.mockRejectedValue(new Error("Session not found")); + // OR: mockGetSession.mockResolvedValue({}); // depending on how generic client behaves + + // 3. No auth methods (user needs setup) + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [], + }); + + // 4. Mock session creation success + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-id", + factors: { user: { id: "user-1", loginName: "test@example.com", organizationId: "org-1" } }, + }, + }); + + const result = await sendVerification({ + userId: "user-1", + code: "123456", + isInvite: false, + }); + + // Expect redirect to authenticator setup + expect(result).toEqual({ + redirect: "/authenticator/set?sessionId=new-session-id&loginName=test%40example.com", + }); + + // Verify getSession was called (and failed, but we recovered) + expect(mockGetSession).toHaveBeenCalled(); + // Verify creation was attempted + expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled(); + // The signed verification check is issued for the verified user + const { setUserVerificationCheckCookie } = await import("@/lib/server/verification-check"); + expect(setUserVerificationCheckCookie).toHaveBeenCalledWith("user-1"); + }); + + test("should include requestId in /authenticator/set redirect when provided", async () => { + // 1. No existing session cookie + mockGetSessionCookieByLoginName.mockResolvedValue(undefined); + + // 2. No auth methods (user needs setup) + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [], + }); + + // 3. Mock session creation success + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-id", + factors: { user: { id: "user-1", loginName: "test@example.com", organizationId: "org-1" } }, + }, + }); + + const result = await sendVerification({ + userId: "user-1", + code: "123456", + isInvite: false, + requestId: "oidc_auth-req-123", + }); + + // Expect redirect to include requestId + expect(result).toEqual({ + redirect: expect.stringContaining("/authenticator/set?"), + }); + const redirectUrl = (result as { redirect: string }).redirect; + const params = new URLSearchParams(redirectUrl.split("?")[1]); + expect(params.get("requestId")).toBe("oidc_auth-req-123"); + expect(params.get("sessionId")).toBe("new-session-id"); + expect(params.get("loginName")).toBe("test@example.com"); + }); + + test("should NOT include requestId in /authenticator/set redirect when not provided", async () => { + // 1. No existing session cookie + mockGetSessionCookieByLoginName.mockResolvedValue(undefined); + + // 2. No auth methods (user needs setup) + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [], + }); + + // 3. Mock session creation success + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-id", + factors: { user: { id: "user-1", loginName: "test@example.com", organizationId: "org-1" } }, + }, + }); + + const result = await sendVerification({ + userId: "user-1", + code: "123456", + isInvite: false, + // no requestId + }); + + const redirectUrl = (result as { redirect: string }).redirect; + const params = new URLSearchParams(redirectUrl.split("?")[1]); + expect(params.get("requestId")).toBeNull(); + }); + + test("should fall back to user.preferredLoginName for session cookie lookup when loginName is undefined", async () => { + // Simulate the email-link scenario: loginName is undefined but userId is provided + mockGetSessionCookieByLoginName.mockResolvedValue(undefined); + mockGetUserByID.mockResolvedValue({ + user: { userId: "user-1", preferredLoginName: "test@example.com" }, + }); + mockListAuthenticationMethodTypes.mockResolvedValue({ + authMethodTypes: [], + }); + mockCreateSessionAndUpdateCookie.mockResolvedValue({ + session: { + id: "new-session-id", + factors: { user: { id: "user-1", loginName: "test@example.com", organizationId: "org-1" } }, + }, + }); + + await sendVerification({ + userId: "user-1", + code: "123456", + isInvite: false, + loginName: undefined, // explicitly undefined, like from email link + }); + + // The key assertion: session cookie lookup should use preferredLoginName as fallback + expect(mockGetSessionCookieByLoginName).toHaveBeenCalledWith({ + loginName: "test@example.com", + organization: undefined, + }); + }); +}); + +describe("trySendVerification", () => { + let mockSendEmailCode: any; + let mockCreateInviteCode: any; + let originalBasePath: string | undefined; + + beforeEach(() => { + originalBasePath = process.env.NEXT_PUBLIC_BASE_PATH; + process.env.NEXT_PUBLIC_BASE_PATH = "/ui/v2/login"; + + vi.clearAllMocks(); + mockSendEmailCode = zitadelSendEmailCode; + mockCreateInviteCode = createInviteCode; + mockSendEmailCode.mockResolvedValue({}); + mockCreateInviteCode.mockResolvedValue({}); + }); + + afterEach(() => { + if (originalBasePath === undefined) { + delete process.env.NEXT_PUBLIC_BASE_PATH; + } else { + process.env.NEXT_PUBLIC_BASE_PATH = originalBasePath; + } + }); + + test("should call sendEmailCode with correct URL template for non-invite and return true", async () => { + const result = await trySendVerification({ + userId: "user-1", + isInvite: false, + }); + + expect(result).toBe(true); + expect(mockSendEmailCode).toHaveBeenCalledWith({ + serviceConfig: {}, + userId: "user-1", + urlTemplate: "https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}", + }); + expect(mockCreateInviteCode).not.toHaveBeenCalled(); + }); + + test("should call createInviteCode with correct URL template for invite and return true", async () => { + const result = await trySendVerification({ + userId: "user-1", + isInvite: true, + }); + + expect(result).toBe(true); + expect(mockCreateInviteCode).toHaveBeenCalledWith({ + serviceConfig: {}, + userId: "user-1", + urlTemplate: + "https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true", + }); + expect(mockSendEmailCode).not.toHaveBeenCalled(); + }); + + test("should include URL-encoded requestId in URL template", async () => { + const result = await trySendVerification({ + userId: "user-1", + isInvite: false, + requestId: "req-123", + }); + + expect(result).toBe(true); + expect(mockSendEmailCode).toHaveBeenCalledWith({ + serviceConfig: {}, + userId: "user-1", + urlTemplate: + "https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&requestId=req-123", + }); + }); + + test("should URL-encode special characters in requestId", async () => { + const result = await trySendVerification({ + userId: "user-1", + isInvite: false, + requestId: "req&id=injected", + }); + + expect(result).toBe(true); + expect(mockSendEmailCode).toHaveBeenCalledWith({ + serviceConfig: {}, + userId: "user-1", + urlTemplate: + "https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&requestId=req%26id%3Dinjected", + }); + }); + + test("should include invite=true and requestId for invite with requestId", async () => { + const result = await trySendVerification({ + userId: "user-1", + isInvite: true, + requestId: "req-456", + }); + + expect(result).toBe(true); + expect(mockCreateInviteCode).toHaveBeenCalledWith({ + serviceConfig: {}, + userId: "user-1", + urlTemplate: + "https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true&requestId=req-456", + }); + }); + + test("should return false when sendEmailCode fails", async () => { + mockSendEmailCode.mockRejectedValue(new Error("Network error")); + + const result = await trySendVerification({ + userId: "user-1", + isInvite: false, + }); + + expect(result).toBe(false); + }); + + test("should return false when createInviteCode fails", async () => { + mockCreateInviteCode.mockRejectedValue(new Error("Already invited")); + + const result = await trySendVerification({ + userId: "user-1", + isInvite: true, + }); + + expect(result).toBe(false); + }); +}); + +describe("verifyTOTP", () => { + let mockLoadMostRecentSession: any; + let mockVerifyTOTPRegistration: any; + let mockGetEnrollmentAuthorizationError: any; + + const totpSession = { + id: "session-1", + factors: { user: { id: "victim-1", loginName: "victim@example.com" } }, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + const _headers = await import("next/headers"); + vi.mocked(_headers.headers).mockResolvedValue(new Headers() as any); + + mockLoadMostRecentSession = vi.mocked((await import("@/lib/server/session")).loadMostRecentSession); + mockVerifyTOTPRegistration = vi.mocked((await import("@/lib/server/zitadel")).verifyTOTPRegistration); + mockGetEnrollmentAuthorizationError = vi.mocked( + (await import("@/lib/server/enrollment-guard")).getEnrollmentAuthorizationError, + ); + + mockLoadMostRecentSession.mockResolvedValue(totpSession); + }); + + test("rejects TOTP enrollment on an unauthenticated (identify-only) session", async () => { + mockGetEnrollmentAuthorizationError.mockResolvedValue( + "You have to authenticate or have a valid User Verification Check", + ); + + const result = await verifyTOTP("123456", "victim@example.com", "org-1"); + + expect(result).toEqual({ error: "You have to authenticate or have a valid User Verification Check" }); + expect(mockGetEnrollmentAuthorizationError).toHaveBeenCalledWith({ + serviceConfig: {}, + session: totpSession, + userId: "victim-1", + }); + expect(mockVerifyTOTPRegistration).not.toHaveBeenCalled(); + }); + + test("verifies TOTP registration when the session is authorized", async () => { + mockGetEnrollmentAuthorizationError.mockResolvedValue(null); + mockVerifyTOTPRegistration.mockResolvedValue({ done: true }); + + const result = await verifyTOTP("123456", "victim@example.com", "org-1"); + + expect(mockVerifyTOTPRegistration).toHaveBeenCalledWith({ + serviceConfig: {}, + code: "123456", + userId: "victim-1", + }); + expect(result).toEqual({ done: true }); + }); + + test("throws when the session has no user id", async () => { + mockLoadMostRecentSession.mockResolvedValue({ id: "session-1", factors: {} }); + + await expect(verifyTOTP("123456")).rejects.toThrow("No user id found in session."); + expect(mockVerifyTOTPRegistration).not.toHaveBeenCalled(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/actions/verify.ts b/auth/ui/v2/apps/login/src/lib/actions/verify.ts new file mode 100644 index 0000000..9b5586d --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/actions/verify.ts @@ -0,0 +1,276 @@ +"use server"; + +import { createLogger } from "@/lib/server/logger"; +import { + createInviteCode, + getLoginSettings, + getSession, + getUserByID, + listAuthenticationMethodTypes, + verifyEmail, + verifyInviteCode, + verifyTOTPRegistration, + sendEmailCode as zitadelSendEmailCode, +} from "@/lib/server/zitadel"; + +import { completeFlowOrGetUrl } from "@/lib/actions/flow"; +import { getSessionCookieByLoginName } from "@/lib/server/cookies"; +import { getEnrollmentAuthorizationError } from "@/lib/server/enrollment-guard"; +import { getPublicHostWithProtocol } from "@/lib/server/host"; +import { checkMFAFactors } from "@/lib/server/mfa-helper"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { loadMostRecentSession } from "@/lib/server/session"; +import { createSessionAndUpdateCookie } from "@/lib/server/session-cookie"; +import { setUserVerificationCheckCookie } from "@/lib/server/verification-check"; +import { buildVerificationUrlTemplate } from "@/lib/server/verification-email"; +import { create } from "@zitadel/client"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb"; +import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb"; +import { getTranslations } from "next-intl/server"; +import { headers } from "next/headers"; + +const logger = createLogger("verify"); + +export async function verifyTOTP(code: string, loginName?: string, organization?: string) { + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + return loadMostRecentSession({ + serviceConfig, + sessionParams: { + loginName, + organization, + }, + }).then(async (session) => { + if (session?.factors?.user?.id) { + // Enrollment must be authorized: a bare identify-only session must not be able to + // activate a TOTP factor on the account (GHSA-45f2-5q3r-xgg6). + const enrollmentError = await getEnrollmentAuthorizationError({ + serviceConfig, + session, + userId: session.factors.user.id, + }); + if (enrollmentError) { + return { error: enrollmentError }; + } + + return verifyTOTPRegistration({ serviceConfig, code, userId: session.factors.user.id }); + } else { + throw Error("No user id found in session."); + } + }); +} + +type VerifyUserByEmailCommand = { + userId: string; + loginName?: string; // to determine already existing session + organization?: string; + code: string; + isInvite: boolean; + requestId?: string; +}; + +export async function sendVerification(command: VerifyUserByEmailCommand) { + const t = await getTranslations("verify"); + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const verifyResponse = command.isInvite + ? await verifyInviteCode({ serviceConfig, userId: command.userId, verificationCode: command.code }).catch((error) => { + logger.warn("Could not verify invite:", { error }); + return { error: t("errors.couldNotVerifyInvite") }; + }) + : await verifyEmail({ serviceConfig, userId: command.userId, verificationCode: command.code }).catch((error) => { + logger.warn("Could not verify email:", { error }); + return { error: t("errors.couldNotVerifyEmail") }; + }); + + if ("error" in verifyResponse) { + return verifyResponse; + } + + if (!verifyResponse) { + return { error: t("errors.couldNotVerify") }; + } + + let session: Session | undefined; + const userResponse = await getUserByID({ serviceConfig, userId: command.userId }); + + if (!userResponse || !userResponse.user) { + return { error: t("errors.couldNotLoadUser") }; + } + + const user = userResponse.user; + + const sessionCookie = await getSessionCookieByLoginName({ + loginName: command.loginName ?? user.preferredLoginName, + organization: command.organization, + }); + + if (sessionCookie) { + session = await getSession({ serviceConfig, sessionId: sessionCookie.id, sessionToken: sessionCookie.token }) + .then((response) => { + if (response?.session) { + return response.session; + } + }) + .catch((error) => { + // user session is not found, so we create a new one + logger.warn("[verify] user session is not found, so we create a new one", { error }); + return undefined; + }); + } + + // load auth methods for user + const authMethodResponse = await listAuthenticationMethodTypes({ serviceConfig, userId: user.userId }); + + if (!authMethodResponse || !authMethodResponse.authMethodTypes) { + return { error: t("errors.couldNotLoadAuthenticators") }; + } + + const hasPrimaryMethod = + authMethodResponse?.authMethodTypes?.some( + (m: AuthenticationMethodType) => + m === AuthenticationMethodType.PASSWORD || + m === AuthenticationMethodType.PASSKEY || + m === AuthenticationMethodType.IDP, + ) ?? false; + + // if no primary auth methods are found on the user, redirect to set one up + if (!hasPrimaryMethod) { + if (!session) { + const checks = create(ChecksSchema, { + user: { + search: { + case: "loginName", + value: userResponse.user.preferredLoginName, + }, + }, + }); + + const result = await createSessionAndUpdateCookie({ + checks, + requestId: command.requestId, + }); + session = result.session; + } + + if (!session) { + return { error: t("errors.couldNotCreateSession") }; + } + + const params = new URLSearchParams({ + sessionId: session.id, + }); + + if (session.factors?.user?.loginName) { + params.set("loginName", session.factors?.user?.loginName); + } + + if (command.requestId) { + params.set("requestId", command.requestId); + } + + // remember the successful verification for this browser (signed with a server-only secret), + // checks are done for users with invalid sessions and invalid userAgentId + await setUserVerificationCheckCookie(user.userId); + + return { redirect: `/authenticator/set?${params}` }; + } + + // if no session found only show success page, + // if user is invited, recreate invite flow to not depend on session + if (!session?.factors?.user?.id) { + const verifySuccessParams = new URLSearchParams({}); + + if (command.userId) { + verifySuccessParams.set("userId", command.userId); + } + + if (("loginName" in command && command.loginName) || user.preferredLoginName) { + verifySuccessParams.set( + "loginName", + "loginName" in command && command.loginName ? command.loginName : user.preferredLoginName, + ); + } + if (command.requestId) { + verifySuccessParams.set("requestId", command.requestId); + } + if (command.organization) { + verifySuccessParams.set("organization", command.organization); + } + + return { redirect: `/verify/success?${verifySuccessParams}` }; + } + + const loginSettings = await getLoginSettings({ serviceConfig, organization: user.details?.resourceOwner }); + + // redirect to mfa factor if user has one, or redirect to set one up + const mfaFactorCheck = await checkMFAFactors( + serviceConfig, + session, + loginSettings, + authMethodResponse.authMethodTypes, + command.organization, + command.requestId, + ); + + if (mfaFactorCheck?.redirect) { + return mfaFactorCheck; + } + + // login user if no additional steps are required + if (command.requestId && session.id) { + return completeFlowOrGetUrl( + { + sessionId: session.id, + requestId: command.requestId, + organization: command.organization ?? session.factors?.user?.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); + } + + // Regular flow - return URL for client-side navigation + return completeFlowOrGetUrl( + { + loginName: session.factors.user.loginName, + organization: session.factors?.user?.organizationId, + }, + loginSettings?.defaultRedirectUri, + ); +} + +type resendVerifyEmailCommand = { + userId: string; + isInvite: boolean; + requestId?: string; +}; + +export async function resendVerification(command: resendVerifyEmailCommand) { + const t = await getTranslations("verify"); + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + const hostWithProtocol = await getPublicHostWithProtocol(_headers); + + const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; + const urlTemplate = buildVerificationUrlTemplate(hostWithProtocol, basePath, command.isInvite, command.requestId); + + return command.isInvite + ? createInviteCode({ + serviceConfig, + userId: command.userId, + urlTemplate, + }).catch((error) => { + if (error.code === 9) { + return { error: t("errors.userAlreadyVerified") }; + } + return { error: t("errors.couldNotResendInvite") }; + }) + : zitadelSendEmailCode({ + serviceConfig, + userId: command.userId, + urlTemplate, + }); +} diff --git a/auth/ui/v2/apps/login/src/lib/client-utils.test.ts b/auth/ui/v2/apps/login/src/lib/client-utils.test.ts new file mode 100644 index 0000000..5c04b72 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/client-utils.test.ts @@ -0,0 +1,99 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { isAllowedPostErrorRedirectUrl, isExternalUrl, isSafeRedirectUri } from "./client-utils"; + +describe("isSafeRedirectUri", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + test("should reject empty uri", async () => { + expect(await isSafeRedirectUri("")).toBe(false); + expect(await isSafeRedirectUri(undefined as unknown as string)).toBe(false); + }); + + test("should allow relative paths", async () => { + expect(await isSafeRedirectUri("/dashboard")).toBe(true); + expect(await isSafeRedirectUri("/ui/console")).toBe(true); + expect(await isSafeRedirectUri("/")).toBe(true); + }); + + test("should reject protocol-relative paths", async () => { + expect(await isSafeRedirectUri("//evil.com")).toBe(false); + expect(await isSafeRedirectUri("\\\\evil.com")).toBe(false); + }); + + test("should allow absolute URLs matching the current host", async () => { + expect(await isSafeRedirectUri("https://my-zitadel.com/console")).toBe(true); + }); + + test("should allow absolute URLs to external domains", async () => { + expect(await isSafeRedirectUri("https://evil.com")).toBe(true); + expect(await isSafeRedirectUri("https://settings.com/dashboard")).toBe(true); + }); + + test("should reject non-http(s) protocols", async () => { + expect(await isSafeRedirectUri("javascript:alert(1)")).toBe(false); + expect(await isSafeRedirectUri("data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==")).toBe(false); + expect(await isSafeRedirectUri("file:///etc/passwd")).toBe(false); + }); + + test("should gracefully reject invalid, unparsable URLs that aren't relative", async () => { + expect(await isSafeRedirectUri("not-a-valid-url")).toBe(false); + expect(await isSafeRedirectUri("http://%")).toBe(false); + }); +}); + +describe("isExternalUrl", () => { + test("should return false for relative paths", () => { + expect(isExternalUrl("/dashboard")).toBe(false); + expect(isExternalUrl("/ui/console")).toBe(false); + expect(isExternalUrl("/")).toBe(false); + expect(isExternalUrl("/password?loginName=user@example.com")).toBe(false); + expect(isExternalUrl("/signedin?sessionId=123&organization=456")).toBe(false); + }); + + test("should return true for absolute HTTPS URLs", () => { + expect(isExternalUrl("https://example.com/callback")).toBe(true); + expect(isExternalUrl("https://my-zitadel.com/ui/console")).toBe(true); + }); + + test("should return true for absolute HTTP URLs", () => { + expect(isExternalUrl("http://localhost:3000/callback")).toBe(true); + expect(isExternalUrl("http://example.com")).toBe(true); + }); + + test("should return true for custom protocol schemes (native apps)", () => { + expect(isExternalUrl("myapp://callback")).toBe(true); + expect(isExternalUrl("com.example.app://oauth/callback")).toBe(true); + expect(isExternalUrl("io.zitadel.app://auth")).toBe(true); + expect(isExternalUrl("flutter-app://callback?code=abc&state=xyz")).toBe(true); + }); + + test("should return true for protocol-relative URLs", () => { + expect(isExternalUrl("//evil.com")).toBe(true); + expect(isExternalUrl("//example.com/path")).toBe(true); + }); +}); + +describe("isAllowedPostErrorRedirectUrl", () => { + test("accepts the known back link targets", () => { + expect(isAllowedPostErrorRedirectUrl("/loginname")).toBe(true); + expect(isAllowedPostErrorRedirectUrl("/idp")).toBe(true); + }); + + test.each([ + "https://evil.example", + "//evil.example", + "/\\evil.example", + "javascript:alert(1)", + "data:text/html,x", + "", + undefined, + "/loginname/x", + "/loginname?x=1", + " /loginname", + "/LOGINNAME", + ])("rejects %s", (url) => { + expect(isAllowedPostErrorRedirectUrl(url)).toBe(false); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/client-utils.ts b/auth/ui/v2/apps/login/src/lib/client-utils.ts new file mode 100644 index 0000000..bc2bd98 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/client-utils.ts @@ -0,0 +1,100 @@ +import { sanitizeUrl } from "@braintree/sanitize-url"; + +export type ServerActionResponse = + | { redirect: string } + | { error: string } + | { samlData: { url: string; fields: Record } } + | undefined + | null; + +export function handleServerActionResponse( + response: ServerActionResponse, + router: { push: (url: string) => void }, + setSamlData: (data: { url: string; fields: Record }) => void, + setError: (error: string) => void, +): boolean { + if (!response) { + return false; + } + + if ("redirect" in response && response.redirect) { + if (isSafeRedirectUri(response.redirect)) { + if (typeof window !== "undefined" && isExternalUrl(response.redirect)) { + // External/custom-protocol URLs: use window.location for full navigation. + // router.push() would trigger an RSC prefetch fetch() that gets blocked + // by CSP connect-src 'self' for non-same-origin URLs. + // CodeQL: This is safe — the URL is validated by isSafeRedirectUri above, + // which blocks javascript:, data:, file:, blob:, and about: schemes. + window.location.href = response.redirect; // lgtm[js/client-side-unvalidated-url-redirection] + } else { + router.push(response.redirect); + } + return true; + } else { + console.warn("handleServerActionResponse: Blocked unsafe redirect URI:", response.redirect); + setError("Unsafe redirect URI was blocked"); + return true; + } + } + + if ("samlData" in response && response.samlData) { + if (isSafeRedirectUri(response.samlData.url)) { + setSamlData(response.samlData); + return true; + } else { + console.warn("handleServerActionResponse: Blocked unsafe SAML post URL:", response.samlData.url); + setError("Unsafe redirect URI was blocked"); + return true; + } + } + + if ("error" in response && response.error) { + setError(response.error); + return true; + } + + return false; +} + +/** + * Returns true if the URL is external (absolute URL or custom protocol). + * Relative paths (starting with "/" but not "//") are considered internal. + */ +export function isExternalUrl(url: string): boolean { + if (url.startsWith("/") && !url.startsWith("//")) { + return false; + } + return true; +} + +const SANITIZE_BLANK = "about:blank"; +const EXTRA_BLOCKED = new Set(["file:", "blob:", "about:"]); + +/** Allowlist for the back link on the IdP error pages. */ +export function isAllowedPostErrorRedirectUrl(url: string | undefined): url is "/loginname" | "/idp" { + return url === "/loginname" || url === "/idp"; +} + +/** + * Validates whether a given redirect URI is safe. + * Safe URIs are either relative paths or absolute URLs matching the current host. + * This prevents open redirect vulnerabilities and XSS via javascript:/data: URIs. + */ +export function isSafeRedirectUri(uri: string): boolean { + if (!uri) return false; + + // 1. Relative paths are generally safe + if (uri.startsWith("/") && !uri.startsWith("//")) { + return true; + } + + const sanitized = sanitizeUrl(uri); + if (sanitized === SANITIZE_BLANK) return false; + + try { + const parsed = new URL(sanitized); + return !EXTRA_BLOCKED.has(parsed.protocol); + } catch { + return false; + } +} diff --git a/auth/ui/v2/apps/login/src/lib/constants.ts b/auth/ui/v2/apps/login/src/lib/constants.ts new file mode 100644 index 0000000..3156862 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/constants.ts @@ -0,0 +1 @@ +export const UNKNOWN_USER_ID = "000000000000000000"; diff --git a/auth/ui/v2/apps/login/src/lib/i18n.ts b/auth/ui/v2/apps/login/src/lib/i18n.ts new file mode 100644 index 0000000..961fca3 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/i18n.ts @@ -0,0 +1,86 @@ +export interface Lang { + name: string; + code: string; +} + +export const LANGS: Lang[] = [ + { + name: "English", + code: "en", + }, + { + name: "Deutsch", + code: "de", + }, + { + name: "Italiano", + code: "it", + }, + { + name: "Español", + code: "es", + }, + { + name: "Français", + code: "fr", + }, + { + name: "Nederlands", + code: "nl", + }, + { + name: "Polski", + code: "pl", + }, + { + name: "Português", + code: "pt", + }, + { + name: "简体中文", + code: "zh", + }, + { + name: "Русский", + code: "ru", + }, + { + name: "Magyar", + code: "hu", + }, + { + name: "Türkçe", + code: "tr", + }, + { + name: "日本語", + code: "ja", + }, + { + name: "Українська", + code: "uk", + }, + { + name: "العربية", + code: "ar", + }, +]; + +export const LANGUAGE_COOKIE_NAME = "NEXT_LOCALE"; +export const LANGUAGE_HEADER_NAME = "accept-language"; + +export function shouldUILocalesOverrideCookie(): boolean { + return process.env.ZITADEL_UI_LOCALES_OVERRIDE_COOKIE === "true"; +} + +export function getLanguage(code: string): Lang { + const lang = LANGS.find((l) => l.code === code); + if (lang) { + return lang; + } + + return { + code, + name: new Intl.DisplayNames([code], { type: "language" }).of(code) || code, + }; +} diff --git a/auth/ui/v2/apps/login/src/lib/idp-errors.test.ts b/auth/ui/v2/apps/login/src/lib/idp-errors.test.ts new file mode 100644 index 0000000..abeaaee --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/idp-errors.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, test } from "vitest"; +import { isKnownIdpError } from "./idp-errors"; + +describe("isKnownIdpError", () => { + test.each([ + ["flow_mismatch", true], + ["missing_idp_info", true], + ["session_mismatch", true], + ["external_idp_taken", true], + ["Your account is locked, call 555", false], + ["", false], + [undefined, false], + ])("%s -> %s", (code, expected) => { + expect(isKnownIdpError(code)).toBe(expected); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/idp-errors.ts b/auth/ui/v2/apps/login/src/lib/idp-errors.ts new file mode 100644 index 0000000..aca68c1 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/idp-errors.ts @@ -0,0 +1,19 @@ +// only these codes are shown on the failure and linking-failed pages, anything else in the URL is ignored +const KNOWN_IDP_ERRORS = new Set([ + "flow_mismatch", + "no_organization_context", + "missing_idp_user_info", + "user_creation_failed", + "missing_idp_info", + "session_invalid", + "session_mismatch", + "linking_not_allowed", + "user_not_found", + "validation_failed", + "missing_organization", + "external_idp_taken", +]); + +export function isKnownIdpError(code: string | undefined): code is string { + return !!code && KNOWN_IDP_ERRORS.has(code); +} diff --git a/auth/ui/v2/apps/login/src/lib/idp.test.ts b/auth/ui/v2/apps/login/src/lib/idp.test.ts new file mode 100644 index 0000000..bfaff32 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/idp.test.ts @@ -0,0 +1,361 @@ +import { IDPType } from "@zitadel/proto/zitadel/idp/v2/idp_pb"; +import { IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { describe, expect, it } from "vitest"; +import { idpTypeToIdentityProviderType, idpTypeToSlug } from "./idp"; + +describe("idp type mapping utilities", () => { + describe("idpTypeToSlug", () => { + it("should map GITHUB to 'github'", () => { + const result = idpTypeToSlug(IdentityProviderType.GITHUB); + expect(result).toBe("github"); + }); + + it("should map GITHUB_ES to 'github_es'", () => { + const result = idpTypeToSlug(IdentityProviderType.GITHUB_ES); + expect(result).toBe("github_es"); + }); + + it("should map GITLAB to 'gitlab'", () => { + const result = idpTypeToSlug(IdentityProviderType.GITLAB); + expect(result).toBe("gitlab"); + }); + + it("should map GITLAB_SELF_HOSTED to 'gitlab_es'", () => { + const result = idpTypeToSlug(IdentityProviderType.GITLAB_SELF_HOSTED); + expect(result).toBe("gitlab_es"); + }); + + it("should map APPLE to 'apple'", () => { + const result = idpTypeToSlug(IdentityProviderType.APPLE); + expect(result).toBe("apple"); + }); + + it("should map GOOGLE to 'google'", () => { + const result = idpTypeToSlug(IdentityProviderType.GOOGLE); + expect(result).toBe("google"); + }); + + it("should map AZURE_AD to 'azure'", () => { + const result = idpTypeToSlug(IdentityProviderType.AZURE_AD); + expect(result).toBe("azure"); + }); + + it("should map SAML to 'saml'", () => { + const result = idpTypeToSlug(IdentityProviderType.SAML); + expect(result).toBe("saml"); + }); + + it("should map OAUTH to 'oauth'", () => { + const result = idpTypeToSlug(IdentityProviderType.OAUTH); + expect(result).toBe("oauth"); + }); + + it("should map OIDC to 'oidc'", () => { + const result = idpTypeToSlug(IdentityProviderType.OIDC); + expect(result).toBe("oidc"); + }); + + it("should map LDAP to 'ldap'", () => { + const result = idpTypeToSlug(IdentityProviderType.LDAP); + expect(result).toBe("ldap"); + }); + + it("should map JWT to 'jwt'", () => { + const result = idpTypeToSlug(IdentityProviderType.JWT); + expect(result).toBe("jwt"); + }); + + it("should map ZITADEL to 'zitadel'", () => { + const result = idpTypeToSlug(IdentityProviderType.ZITADEL); + expect(result).toBe("zitadel"); + }); + + it("should throw error for unknown identity provider type", () => { + // Using a value that doesn't match any known type + const unknownType = 9999 as IdentityProviderType; + + expect(() => idpTypeToSlug(unknownType)).toThrow("Unknown identity provider type"); + }); + + it("should throw error for undefined type", () => { + const undefinedType = undefined as any as IdentityProviderType; + expect(() => idpTypeToSlug(undefinedType)).toThrow(); + }); + + it("should handle all defined IdentityProviderType enum values", () => { + // This test ensures all enum values are handled + const handledTypes = [ + IdentityProviderType.GITHUB, + IdentityProviderType.GITHUB_ES, + IdentityProviderType.GITLAB, + IdentityProviderType.GITLAB_SELF_HOSTED, + IdentityProviderType.APPLE, + IdentityProviderType.GOOGLE, + IdentityProviderType.AZURE_AD, + IdentityProviderType.SAML, + IdentityProviderType.OAUTH, + IdentityProviderType.OIDC, + IdentityProviderType.LDAP, + IdentityProviderType.JWT, + IdentityProviderType.ZITADEL, + ]; + + handledTypes.forEach((type) => { + expect(() => idpTypeToSlug(type)).not.toThrow(); + }); + }); + + it("should return consistent slugs for the same input", () => { + const type = IdentityProviderType.GITHUB; + const result1 = idpTypeToSlug(type); + const result2 = idpTypeToSlug(type); + + expect(result1).toBe(result2); + }); + + it("should return lowercase slugs", () => { + const types = [ + IdentityProviderType.GITHUB, + IdentityProviderType.GOOGLE, + IdentityProviderType.AZURE_AD, + IdentityProviderType.SAML, + ]; + + types.forEach((type) => { + const slug = idpTypeToSlug(type); + expect(slug).toBe(slug.toLowerCase()); + }); + }); + }); + + describe("idpTypeToIdentityProviderType", () => { + it("should map IDP_TYPE_GITHUB to GITHUB", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_GITHUB); + expect(result).toBe(IdentityProviderType.GITHUB); + }); + + it("should map IDP_TYPE_GITHUB_ES to GITHUB_ES", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_GITHUB_ES); + expect(result).toBe(IdentityProviderType.GITHUB_ES); + }); + + it("should map IDP_TYPE_GITLAB to GITLAB", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_GITLAB); + expect(result).toBe(IdentityProviderType.GITLAB); + }); + + it("should map IDP_TYPE_GITLAB_SELF_HOSTED to GITLAB_SELF_HOSTED", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_GITLAB_SELF_HOSTED); + expect(result).toBe(IdentityProviderType.GITLAB_SELF_HOSTED); + }); + + it("should map IDP_TYPE_APPLE to APPLE", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_APPLE); + expect(result).toBe(IdentityProviderType.APPLE); + }); + + it("should map IDP_TYPE_GOOGLE to GOOGLE", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_GOOGLE); + expect(result).toBe(IdentityProviderType.GOOGLE); + }); + + it("should map IDP_TYPE_AZURE_AD to AZURE_AD", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_AZURE_AD); + expect(result).toBe(IdentityProviderType.AZURE_AD); + }); + + it("should map IDP_TYPE_SAML to SAML", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_SAML); + expect(result).toBe(IdentityProviderType.SAML); + }); + + it("should map IDP_TYPE_OAUTH to OAUTH", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_OAUTH); + expect(result).toBe(IdentityProviderType.OAUTH); + }); + + it("should map IDP_TYPE_OIDC to OIDC", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_OIDC); + expect(result).toBe(IdentityProviderType.OIDC); + }); + + it("should map IDP_TYPE_JWT to JWT", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_JWT); + expect(result).toBe(IdentityProviderType.JWT); + }); + + it("should map IDP_TYPE_ZITADEL to ZITADEL", () => { + const result = idpTypeToIdentityProviderType(IDPType.IDP_TYPE_ZITADEL); + expect(result).toBe(IdentityProviderType.ZITADEL); + }); + + it("should throw error for unknown IDP type", () => { + // Using a value that doesn't match any known type + const unknownType = 9999 as IDPType; + + expect(() => idpTypeToIdentityProviderType(unknownType)).toThrow("Unknown identity provider type"); + }); + + it("should throw error for undefined type", () => { + const undefinedType = undefined as any as IDPType; + expect(() => idpTypeToIdentityProviderType(undefinedType)).toThrow(); + }); + + it("should handle all defined IDPType enum values", () => { + const handledTypes = [ + IDPType.IDP_TYPE_GITHUB, + IDPType.IDP_TYPE_GITHUB_ES, + IDPType.IDP_TYPE_GITLAB, + IDPType.IDP_TYPE_GITLAB_SELF_HOSTED, + IDPType.IDP_TYPE_APPLE, + IDPType.IDP_TYPE_GOOGLE, + IDPType.IDP_TYPE_AZURE_AD, + IDPType.IDP_TYPE_SAML, + IDPType.IDP_TYPE_OAUTH, + IDPType.IDP_TYPE_OIDC, + IDPType.IDP_TYPE_JWT, + IDPType.IDP_TYPE_ZITADEL, + ]; + + handledTypes.forEach((type) => { + expect(() => idpTypeToIdentityProviderType(type)).not.toThrow(); + }); + }); + + it("should return consistent results for the same input", () => { + const type = IDPType.IDP_TYPE_GITHUB; + const result1 = idpTypeToIdentityProviderType(type); + const result2 = idpTypeToIdentityProviderType(type); + + expect(result1).toBe(result2); + }); + + it("should return valid IdentityProviderType enum values", () => { + const types = [IDPType.IDP_TYPE_GITHUB, IDPType.IDP_TYPE_GOOGLE, IDPType.IDP_TYPE_AZURE_AD]; + + types.forEach((type) => { + const result = idpTypeToIdentityProviderType(type); + expect(Object.values(IdentityProviderType)).toContain(result); + }); + }); + }); + + describe("round-trip conversions", () => { + it("should successfully convert IDPType -> IdentityProviderType -> slug", () => { + const idpType = IDPType.IDP_TYPE_GITHUB; + const identityProviderType = idpTypeToIdentityProviderType(idpType); + const slug = idpTypeToSlug(identityProviderType); + + expect(slug).toBe("github"); + }); + + it("should handle enterprise providers in round-trip", () => { + const idpType = IDPType.IDP_TYPE_AZURE_AD; + const identityProviderType = idpTypeToIdentityProviderType(idpType); + const slug = idpTypeToSlug(identityProviderType); + + expect(slug).toBe("azure"); + }); + + it("should handle self-hosted variants", () => { + const githubES = IDPType.IDP_TYPE_GITHUB_ES; + const gitlabSH = IDPType.IDP_TYPE_GITLAB_SELF_HOSTED; + + const githubESType = idpTypeToIdentityProviderType(githubES); + const gitlabSHType = idpTypeToIdentityProviderType(gitlabSH); + + const githubESSlug = idpTypeToSlug(githubESType); + const gitlabSHSlug = idpTypeToSlug(gitlabSHType); + + expect(githubESSlug).toBe("github_es"); + expect(gitlabSHSlug).toBe("gitlab_es"); + }); + + it("should handle protocol-based providers", () => { + const providers = [ + { idpType: IDPType.IDP_TYPE_OIDC, expectedSlug: "oidc" }, + { idpType: IDPType.IDP_TYPE_OAUTH, expectedSlug: "oauth" }, + { idpType: IDPType.IDP_TYPE_SAML, expectedSlug: "saml" }, + { idpType: IDPType.IDP_TYPE_JWT, expectedSlug: "jwt" }, + ]; + + providers.forEach(({ idpType, expectedSlug }) => { + const identityProviderType = idpTypeToIdentityProviderType(idpType); + const slug = idpTypeToSlug(identityProviderType); + expect(slug).toBe(expectedSlug); + }); + }); + + it("should handle all supported providers in complete round-trip", () => { + const allProviders = [ + { idpType: IDPType.IDP_TYPE_GITHUB, slug: "github" }, + { idpType: IDPType.IDP_TYPE_GITHUB_ES, slug: "github_es" }, + { idpType: IDPType.IDP_TYPE_GITLAB, slug: "gitlab" }, + { idpType: IDPType.IDP_TYPE_GITLAB_SELF_HOSTED, slug: "gitlab_es" }, + { idpType: IDPType.IDP_TYPE_APPLE, slug: "apple" }, + { idpType: IDPType.IDP_TYPE_GOOGLE, slug: "google" }, + { idpType: IDPType.IDP_TYPE_AZURE_AD, slug: "azure" }, + { idpType: IDPType.IDP_TYPE_SAML, slug: "saml" }, + { idpType: IDPType.IDP_TYPE_OAUTH, slug: "oauth" }, + { idpType: IDPType.IDP_TYPE_OIDC, slug: "oidc" }, + { idpType: IDPType.IDP_TYPE_JWT, slug: "jwt" }, + ]; + + allProviders.forEach(({ idpType, slug }) => { + const identityProviderType = idpTypeToIdentityProviderType(idpType); + const actualSlug = idpTypeToSlug(identityProviderType); + expect(actualSlug).toBe(slug); + }); + }); + }); + + describe("slug uniqueness", () => { + it("should generate unique slugs for different providers", () => { + const types = [ + IdentityProviderType.GITHUB, + IdentityProviderType.GITLAB, + IdentityProviderType.GOOGLE, + IdentityProviderType.APPLE, + IdentityProviderType.AZURE_AD, + IdentityProviderType.SAML, + IdentityProviderType.OIDC, + IdentityProviderType.OAUTH, + IdentityProviderType.LDAP, + IdentityProviderType.JWT, + IdentityProviderType.ZITADEL, + ]; + + const slugs = types.map((type) => idpTypeToSlug(type)); + const uniqueSlugs = new Set(slugs); + + expect(uniqueSlugs.size).toBe(slugs.length); + }); + + it("should use consistent naming convention for enterprise variants", () => { + const githubES = idpTypeToSlug(IdentityProviderType.GITHUB_ES); + const gitlabSH = idpTypeToSlug(IdentityProviderType.GITLAB_SELF_HOSTED); + + // Both use _es suffix for enterprise/self-hosted + expect(githubES).toContain("_es"); + expect(gitlabSH).toContain("_es"); + }); + }); + + describe("error handling", () => { + it("should provide clear error messages", () => { + const unknownType = 9999 as IdentityProviderType; + + expect(() => idpTypeToSlug(unknownType)).toThrow(/Unknown identity provider type/); + }); + + it("should handle undefined gracefully with error", () => { + expect(() => idpTypeToSlug(undefined as any)).toThrow(); + expect(() => idpTypeToIdentityProviderType(undefined as any)).toThrow(); + }); + + it("should handle null gracefully with error", () => { + expect(() => idpTypeToSlug(null as any)).toThrow(); + expect(() => idpTypeToIdentityProviderType(null as any)).toThrow(); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/idp.ts b/auth/ui/v2/apps/login/src/lib/idp.ts new file mode 100644 index 0000000..916e7e9 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/idp.ts @@ -0,0 +1,80 @@ +import { IDPType } from "@zitadel/proto/zitadel/idp/v2/idp_pb"; +import { IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; + +// This maps the IdentityProviderType to a slug which is used in the /success and /failure routes +export function idpTypeToSlug(idpType: IdentityProviderType) { + switch (idpType) { + case IdentityProviderType.GITHUB: + return "github"; + case IdentityProviderType.GITHUB_ES: + return "github_es"; + case IdentityProviderType.GITLAB: + return "gitlab"; + case IdentityProviderType.GITLAB_SELF_HOSTED: + return "gitlab_es"; + case IdentityProviderType.APPLE: + return "apple"; + case IdentityProviderType.GOOGLE: + return "google"; + case IdentityProviderType.AZURE_AD: + return "azure"; + case IdentityProviderType.SAML: + return "saml"; + case IdentityProviderType.OAUTH: + return "oauth"; + case IdentityProviderType.OIDC: + return "oidc"; + case IdentityProviderType.LDAP: + return "ldap"; + case IdentityProviderType.JWT: + return "jwt"; + case IdentityProviderType.ZITADEL: + return "zitadel"; + default: + throw new Error("Unknown identity provider type"); + } +} + +// TODO: this is ugly but needed atm as the getIDPByID returns a IDPType and not a IdentityProviderType +export function idpTypeToIdentityProviderType(idpType: IDPType): IdentityProviderType { + switch (idpType) { + case IDPType.IDP_TYPE_GITHUB: + return IdentityProviderType.GITHUB; + + case IDPType.IDP_TYPE_GITHUB_ES: + return IdentityProviderType.GITHUB_ES; + + case IDPType.IDP_TYPE_GITLAB: + return IdentityProviderType.GITLAB; + + case IDPType.IDP_TYPE_GITLAB_SELF_HOSTED: + return IdentityProviderType.GITLAB_SELF_HOSTED; + + case IDPType.IDP_TYPE_APPLE: + return IdentityProviderType.APPLE; + + case IDPType.IDP_TYPE_GOOGLE: + return IdentityProviderType.GOOGLE; + + case IDPType.IDP_TYPE_AZURE_AD: + return IdentityProviderType.AZURE_AD; + + case IDPType.IDP_TYPE_SAML: + return IdentityProviderType.SAML; + + case IDPType.IDP_TYPE_OAUTH: + return IdentityProviderType.OAUTH; + + case IDPType.IDP_TYPE_OIDC: + return IdentityProviderType.OIDC; + + case IDPType.IDP_TYPE_JWT: + return IdentityProviderType.JWT; + + case IDPType.IDP_TYPE_ZITADEL: + return IdentityProviderType.ZITADEL; + + default: + throw new Error("Unknown identity provider type"); + } +} diff --git a/auth/ui/v2/apps/login/src/lib/legal-links.test.ts b/auth/ui/v2/apps/login/src/lib/legal-links.test.ts new file mode 100644 index 0000000..45be86f --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/legal-links.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { resolveLocalizedLegalLink } from "./legal-links"; + +describe("resolveLocalizedLegalLink", () => { + it("replaces the language placeholder with the active locale", () => { + expect(resolveLocalizedLegalLink("https://example.com/{{.Lang}}/terms", "de")).toBe("https://example.com/de/terms"); + }); + + it("replaces every language placeholder in the link", () => { + expect(resolveLocalizedLegalLink("https://example.com/{{.Lang}}/docs?lang={{.Lang}}", "fr")).toBe( + "https://example.com/fr/docs?lang=fr", + ); + }); + + it("returns the original link when no placeholder is present", () => { + expect(resolveLocalizedLegalLink("https://example.com/terms", "en")).toBe("https://example.com/terms"); + }); + + it("returns the original link when locale is missing", () => { + expect(resolveLocalizedLegalLink("https://example.com/{{.Lang}}/terms", undefined)).toBe( + "https://example.com/{{.Lang}}/terms", + ); + }); + + it("returns undefined when the link is missing", () => { + expect(resolveLocalizedLegalLink(undefined, "en")).toBeUndefined(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/legal-links.ts b/auth/ui/v2/apps/login/src/lib/legal-links.ts new file mode 100644 index 0000000..f8bc5ab --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/legal-links.ts @@ -0,0 +1,9 @@ +const LANGUAGE_PLACEHOLDER = "{{.Lang}}"; + +export function resolveLocalizedLegalLink(link: string | undefined, locale: string | undefined): string | undefined { + if (!link || !locale) { + return link; + } + + return link.replaceAll(LANGUAGE_PLACEHOLDER, locale); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/api.test.ts b/auth/ui/v2/apps/login/src/lib/server/api.test.ts new file mode 100644 index 0000000..160405a --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/api.test.ts @@ -0,0 +1,120 @@ +// @vitest-environment node +import { newSystemToken } from "@zitadel/client/node"; +import { exec } from "child_process"; +import { promisify } from "util"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const execAsync = promisify(exec); + +const { stdout: pkcs1Key } = await execAsync( + "openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 2>/dev/null | openssl rsa -traditional 2>/dev/null", +); + +const { stdout: pkcs8Key } = await execAsync("openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 2>/dev/null"); + +describe("newSystemToken key format support", () => { + test("should sign a JWT with a PKCS#8 key (BEGIN PRIVATE KEY)", async () => { + expect(pkcs8Key).toContain("BEGIN PRIVATE KEY"); + + const token = await newSystemToken({ + audience: "https://example.com", + subject: "login-client", + key: pkcs8Key, + }); + + expect(token).toBeDefined(); + expect(typeof token).toBe("string"); + expect(token.split(".")).toHaveLength(3); + }); + + test("should sign a JWT with a PKCS#1 key (BEGIN RSA PRIVATE KEY)", async () => { + expect(pkcs1Key).toContain("BEGIN RSA PRIVATE KEY"); + + const token = await newSystemToken({ + audience: "https://example.com", + subject: "login-client", + key: pkcs1Key, + }); + + expect(token).toBeDefined(); + expect(typeof token).toBe("string"); + expect(token.split(".")).toHaveLength(3); + }); +}); + +describe("loginClientKeyToken", () => { + const originalEnv = process.env; + let mockReadFile: ReturnType; + let mockNewSystemToken: ReturnType; + + beforeEach(() => { + process.env = { ...originalEnv }; + vi.resetModules(); + + mockReadFile = vi.fn(); + mockNewSystemToken = vi.fn(); + + vi.doMock("fs/promises", () => ({ readFile: mockReadFile })); + vi.doMock("@zitadel/client/node", () => ({ newSystemToken: mockNewSystemToken })); + }); + + afterEach(() => { + process.env = originalEnv; + }); + + test("should read key file and create token with hardcoded subject", async () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = "/path/to/key.pem"; + process.env.AUDIENCE = "https://api.zitadel.cloud"; + + mockReadFile.mockResolvedValue("-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----"); + mockNewSystemToken.mockResolvedValue("signed-jwt-token"); + + const { loginClientKeyToken } = await import("@/lib/server/api"); + const token = await loginClientKeyToken(); + + expect(token).toBe("signed-jwt-token"); + expect(mockReadFile).toHaveBeenCalledWith("/path/to/key.pem", "utf-8"); + expect(mockNewSystemToken).toHaveBeenCalledWith({ + audience: "https://api.zitadel.cloud", + subject: "login-client", + key: "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----", + }); + }); + + test("should cache key and not re-read file on subsequent calls", async () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = "/path/to/key.pem"; + process.env.AUDIENCE = "https://api.zitadel.cloud"; + + mockReadFile.mockResolvedValue("cached-key"); + mockNewSystemToken.mockResolvedValue("token"); + + const { loginClientKeyToken } = await import("@/lib/server/api"); + await loginClientKeyToken(); + await loginClientKeyToken(); + + expect(mockReadFile).toHaveBeenCalledTimes(1); + }); + + test("should fall back to ZITADEL_API_URL when AUDIENCE is not set", async () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = "/path/to/key.pem"; + process.env.AUDIENCE = undefined as any; + process.env.ZITADEL_API_URL = "https://zitadel.example.com"; + + mockReadFile.mockResolvedValue("key-content"); + mockNewSystemToken.mockResolvedValue("token"); + + const { loginClientKeyToken } = await import("@/lib/server/api"); + await loginClientKeyToken(); + + expect(mockNewSystemToken).toHaveBeenCalledWith(expect.objectContaining({ audience: "https://zitadel.example.com" })); + }); + + test("should throw a clear error when key file cannot be read", async () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = "/nonexistent/key.pem"; + + mockReadFile.mockRejectedValue(new Error("ENOENT: no such file or directory")); + + const { loginClientKeyToken } = await import("@/lib/server/api"); + await expect(loginClientKeyToken()).rejects.toThrow('Failed to read login client key file "/nonexistent/key.pem"'); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/api.ts b/auth/ui/v2/apps/login/src/lib/server/api.ts new file mode 100644 index 0000000..233d2cd --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/api.ts @@ -0,0 +1,67 @@ +import "server-only"; + +import { newSystemToken } from "@zitadel/client/node"; +import { readFile } from "fs/promises"; + +// Keys are only loaded once from disk per process. +// If a file changes you need to restart the process to pick up the new key. +let keyToken: string | undefined; +let loginClientKeyCache: string | undefined; + +async function getTokenFromFile(): Promise { + if (keyToken) { + return keyToken; + } + + keyToken = await readFile(process.env.SYSTEM_USER_PRIVATE_KEY_FILE, "binary"); + return keyToken; +} + +/** + * Creates a signed JWT token using system user credentials from environment + * variables. The SYSTEM_USER_PRIVATE_KEY is expected to be base64-encoded and + * is decoded before signing. Requires AUDIENCE, SYSTEM_USER_ID, and + * SYSTEM_USER_PRIVATE_KEY to be set in the environment. + * + * @returns A signed JWT token string for authenticating API requests. + * @throws If the underlying token signing fails. + */ +export async function systemAPIToken() { + const key = process.env.SYSTEM_USER_PRIVATE_KEY_FILE + ? await getTokenFromFile() + : Buffer.from(process.env.SYSTEM_USER_PRIVATE_KEY, "base64").toString("utf-8"); + + return newSystemToken({ + audience: process.env.AUDIENCE, + subject: process.env.SYSTEM_USER_ID, + key, + }); +} + +/** + * Creates a signed JWT token by reading a private key from the file path + * specified in ZITADEL_LOGINCLIENT_KEYFILE. Uses a hardcoded subject of + * "login-client". The audience is resolved from AUDIENCE or ZITADEL_API_URL. + * + * @returns A signed JWT token string for authenticating API requests. + * @throws If the key file cannot be read or the token signing fails. + */ +export async function loginClientKeyToken() { + const keyFile = process.env.ZITADEL_LOGINCLIENT_KEYFILE!; + + if (!loginClientKeyCache) { + try { + loginClientKeyCache = await readFile(keyFile, "utf-8"); + } catch (err) { + throw new Error(`Failed to read login client key file "${keyFile}": ${err instanceof Error ? err.message : err}`, { + cause: err, + }); + } + } + + return newSystemToken({ + audience: process.env.AUDIENCE || process.env.ZITADEL_API_URL, + subject: "login-client", + key: loginClientKeyCache, + }); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/auth-flow.ts b/auth/ui/v2/apps/login/src/lib/server/auth-flow.ts new file mode 100644 index 0000000..1cadb92 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/auth-flow.ts @@ -0,0 +1,92 @@ +import "server-only"; + +import { getAllSessions } from "@/lib/server/cookies"; +import { createLogger } from "@/lib/server/logger"; +import { loginWithOIDCAndSession } from "@/lib/server/oidc"; +import { loginWithSAMLAndSession } from "@/lib/server/saml"; +import { getServiceConfig } from "@/lib/server/service-url"; +import { listSessions, ServiceConfig } from "@/lib/server/zitadel"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { headers } from "next/headers"; + +const logger = createLogger("auth-flow"); + +export interface AuthFlowParams { + sessionId: string; + requestId: string; + organization?: string; +} + +async function loadSessions({ serviceConfig, ids }: { serviceConfig: ServiceConfig; ids: string[] }): Promise { + const response = await listSessions({ serviceConfig, ids: ids.filter((id: string | undefined) => !!id) }); + + return response?.sessions ?? []; +} + +/** + * Complete OIDC/SAML authentication flow with session + * This is the shared logic for flow completion + * Returns either an error or a redirect URL for client-side navigation + */ +export async function completeAuthFlow( + command: AuthFlowParams, +): Promise<{ error: string } | { redirect: string } | { samlData: { url: string; fields: Record } }> { + const { sessionId, requestId } = command; + + const _headers = await headers(); + const { serviceConfig } = getServiceConfig(_headers); + + const sessionCookies = await getAllSessions(); + const ids = sessionCookies.map((s) => s.id); + let sessions: Session[] = []; + + if (ids && ids.length) { + sessions = await loadSessions({ serviceConfig, ids }); + } + + if (requestId.startsWith("oidc_")) { + // Complete OIDC flow + const result = await loginWithOIDCAndSession({ + serviceConfig, + authRequest: requestId.replace("oidc_", ""), + sessionId, + sessions, + sessionCookies, + }); + + // Safety net - ensure we always return a valid object + if ( + !result || + typeof result !== "object" || + (!("redirect" in result) && !("error" in result) && !("samlData" in result)) + ) { + logger.error("Auth flow: Invalid result from loginWithOIDCAndSession:", { result }); + return { error: "Authentication completed but navigation failed" }; + } + + return result; + } else if (requestId.startsWith("saml_")) { + // Complete SAML flow + const result = await loginWithSAMLAndSession({ + serviceConfig, + samlRequest: requestId.replace("saml_", ""), + sessionId, + sessions, + sessionCookies, + }); + + // Safety net - ensure we always return a valid object + if ( + !result || + typeof result !== "object" || + (!("redirect" in result) && !("error" in result) && !("samlData" in result)) + ) { + logger.error("Auth flow: Invalid result from loginWithSAMLAndSession:", { result }); + return { error: "Authentication completed but navigation failed" }; + } + + return result; + } + + return { error: "Invalid request ID format" }; +} diff --git a/auth/ui/v2/apps/login/src/lib/server/auth-utils.test.ts b/auth/ui/v2/apps/login/src/lib/server/auth-utils.test.ts new file mode 100644 index 0000000..90238d6 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/auth-utils.test.ts @@ -0,0 +1,265 @@ +import { + equalsIgnoreCase, + getValidLocaleFromUILocales, + isRSCRequest, + isValidLanguage, + validateAuthRequest, +} from "@/lib/server/auth-utils"; +import { describe, expect, it } from "vitest"; + +describe("auth-utils", () => { + describe("equalsIgnoreCase", () => { + it("should match identifiers regardless of case", () => { + expect(equalsIgnoreCase("jackson@example.com", "Jackson@Example.com")).toBe(true); + expect(equalsIgnoreCase("USER@ORGDOMAIN.COM", "user@orgdomain.com")).toBe(true); + expect(equalsIgnoreCase("user", "user")).toBe(true); + }); + + it("should not match different identifiers", () => { + expect(equalsIgnoreCase("jackson@example.com", "jane@example.com")).toBe(false); + expect(equalsIgnoreCase("user@example.com", "user@other.com")).toBe(false); + }); + + it("should return false when either value is undefined", () => { + expect(equalsIgnoreCase(undefined, "user@example.com")).toBe(false); + expect(equalsIgnoreCase("user@example.com", undefined)).toBe(false); + expect(equalsIgnoreCase(undefined, undefined)).toBe(false); + }); + }); + + describe("isValidLanguage", () => { + it("should return true for valid language codes", () => { + expect(isValidLanguage("en")).toBe(true); + expect(isValidLanguage("de")).toBe(true); + expect(isValidLanguage("fr")).toBe(true); + expect(isValidLanguage("zh")).toBe(true); + }); + + it("should return false for invalid language codes", () => { + expect(isValidLanguage("invalid")).toBe(false); + expect(isValidLanguage("xx")).toBe(false); + expect(isValidLanguage("")).toBe(false); + }); + + it("should be case-insensitive", () => { + expect(isValidLanguage("EN")).toBe(true); + expect(isValidLanguage("De")).toBe(true); + }); + }); + + describe("getValidLocaleFromUILocales", () => { + it("should return null for undefined or empty array", () => { + expect(getValidLocaleFromUILocales(undefined)).toBeNull(); + expect(getValidLocaleFromUILocales([])).toBeNull(); + }); + + it("should extract valid language from simple locale codes", () => { + expect(getValidLocaleFromUILocales(["de"])).toBe("de"); + expect(getValidLocaleFromUILocales(["en", "de"])).toBe("en"); + }); + + it("should extract language code from language tags", () => { + expect(getValidLocaleFromUILocales(["de-CH"])).toBe("de"); + expect(getValidLocaleFromUILocales(["en-US"])).toBe("en"); + expect(getValidLocaleFromUILocales(["zh-CN"])).toBe("zh"); + }); + + it("should return first valid language when multiple provided", () => { + expect(getValidLocaleFromUILocales(["xx-XX", "de", "en"])).toBe("de"); + }); + + it("should return null when no valid languages found", () => { + expect(getValidLocaleFromUILocales(["xx", "yy", "zz"])).toBeNull(); + }); + + it("should handle case-insensitive matching", () => { + expect(getValidLocaleFromUILocales(["DE"])).toBe("de"); + expect(getValidLocaleFromUILocales(["En-US"])).toBe("en"); + }); + }); + + describe("validateAuthRequest", () => { + it("should return null when no auth parameters are present", () => { + const searchParams = new URLSearchParams(); + const result = validateAuthRequest(searchParams); + expect(result).toBeNull(); + }); + + it("should return requestId when explicitly provided", () => { + const searchParams = new URLSearchParams({ + requestId: "explicit-request-123", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("explicit-request-123"); + }); + + it("should generate OIDC requestId from authRequest parameter", () => { + const searchParams = new URLSearchParams({ + authRequest: "oidc-auth-456", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("oidc_oidc-auth-456"); + }); + + it("should generate SAML requestId from samlRequest parameter", () => { + const searchParams = new URLSearchParams({ + samlRequest: "saml-req-789", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("saml_saml-req-789"); + }); + + it("should prioritize explicit requestId over authRequest", () => { + const searchParams = new URLSearchParams({ + requestId: "explicit-123", + authRequest: "oidc-456", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("explicit-123"); + }); + + it("should prioritize explicit requestId over samlRequest", () => { + const searchParams = new URLSearchParams({ + requestId: "explicit-123", + samlRequest: "saml-456", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("explicit-123"); + }); + + it("should handle both authRequest and samlRequest, preferring OIDC", () => { + const searchParams = new URLSearchParams({ + authRequest: "oidc-123", + samlRequest: "saml-456", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("oidc_oidc-123"); + }); + + it("should handle empty string requestId", () => { + const searchParams = new URLSearchParams({ + requestId: "", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBeNull(); + }); + + it("should handle whitespace in requestId", () => { + const searchParams = new URLSearchParams({ + requestId: " request-with-spaces ", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe(" request-with-spaces "); + }); + + it("should handle special characters in requestId", () => { + const searchParams = new URLSearchParams({ + requestId: "request-!@#$%^&*()", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("request-!@#$%^&*()"); + }); + + it("should handle URL-encoded values", () => { + const searchParams = new URLSearchParams({ + authRequest: "oidc encoded", + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe("oidc_oidc encoded"); + }); + + it("should handle very long requestId values", () => { + const longId = "a".repeat(1000); + const searchParams = new URLSearchParams({ + requestId: longId, + }); + const result = validateAuthRequest(searchParams); + expect(result).toBe(longId); + }); + }); + + describe("isRSCRequest", () => { + it("should return true when _rsc parameter is present", () => { + const searchParams = new URLSearchParams({ + _rsc: "1", + }); + const result = isRSCRequest(searchParams); + expect(result).toBe(true); + }); + + it("should return true when _rsc parameter has empty value", () => { + const searchParams = new URLSearchParams({ + _rsc: "", + }); + const result = isRSCRequest(searchParams); + expect(result).toBe(true); + }); + + it("should return false when _rsc parameter is not present", () => { + const searchParams = new URLSearchParams({ + other: "param", + }); + const result = isRSCRequest(searchParams); + expect(result).toBe(false); + }); + + it("should return false for empty search params", () => { + const searchParams = new URLSearchParams(); + const result = isRSCRequest(searchParams); + expect(result).toBe(false); + }); + + it("should return true regardless of _rsc value", () => { + const searchParams = new URLSearchParams({ + _rsc: "any-value-123", + }); + const result = isRSCRequest(searchParams); + expect(result).toBe(true); + }); + + it("should work with multiple parameters", () => { + const searchParams = new URLSearchParams({ + authRequest: "123", + _rsc: "1", + other: "param", + }); + const result = isRSCRequest(searchParams); + expect(result).toBe(true); + }); + + it("should be case-sensitive for parameter name", () => { + const searchParams = new URLSearchParams({ + _RSC: "1", + }); + const result = isRSCRequest(searchParams); + expect(result).toBe(false); + }); + }); + + describe("integration: validateAuthRequest and isRSCRequest", () => { + it("should handle typical OIDC auth flow with RSC", () => { + const searchParams = new URLSearchParams({ + authRequest: "oidc-123", + _rsc: "1", + }); + + const requestId = validateAuthRequest(searchParams); + const isRSC = isRSCRequest(searchParams); + + expect(requestId).toBe("oidc_oidc-123"); + expect(isRSC).toBe(true); + }); + + it("should handle SAML flow without RSC", () => { + const searchParams = new URLSearchParams({ + samlRequest: "saml-456", + }); + + const requestId = validateAuthRequest(searchParams); + const isRSC = isRSCRequest(searchParams); + + expect(requestId).toBe("saml_saml-456"); + expect(isRSC).toBe(false); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/auth-utils.ts b/auth/ui/v2/apps/login/src/lib/server/auth-utils.ts new file mode 100644 index 0000000..a32833d --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/auth-utils.ts @@ -0,0 +1,83 @@ +import "server-only"; + +import { LANGS } from "@/lib/i18n"; + +/** + * Authentication utility functions that don't require server actions + */ + +/** + * Compare two identifiers (loginname, email, phone) case insensitively. + * + * User lookup is performed with EQUALS_IGNORE_CASE, so any follow up check that + * verifies *which* identifier the user was found by has to ignore case as well. + * Otherwise entering "Jackson@example.com" for the user "jackson@example.com" + * resolves the user but is then rejected as unknown. + */ +export function equalsIgnoreCase(a: string | undefined, b: string | undefined): boolean { + if (a === undefined || b === undefined) { + return false; + } + return a.toLowerCase() === b.toLowerCase(); +} + +/** + * Check if a language code is valid (supported by the login UI) + */ +export function isValidLanguage(code: string): boolean { + const normalized = code.trim().toLowerCase(); + return LANGS.some((lang) => lang.code === normalized); +} + +/** + * Extract a valid language code from uiLocales array. + * Returns the first valid language code (normalized to lowercase), or null if none found. + */ +export function getValidLocaleFromUILocales(uiLocales: string[] | undefined): string | null { + if (!uiLocales || uiLocales.length === 0) { + return null; + } + + for (const locale of uiLocales) { + const normalized = locale.trim().toLowerCase(); + + // Check if the full locale is a valid language code (e.g., "de", "EN") + if (isValidLanguage(normalized)) { + return normalized; + } + + // uiLocales may contain language tags like "en-US" or "de-CH" + // Extract the language code (part before the hyphen) + // Note: this strips any regional specifier + // e.g., de-CH and de-AT both become just de + // zh-Hans-CN (Simplified) and zh-Hant-TW (Traditional) both become zh + // As of time of writing, this is expected behaviour, since there is only one translation for all languages + const languageCode = normalized.split("-")[0]; + if (isValidLanguage(languageCode)) { + return languageCode; + } + } + + return null; +} + +/** + * Validate authentication request parameters + */ +export function validateAuthRequest(searchParams: URLSearchParams): string | null { + const oidcRequestId = searchParams.get("authRequest"); + const samlRequestId = searchParams.get("samlRequest"); + + const requestId = + searchParams.get("requestId") ?? + (oidcRequestId ? `oidc_${oidcRequestId}` : samlRequestId ? `saml_${samlRequestId}` : undefined); + + return requestId || null; +} + +/** + * Check if request is an RSC request + */ +export function isRSCRequest(searchParams: URLSearchParams): boolean { + return searchParams.has("_rsc"); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/cache.test.ts b/auth/ui/v2/apps/login/src/lib/server/cache.test.ts new file mode 100644 index 0000000..75dd19a --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/cache.test.ts @@ -0,0 +1,251 @@ +import { PromiseCache } from "@/lib/server/cache"; +import { afterEach, describe, expect, test, vi } from "vitest"; + +// Suppress logger output during tests +vi.mock("@/lib/server/logger", () => ({ + createLogger: () => ({ + warn: vi.fn(), + info: vi.fn(), + error: vi.fn(), + debug: vi.fn(), + }), +})); + +/** + * Creates a mock clock for lru-cache's `perf` option. + * lru-cache uses `performance.now()` internally for TTL tracking, and caches + * the reference at import time. The `perf` option lets us inject a custom clock. + */ +function mockClock(initial = 1000) { + let now = initial; + return { + perf: { now: () => now }, + advance: (ms: number) => { + now += ms; + }, + }; +} + +describe("PromiseCache", () => { + let cache: PromiseCache; + + afterEach(() => { + cache?.clear(); + }); + + describe("getOrFetch", () => { + test("should return the fetcher result on cache miss", async () => { + cache = new PromiseCache(10); + const result = await cache.getOrFetch("key1", () => Promise.resolve("value1"), 60_000); + expect(result).toBe("value1"); + expect(cache.size).toBe(1); + }); + + test("should return cached value on cache hit", async () => { + cache = new PromiseCache(10); + let callCount = 0; + const fetcher = () => { + callCount++; + return Promise.resolve(`value-${callCount}`); + }; + + const first = await cache.getOrFetch("key1", fetcher, 60_000); + const second = await cache.getOrFetch("key1", fetcher, 60_000); + + expect(first).toBe("value-1"); + expect(second).toBe("value-1"); + expect(callCount).toBe(1); + }); + + test("should return stale value immediately after TTL expires (SWR)", async () => { + const clock = mockClock(); + cache = new PromiseCache(10, clock.perf); + + let callCount = 0; + let resolveRevalidation: ((v: string) => void) | undefined; + + const fetcher = () => { + callCount++; + if (callCount === 1) { + return Promise.resolve("value-1"); + } + // Second call: return a promise we control + return new Promise((resolve) => { + resolveRevalidation = resolve; + }); + }; + + // First call — blocks on fetch + const first = await cache.getOrFetch("key1", fetcher, 100); + expect(first).toBe("value-1"); + expect(callCount).toBe(1); + + // Expire the entry + clock.advance(101); + + // Second call after expiry — should get stale value immediately + const second = await cache.getOrFetch("key1", fetcher, 100); + expect(second).toBe("value-1"); // stale value, not blocking + expect(callCount).toBe(2); // revalidation was triggered + + // Third call while revalidation is in-flight — also gets stale value + const third = await cache.getOrFetch("key1", fetcher, 100); + expect(third).toBe("value-1"); // stale value + expect(callCount).toBe(2); // no additional fetch (already revalidating) + + // Resolve the background revalidation and flush the .then() chain + resolveRevalidation!("value-2"); + await new Promise((r) => setTimeout(r, 0)); + await new Promise((r) => setTimeout(r, 0)); + + // Now we should get the fresh value + const fourth = await cache.getOrFetch("key1", fetcher, 100); + expect(fourth).toBe("value-2"); + }); + + test("should keep stale value when revalidation fails", async () => { + const clock = mockClock(); + cache = new PromiseCache(10, clock.perf); + + let callCount = 0; + + const fetcher = () => { + callCount++; + if (callCount === 1) { + return Promise.resolve("value-1"); + } + return Promise.reject(new Error("network error")); + }; + + const first = await cache.getOrFetch("key1", fetcher, 100); + expect(first).toBe("value-1"); + + clock.advance(101); + + // After TTL: returns stale, triggers failing revalidation + const second = await cache.getOrFetch("key1", fetcher, 100); + expect(second).toBe("value-1"); + expect(callCount).toBe(2); + + // Flush the rejected promise's handlers + await new Promise((r) => setTimeout(r, 0)); + await new Promise((r) => setTimeout(r, 0)); + + // Next call can retry + clock.advance(1); + const third = await cache.getOrFetch("key1", fetcher, 100); + expect(third).toBe("value-1"); // still stale + expect(callCount).toBe(3); // retried + }); + + test("should re-fetch after entry is evicted", async () => { + cache = new PromiseCache(10); + let callCount = 0; + const fetcher = () => { + callCount++; + return Promise.resolve(`value-${callCount}`); + }; + + const first = await cache.getOrFetch("key1", fetcher, 60_000); + expect(first).toBe("value-1"); + + // Evict the entry manually + cache.clear(); + + const second = await cache.getOrFetch("key1", fetcher, 60_000); + expect(second).toBe("value-2"); + expect(callCount).toBe(2); + }); + + test("should reject on first-fetch failure", async () => { + cache = new PromiseCache(10); + const failingFetcher = () => Promise.reject(new Error("fail")); + + await expect(cache.getOrFetch("key1", failingFetcher, 60_000)).rejects.toThrow(); + + // Wait a tick for internal cleanup + await new Promise((r) => setTimeout(r, 0)); + expect(cache.size).toBe(0); + }); + + test("should deduplicate concurrent requests for the same key", async () => { + cache = new PromiseCache(10); + let callCount = 0; + const fetcher = () => { + callCount++; + return new Promise((resolve) => setTimeout(() => resolve(`value-${callCount}`), 10)); + }; + + const [a, b] = await Promise.all([ + cache.getOrFetch("key1", fetcher, 60_000), + cache.getOrFetch("key1", fetcher, 60_000), + ]); + + expect(a).toBe("value-1"); + expect(b).toBe("value-1"); + expect(callCount).toBe(1); + }); + }); + + describe("maxSize eviction", () => { + test("should evict entries when maxSize is exceeded", async () => { + cache = new PromiseCache(3); + + await cache.getOrFetch("a", () => Promise.resolve(1), 60_000); + await cache.getOrFetch("b", () => Promise.resolve(2), 60_000); + await cache.getOrFetch("c", () => Promise.resolve(3), 60_000); + expect(cache.size).toBe(3); + + // Adding a 4th entry should trigger eviction of the LRU entry ("a") + await cache.getOrFetch("d", () => Promise.resolve(4), 60_000); + expect(cache.size).toBe(3); + + // "a" should have been evicted — re-fetching should call a new fetcher + let refetched = false; + await cache.getOrFetch( + "a", + () => { + refetched = true; + return Promise.resolve(10); + }, + 60_000, + ); + expect(refetched).toBe(true); + }); + + test("should respect maxSize of 1", async () => { + cache = new PromiseCache(1); + + await cache.getOrFetch("a", () => Promise.resolve(1), 60_000); + expect(cache.size).toBe(1); + + await cache.getOrFetch("b", () => Promise.resolve(2), 60_000); + expect(cache.size).toBe(1); + + // Only "b" should remain + let aRefetched = false; + await cache.getOrFetch( + "a", + () => { + aRefetched = true; + return Promise.resolve(10); + }, + 60_000, + ); + expect(aRefetched).toBe(true); + }); + }); + + describe("clear", () => { + test("should remove all entries", async () => { + cache = new PromiseCache(10); + + await cache.getOrFetch("a", () => Promise.resolve(1), 60_000); + await cache.getOrFetch("b", () => Promise.resolve(2), 60_000); + expect(cache.size).toBe(2); + + cache.clear(); + expect(cache.size).toBe(0); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/cache.ts b/auth/ui/v2/apps/login/src/lib/server/cache.ts new file mode 100644 index 0000000..ff0af88 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/cache.ts @@ -0,0 +1,63 @@ +import "server-only"; + +import { LRUCache } from "lru-cache"; + +interface FetchContext { + fetcher: () => Promise; +} + +/** + * A bounded, stale-while-revalidate in-memory promise cache backed by lru-cache. + * + * Features: + * - True LRU eviction + * - Deduplicates concurrent requests (built-in to lru-cache's fetchMethod) + * - Serves stale data immediately while revalidating in the background + * - Keeps stale value on fetch rejection + * - Bounded to `maxSize` entries to prevent unbounded memory growth + */ +export class PromiseCache { + private readonly cache: LRUCache; + + constructor(maxSize = 100_000, perf?: { now: () => number }) { + this.cache = new LRUCache({ + max: Math.max(1, maxSize), + // A global TTL is required to initialize lru-cache's TTL tracking internals. + // Per-entry TTLs passed to fetch() will override this default. + ttl: 1, + allowStale: true, + noDeleteOnStaleGet: true, + noDeleteOnFetchRejection: true, + allowStaleOnFetchRejection: true, + fetchMethod: async (_key, _staleValue, { context }) => { + return context.fetcher(); + }, + ...(perf ? { perf, ttlResolution: 0 } : {}), + }); + } + + /** + * Get a cached value or execute the fetcher and cache its result. + * + * After the first successful fetch, expired entries return the stale + * value immediately and trigger a background revalidation (SWR). + * Only the very first call for a key (or after eviction) blocks + * on the fetch. + */ + getOrFetch(key: string, fetcher: () => Promise, ttlMs: number): Promise { + return this.cache.forceFetch(key, { + ttl: ttlMs, + context: { fetcher }, + }) as Promise; + } + + /** Current number of entries (including stale). */ + get size(): number { + return this.cache.size; + } + + /** Clear all entries. */ + clear(): void { + this.cache.clear(); + } +} diff --git a/auth/ui/v2/apps/login/src/lib/server/challenges.test.ts b/auth/ui/v2/apps/login/src/lib/server/challenges.test.ts new file mode 100644 index 0000000..14621ae --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/challenges.test.ts @@ -0,0 +1,143 @@ +import { create } from "@zitadel/client"; +import { RequestChallengesSchema } from "@zitadel/proto/zitadel/session/v2/challenge_pb"; +import { afterEach, assert, describe, expect, it, vi } from "vitest"; +import { getOTPSMSResendCooldownSeconds, getOTPSMSRetryAfterSeconds, sanitizeChallenges } from "./challenges"; + +describe("sanitizeChallenges", () => { + it("returns undefined when no challenges are requested", () => { + expect(sanitizeChallenges(undefined)).toBeUndefined(); + }); + + it("forces returnCode off for an OTP SMS challenge", () => { + const challenges = create(RequestChallengesSchema, { + otpSms: { returnCode: true }, + }); + + expect(sanitizeChallenges(challenges)?.otpSms?.returnCode).toBe(false); + }); + + it("leaves an OTP SMS challenge that already sends the code alone", () => { + const challenges = create(RequestChallengesSchema, { + otpSms: {}, + }); + + expect(sanitizeChallenges(challenges)?.otpSms?.returnCode).toBe(false); + }); + + it("rewrites an OTP email returnCode challenge to sendCode", () => { + const challenges = create(RequestChallengesSchema, { + otpEmail: { deliveryType: { case: "returnCode", value: {} } }, + }); + + const deliveryType = sanitizeChallenges(challenges)?.otpEmail?.deliveryType; + + assert(deliveryType?.case === "sendCode"); + // no url template: Zitadel falls back to its default verification url + expect(deliveryType.value.urlTemplate).toBeUndefined(); + }); + + it("preserves the url template of an OTP email sendCode challenge", () => { + const urlTemplate = "https://example.com/otp/verify?code={{.Code}}"; + const challenges = create(RequestChallengesSchema, { + otpEmail: { deliveryType: { case: "sendCode", value: { urlTemplate } } }, + }); + + const deliveryType = sanitizeChallenges(challenges)?.otpEmail?.deliveryType; + + assert(deliveryType?.case === "sendCode"); + expect(deliveryType.value.urlTemplate).toBe(urlTemplate); + }); + + it("passes a WebAuthN challenge through untouched", () => { + const challenges = create(RequestChallengesSchema, { + webAuthN: { domain: "login.example.com", userVerificationRequirement: 1 }, + }); + + expect(sanitizeChallenges(challenges)?.webAuthN).toEqual(challenges.webAuthN); + }); + + it("strips returnCode from both OTP methods requested together", () => { + const challenges = create(RequestChallengesSchema, { + otpSms: { returnCode: true }, + otpEmail: { deliveryType: { case: "returnCode", value: {} } }, + }); + + const sanitized = sanitizeChallenges(challenges); + + expect(sanitized?.otpSms?.returnCode).toBe(false); + expect(sanitized?.otpEmail?.deliveryType?.case).toBe("sendCode"); + }); + + it("does not mutate the caller's challenges", () => { + const challenges = create(RequestChallengesSchema, { + otpSms: { returnCode: true }, + otpEmail: { deliveryType: { case: "returnCode", value: {} } }, + }); + + sanitizeChallenges(challenges); + + expect(challenges.otpSms?.returnCode).toBe(true); + expect(challenges.otpEmail?.deliveryType?.case).toBe("returnCode"); + }); +}); + +describe("getOTPSMSResendCooldownSeconds", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("defaults to 30 seconds", () => { + vi.stubEnv("OTP_SMS_RESEND_COOLDOWN_SECONDS", undefined); + expect(getOTPSMSResendCooldownSeconds()).toBe(30); + }); + + it("uses the configured value", () => { + vi.stubEnv("OTP_SMS_RESEND_COOLDOWN_SECONDS", "60"); + expect(getOTPSMSResendCooldownSeconds()).toBe(60); + }); + + it("allows disabling the cooldown with 0", () => { + vi.stubEnv("OTP_SMS_RESEND_COOLDOWN_SECONDS", "0"); + expect(getOTPSMSResendCooldownSeconds()).toBe(0); + }); + + it.each(["", "abc", "-5", "1.5"])("falls back to the default for the invalid value %j", (value) => { + vi.stubEnv("OTP_SMS_RESEND_COOLDOWN_SECONDS", value); + expect(getOTPSMSResendCooldownSeconds()).toBe(30); + }); +}); + +describe("getOTPSMSRetryAfterSeconds", () => { + const now = 1_000_000; + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("allows sending when no SMS was sent yet", () => { + expect(getOTPSMSRetryAfterSeconds(undefined, now)).toBe(0); + }); + + it("allows sending when the timestamp is not a number", () => { + expect(getOTPSMSRetryAfterSeconds("garbage", now)).toBe(0); + }); + + it("returns the remaining seconds, rounded up, within the cooldown", () => { + expect(getOTPSMSRetryAfterSeconds(`${now}`, now)).toBe(30); + expect(getOTPSMSRetryAfterSeconds(`${now - 10_500}`, now)).toBe(20); + expect(getOTPSMSRetryAfterSeconds(`${now - 29_999}`, now)).toBe(1); + }); + + it("allows sending once the cooldown has passed", () => { + expect(getOTPSMSRetryAfterSeconds(`${now - 30_000}`, now)).toBe(0); + }); + + it("caps a timestamp in the future at the full cooldown", () => { + expect(getOTPSMSRetryAfterSeconds(`${now + 3_600_000}`, now)).toBe(30); + }); + + it("follows the configured cooldown", () => { + vi.stubEnv("OTP_SMS_RESEND_COOLDOWN_SECONDS", "0"); + expect(getOTPSMSRetryAfterSeconds(`${now}`, now)).toBe(0); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/challenges.ts b/auth/ui/v2/apps/login/src/lib/server/challenges.ts new file mode 100644 index 0000000..52d1b67 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/challenges.ts @@ -0,0 +1,93 @@ +import "server-only"; + +import { create } from "@zitadel/client"; +import { + RequestChallenges, + RequestChallenges_OTPEmail_SendCodeSchema, +} from "@zitadel/proto/zitadel/session/v2/challenge_pb"; + +/** + * Strips the `returnCode` delivery type from a client-supplied challenge request. + * + * `returnCode` makes Zitadel return the freshly generated OTP in plaintext in the response + * body instead of sending it to the user's mailbox or phone. It is a legitimate API feature + * for callers that deliver the code themselves, but this app proxies requests on behalf of + * an untrusted browser: anything it forwards is attacker-controllable, and anything it + * returns is attacker-readable. + * + * Without this, a party who knows only a victim's login name could request both OTP-Email + * and OTP-SMS challenges on an identify-only session, read both codes straight out of the + * server-action response and submit them back as two verified factors — GHSA-3gwm-5wx8-4gm6. + * + * OTP challenges are rewritten to their out-of-band equivalent rather than dropped, so the + * legitimate 2FA flow still completes and the code reaches the actual user. WebAuthN + * challenges carry no code and are passed through untouched. + */ +export function sanitizeChallenges(challenges?: RequestChallenges): RequestChallenges | undefined { + if (!challenges) { + return challenges; + } + + const sanitized = { ...challenges }; + + if (sanitized.otpSms) { + sanitized.otpSms = { ...sanitized.otpSms, returnCode: false }; + } + + if (sanitized.otpEmail?.deliveryType?.case === "returnCode") { + sanitized.otpEmail = { + ...sanitized.otpEmail, + // fall back to the default Zitadel verification url + deliveryType: { case: "sendCode", value: create(RequestChallenges_OTPEmail_SendCodeSchema, {}) }, + }; + } + + return sanitized; +} + +const DEFAULT_OTP_SMS_RESEND_COOLDOWN_SECONDS = 30; + +/** + * Minimum number of seconds between two OTP SMS challenges on the same session. + * + * Every OTP SMS challenge makes Zitadel send a text message. Without a cooldown a user (or a script) + * can hit "resend" in a loop and flood the user's phone with codes. + * + * Configurable via `OTP_SMS_RESEND_COOLDOWN_SECONDS`, defaults to 30. `0` disables the cooldown; + * anything that is not a non-negative integer falls back to the default. + */ +export function getOTPSMSResendCooldownSeconds(): number { + const configured = process.env.OTP_SMS_RESEND_COOLDOWN_SECONDS?.trim(); + if (!configured || !/^\d+$/.test(configured)) { + return DEFAULT_OTP_SMS_RESEND_COOLDOWN_SECONDS; + } + return Number(configured); +} + +/** + * Returns how many seconds are left until another OTP SMS may be sent, or 0 if one may be sent now. + * + * @param otpSmsSentTs the `otpSmsSentTs` (ms since epoch) of the session cookie entry + */ +export function getOTPSMSRetryAfterSeconds(otpSmsSentTs: string | undefined, now: number = Date.now()): number { + const sentAt = Number(otpSmsSentTs); + if (!otpSmsSentTs || !Number.isFinite(sentAt)) { + return 0; + } + + const cooldownSeconds = getOTPSMSResendCooldownSeconds(); + const remainingSeconds = Math.ceil((sentAt + cooldownSeconds * 1000 - now) / 1000); + // a timestamp in the future can only come from clock skew between replicas, cap it at the full cooldown + return Math.min(Math.max(remainingSeconds, 0), cooldownSeconds); +} + +/** + * Thrown when a session was updated, so the requested challenges were already sent, but a step after + * the update failed. Callers must not request the same challenges again, the user already has the code. + */ +export class SessionUpdatedError extends Error { + constructor(cause: unknown) { + super("session was updated, but the steps after the update failed", { cause }); + this.name = "SessionUpdatedError"; + } +} diff --git a/auth/ui/v2/apps/login/src/lib/server/cookies.test.ts b/auth/ui/v2/apps/login/src/lib/server/cookies.test.ts new file mode 100644 index 0000000..ee99089 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/cookies.test.ts @@ -0,0 +1,1140 @@ +import { + Cookie, + addSessionToCookie, + getAllSessionCookieIds, + getAllSessions, + getLanguageCookie, + getMostRecentCookieWithLoginname, + getMostRecentSessionCookie, + getSessionCookieById, + getSessionCookieByLoginName, + removeSessionFromCookie, + setLanguageCookie, + updateSessionCookie, +} from "@/lib/server/cookies"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { signSession, verifySession } from "@/lib/server/session-cookie-signature"; +import { timestampDate, timestampFromMs } from "@zitadel/client"; +import { cookies } from "next/headers"; + +// Mock logger - use vi.hoisted to ensure it's defined before vi.mock runs +const mockLogger = vi.hoisted(() => ({ + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), +})); + +// Mock dependencies +vi.mock("next/headers", () => ({ + cookies: vi.fn(), +})); + +vi.mock("@/lib/server/logger", () => ({ + createLogger: () => mockLogger, +})); + +vi.mock("@zitadel/client", () => ({ + timestampDate: vi.fn((ts: any) => new Date(Number(ts.seconds) * 1000)), + timestampFromMs: vi.fn((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any), +})); + +describe("cookies", () => { + let mockCookies: any; + + function stored(...sessions: Cookie[]) { + return { value: JSON.stringify(sessions.map((session) => signSession(session))) }; + } + + function writtenSessions(): Array { + return JSON.parse(mockCookies.set.mock.calls[0][0].value); + } + + beforeEach(() => { + vi.clearAllMocks(); + process.env.ZITADEL_SESSION_COOKIE_SECRET = "test-session-cookie-secret-at-least-32-chars"; + mockCookies = { + get: vi.fn(), + set: vi.fn(), + }; + vi.mocked(cookies).mockResolvedValue(mockCookies); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("setLanguageCookie", () => { + it("should set language cookie with correct parameters", async () => { + await setLanguageCookie("en"); + + expect(mockCookies.set).toHaveBeenCalledWith({ + name: "NEXT_LOCALE", + value: "en", + httpOnly: true, + path: "/", + }); + }); + }); + + describe("getLanguageCookie", () => { + it("should return the language cookie value when set", async () => { + mockCookies.get.mockReturnValue({ value: "de" }); + + const result = await getLanguageCookie(); + + expect(result).toBe("de"); + expect(mockCookies.get).toHaveBeenCalledWith("NEXT_LOCALE"); + }); + + it("should return undefined when no language cookie exists", async () => { + mockCookies.get.mockReturnValue(undefined); + + const result = await getLanguageCookie(); + + expect(result).toBeUndefined(); + }); + + it("should return undefined when cookie has no value", async () => { + mockCookies.get.mockReturnValue({ value: undefined }); + + const result = await getLanguageCookie(); + + expect(result).toBeUndefined(); + }); + }); + + describe("addSessionToCookie", () => { + const mockSession: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + organization: "org-1", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + it("should add new session to empty cookie", async () => { + mockCookies.get.mockReturnValue(undefined); + + await addSessionToCookie({ session: mockSession }); + + const sessions = writtenSessions(); + expect(sessions).toHaveLength(1); + expect(sessions[0]).toMatchObject(mockSession); + expect(verifySession(sessions[0])).toBe(true); + }); + + it("should prepend new session to existing sessions", async () => { + const existingSession: Cookie = { + id: "session-0", + token: "token-0", + loginName: "other@example.com", + creationTs: "1600000000000", + expirationTs: "1700000000000", + changeTs: "1600000000000", + }; + + mockCookies.get.mockReturnValue(stored(existingSession)); + + await addSessionToCookie({ session: mockSession }); + + const sessions = writtenSessions(); + expect(sessions).toHaveLength(2); + expect(sessions[0]).toMatchObject(mockSession); + expect(sessions[1]).toMatchObject(existingSession); + expect(sessions.every(verifySession)).toBe(true); + }); + + it("should update existing session with same loginName", async () => { + const existingSession: Cookie = { + id: "session-old", + token: "token-old", + loginName: "user@example.com", + creationTs: "1600000000000", + expirationTs: "1700000000000", + changeTs: "1600000000000", + }; + + mockCookies.get.mockReturnValue(stored(existingSession)); + + const updatedSession: Cookie = { + ...mockSession, + id: "session-new", + token: "token-new", + }; + + await addSessionToCookie({ session: updatedSession }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + expect(sessions).toHaveLength(1); + expect(sessions[0].id).toBe("session-new"); + expect(sessions[0].token).toBe("token-new"); + }); + + it("should handle cookie overflow by evicting the least recently changed sessions", async () => { + const manySessions: Cookie[] = Array.from({ length: 16 }, (_, i) => ({ + id: `session-${i}`, + token: `token-${i}-very-long-token-to-increase-size-padding-padding-padding`, + loginName: `user${i}@example.com`, + creationTs: `${1600000000000 + i * 1000}`, + expirationTs: `${1900000000000 + i * 1000}`, + changeTs: `${1600000000000 + i * 1000}`, + })); + + mockCookies.get.mockReturnValue(stored(...manySessions)); + + await addSessionToCookie({ session: mockSession }); + + expect(mockLogger.warn).toHaveBeenCalledWith( + "sessions cookie exceeded the size budget, evicted the oldest entries", + expect.objectContaining({ evicted: expect.any(Number) }), + ); + + const sessions = writtenSessions(); + + expect(sessions[0]).toMatchObject(mockSession); + expect(sessions.some((s) => s.id === manySessions[0].id)).toBe(false); + // the most recently changed existing session survives + expect(sessions.some((s) => s.id === manySessions[15].id)).toBe(true); + }); + + it("should cleanup expired sessions when cleanup is true", async () => { + const now = Date.now(); + const expiredSession: Cookie = { + id: "session-expired", + token: "token-expired", + loginName: "expired@example.com", + creationTs: `${now - 10000000}`, + expirationTs: `${now - 1000}`, // Expired + changeTs: `${now - 10000000}`, + }; + + const validSession: Cookie = { + id: "session-valid", + token: "token-valid", + loginName: "valid@example.com", + creationTs: `${now}`, + expirationTs: `${now + 10000000}`, // Not expired + changeTs: `${now}`, + }; + + mockCookies.get.mockReturnValue(stored(expiredSession, validSession)); + + vi.mocked(timestampDate).mockImplementation((ts: any) => new Date(Number(ts.seconds) * 1000)); + vi.mocked(timestampFromMs).mockImplementation((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any); + + await addSessionToCookie({ session: mockSession, cleanup: true }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + // Should not include expired session + const hasExpired = sessions.some((s: Cookie) => s.id === "session-expired"); + expect(hasExpired).toBe(false); + }); + + it("should set sameSite to 'none' when iFrameEnabled is true", async () => { + mockCookies.get.mockReturnValue(undefined); + + await addSessionToCookie({ session: mockSession, iFrameEnabled: true }); + + expect(mockCookies.set).toHaveBeenCalledWith( + expect.objectContaining({ + sameSite: "none", + secure: true, + }), + ); + }); + + it("should set sameSite to 'lax' when iFrameEnabled is false or undefined", async () => { + mockCookies.get.mockReturnValue(undefined); + + await addSessionToCookie({ session: mockSession, iFrameEnabled: false }); + + expect(mockCookies.set).toHaveBeenCalledWith( + expect.objectContaining({ + sameSite: "lax", + }), + ); + + mockCookies.set.mockClear(); + await addSessionToCookie({ session: mockSession }); + + expect(mockCookies.set).toHaveBeenCalledWith( + expect.objectContaining({ + sameSite: "lax", + }), + ); + }); + }); + + describe("updateSessionCookie", () => { + const mockSession: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + it("should update existing session by id", async () => { + mockCookies.get.mockReturnValue({ + ...stored(mockSession), + }); + + const updatedSession: Cookie = { + ...mockSession, + token: "new-token", + changeTs: "1700000001000", + }; + + await updateSessionCookie({ + id: "session-1", + session: updatedSession, + }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + expect(sessions[0].token).toBe("new-token"); + expect(sessions[0].changeTs).toBe("1700000001000"); + }); + + it("should throw error if session id not found", async () => { + mockCookies.get.mockReturnValue({ + ...stored(mockSession), + }); + + await expect( + updateSessionCookie({ + id: "non-existent-id", + session: mockSession, + }), + ).rejects.toThrow("updateSessionCookie: session id not found"); + }); + + it("should cleanup expired sessions when cleanup is true", async () => { + const now = Date.now(); + const expiredSession: Cookie = { + id: "session-expired", + token: "token-expired", + loginName: "expired@example.com", + creationTs: `${now - 10000000}`, + expirationTs: `${now - 1000}`, + changeTs: `${now - 10000000}`, + }; + + mockCookies.get.mockReturnValue({ + ...stored(mockSession, expiredSession), + }); + + vi.mocked(timestampDate).mockImplementation((ts: any) => new Date(Number(ts.seconds) * 1000)); + vi.mocked(timestampFromMs).mockImplementation((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any); + + await updateSessionCookie({ + id: "session-1", + session: { ...mockSession, token: "updated" }, + cleanup: true, + }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + const hasExpired = sessions.some((s: Cookie) => s.id === "session-expired"); + expect(hasExpired).toBe(false); + }); + + it("should respect iFrameEnabled parameter", async () => { + mockCookies.get.mockReturnValue({ + ...stored(mockSession), + }); + + await updateSessionCookie({ + id: "session-1", + session: mockSession, + iFrameEnabled: true, + }); + + expect(mockCookies.set).toHaveBeenCalledWith( + expect.objectContaining({ + sameSite: "none", + }), + ); + }); + }); + + describe("removeSessionFromCookie", () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000001000", + }; + + it("should remove session by id", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + await removeSessionFromCookie({ session: session1 }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + expect(sessions).toHaveLength(1); + expect(sessions[0].id).toBe("session-2"); + }); + + it("should handle removing non-existent session gracefully", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1), + }); + + const nonExistentSession: Cookie = { + ...session2, + id: "non-existent", + }; + + await removeSessionFromCookie({ session: nonExistentSession }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + expect(sessions).toHaveLength(1); + expect(sessions[0].id).toBe("session-1"); + }); + + it("should cleanup expired sessions when cleanup is true", async () => { + const now = Date.now(); + const expiredSession: Cookie = { + id: "session-expired", + token: "token-expired", + loginName: "expired@example.com", + creationTs: `${now - 10000000}`, + expirationTs: `${now - 1000}`, + changeTs: `${now - 10000000}`, + }; + + mockCookies.get.mockReturnValue({ + ...stored(session1, session2, expiredSession), + }); + + vi.mocked(timestampDate).mockImplementation((ts: any) => new Date(Number(ts.seconds) * 1000)); + vi.mocked(timestampFromMs).mockImplementation((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any); + + await removeSessionFromCookie({ session: session1, cleanup: true }); + + const setCall = mockCookies.set.mock.calls[0][0]; + const sessions = JSON.parse(setCall.value); + + expect(sessions).toHaveLength(1); + expect(sessions[0].id).toBe("session-2"); + }); + + it("should respect iFrameEnabled parameter", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + await removeSessionFromCookie({ + session: session1, + iFrameEnabled: true, + }); + + expect(mockCookies.set).toHaveBeenCalledWith( + expect.objectContaining({ + sameSite: "none", + }), + ); + }); + }); + + describe("sessions cookie size budget", () => { + // size of the Set-Cookie `name=value` pair as Next.js sends it (the value is URL-encoded) + function sentCookieSize(value: string) { + return `sessions=${encodeURIComponent(value)}`.length; + } + + function writtenValues(): string[] { + return mockCookies.set.mock.calls.map((call: any[]) => call[0].value); + } + + function lastWrittenSessions(): Array { + const values = writtenValues(); + return JSON.parse(values[values.length - 1]); + } + + // shaped like the entries ZITADEL Cloud writes: numeric ids, encrypted token, email login names, OIDC request + function realisticSession(i: number, overrides: Partial = {}): Cookie { + return { + id: `34567890123456${String(i).padStart(4, "0")}`, + token: `${"x".repeat(100)}${i}`, + loginName: `qa.user${i}@example-company.ch`, + organization: "345678901234567890", + creationTs: `${1761480000000 + i * 1000}`, + expirationTs: `${1900000000000 + i * 1000}`, + changeTs: `${1761480000000 + i * 1000}`, + requestId: "oidc_V2_345678901234567890", + ...overrides, + }; + } + + beforeEach(() => { + vi.mocked(timestampDate).mockImplementation((ts: any) => new Date(Number(ts.seconds) * 1000)); + vi.mocked(timestampFromMs).mockImplementation((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any); + }); + + it("should keep the URL-encoded cookie below the browser limit while many users sign in", async () => { + let current: { value: string } | undefined; + mockCookies.get.mockImplementation(() => current); + mockCookies.set.mockImplementation((cookie: { value: string }) => { + current = { value: cookie.value }; + }); + + for (let i = 0; i < 30; i++) { + const session = realisticSession(i); + await addSessionToCookie({ session }); + + const written = lastWrittenSessions(); + expect(written[0]).toMatchObject(session); + expect(sentCookieSize(current!.value)).toBeLessThanOrEqual(3800); + } + + // the most recent users are the ones that remain + const ids = lastWrittenSessions().map((s) => s.id); + expect(ids).toContain(realisticSession(29).id); + expect(ids).toContain(realisticSession(28).id); + expect(ids).not.toContain(realisticSession(0).id); + }); + + it("should measure the URL-encoded size, not the raw JSON length", async () => { + // 8 entries: the raw JSON stays below 3800 bytes but the encoded cookie is above the 4096 browser limit + const existing = Array.from({ length: 7 }, (_, i) => realisticSession(i)); + const rawLength = stored(...existing, realisticSession(7)).value.length; + expect(rawLength).toBeLessThan(3800); + expect(sentCookieSize(stored(...existing, realisticSession(7)).value)).toBeGreaterThan(4096); + + mockCookies.get.mockReturnValue(stored(...existing)); + + await addSessionToCookie({ session: realisticSession(7) }); + + expect(sentCookieSize(writtenValues()[0])).toBeLessThanOrEqual(3800); + }); + + it("should evict by least recent changeTs, not by position in the cookie", async () => { + // position 0 holds the most recently changed entry + const existing = Array.from({ length: 8 }, (_, i) => realisticSession(i, { changeTs: `${1761480000000 - i * 1000}` })); + mockCookies.get.mockReturnValue(stored(...existing)); + + await addSessionToCookie({ session: realisticSession(99) }); + + const ids = lastWrittenSessions().map((s) => s.id); + expect(ids[0]).toBe(realisticSession(99).id); + expect(ids).toContain(existing[0].id); + expect(ids).not.toContain(existing[7].id); + }); + + it("should evict expired entries before older valid ones", async () => { + const now = Date.now(); + const expired = realisticSession(1, { expirationTs: `${now - 1000}`, changeTs: `${now - 1000}` }); + const existing = [ + expired, + ...Array.from({ length: 6 }, (_, i) => realisticSession(i + 2, { changeTs: `${now - 1000000 + i}` })), + ]; + mockCookies.get.mockReturnValue(stored(...existing)); + + await addSessionToCookie({ session: realisticSession(99, { changeTs: `${now}` }) }); + + const ids = lastWrittenSessions().map((s) => s.id); + expect(ids).not.toContain(expired.id); + // removing the expired entry is enough, the oldest valid one stays + expect(ids).toContain(existing[1].id); + }); + + it("should keep expired entries while the cookie fits", async () => { + const now = Date.now(); + const expired = realisticSession(1, { expirationTs: `${now - 1000}` }); + mockCookies.get.mockReturnValue(stored(expired)); + + await addSessionToCookie({ session: realisticSession(2) }); + + expect(lastWrittenSessions().map((s) => s.id)).toContain(expired.id); + expect(mockLogger.warn).not.toHaveBeenCalled(); + }); + + it("should never evict the session being updated", async () => { + const existing = Array.from({ length: 9 }, (_, i) => realisticSession(i)); + mockCookies.get.mockReturnValue(stored(...existing)); + + // the updated entry has the oldest changeTs + const updated = { ...existing[0], token: `${"y".repeat(100)}0` }; + await updateSessionCookie({ id: updated.id, session: updated }); + + const written = lastWrittenSessions(); + expect(written.find((s) => s.id === updated.id)).toMatchObject(updated); + expect(written.length).toBeLessThan(existing.length); + expect(sentCookieSize(writtenValues()[0])).toBeLessThanOrEqual(3800); + }); + + it("should enforce the budget when removing a session", async () => { + // a cookie written by an older version can already be over the budget + const existing = Array.from({ length: 12 }, (_, i) => realisticSession(i)); + mockCookies.get.mockReturnValue(stored(...existing)); + + await removeSessionFromCookie({ session: existing[11] }); + + const ids = lastWrittenSessions().map((s) => s.id); + expect(ids).not.toContain(existing[11].id); + expect(sentCookieSize(writtenValues()[0])).toBeLessThanOrEqual(3800); + }); + }); + + describe("getMostRecentSessionCookie", () => { + it("should return session with most recent changeTs", async () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000005000", // Most recent + }; + + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getMostRecentSessionCookie(); + + expect(result).toBeDefined(); + expect(result?.id).toBe("session-2"); + }); + + it("should return undefined when no session cookie exists", async () => { + mockCookies.get.mockReturnValue(undefined); + + await expect(getMostRecentSessionCookie()).resolves.toBeUndefined(); + }); + + it("should handle single session", async () => { + const session: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + mockCookies.get.mockReturnValue({ + ...stored(session), + }); + + const result = await getMostRecentSessionCookie(); + + expect(result).toBeDefined(); + expect(result?.id).toBe("session-1"); + }); + }); + + describe("getSessionCookieById", () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + organization: "org-1", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + organization: "org-2", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000001000", + }; + + it("should find session by id", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getSessionCookieById({ sessionId: "session-1" }); + + expect(result).toBeDefined(); + expect(result?.id).toBe("session-1"); + expect(result?.loginName).toBe("user1@example.com"); + }); + + it("should filter by organization when provided", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getSessionCookieById({ + sessionId: "session-2", + organization: "org-2", + }); + + expect(result).toBeDefined(); + expect(result?.id).toBe("session-2"); + expect(result?.organization).toBe("org-2"); + }); + + it("should return undefined if session not found", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1), + }); + + await expect(getSessionCookieById({ sessionId: "non-existent" })).resolves.toBeUndefined(); + }); + + it("should return undefined if organization doesn't match", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1), + }); + + await expect( + getSessionCookieById({ + sessionId: "session-1", + organization: "wrong-org", + }), + ).resolves.toBeUndefined(); + }); + + it("should return undefined when no session cookie exists", async () => { + mockCookies.get.mockReturnValue(undefined); + + await expect(getSessionCookieById({ sessionId: "session-1" })).resolves.toBeUndefined(); + }); + }); + + describe("getSessionCookieByLoginName", () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + organization: "org-1", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + organization: "org-2", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000001000", + }; + + it("should find session by loginName", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getSessionCookieByLoginName({ + loginName: "user1@example.com", + }); + + expect(result).toBeDefined(); + expect(result?.id).toBe("session-1"); + expect(result?.loginName).toBe("user1@example.com"); + }); + + it("should filter by organization when provided", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getSessionCookieByLoginName({ + loginName: "user2@example.com", + organization: "org-2", + }); + + expect(result).toBeDefined(); + expect(result?.id).toBe("session-2"); + expect(result?.organization).toBe("org-2"); + }); + + it("should return undefined if session not found", async () => { + mockCookies.get.mockReturnValue({ + ...stored(session1), + }); + + await expect(getSessionCookieByLoginName({ loginName: "nonexistent@example.com" })).resolves.toBeUndefined(); + }); + + it("should return undefined when no session cookie exists", async () => { + mockCookies.get.mockReturnValue(undefined); + + await expect(getSessionCookieByLoginName({ loginName: "user@example.com" })).resolves.toBeUndefined(); + }); + }); + + describe("getAllSessionCookieIds", () => { + it("should return all session IDs", async () => { + const sessions: Cookie[] = [ + { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }, + { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000001000", + }, + ]; + + mockCookies.get.mockReturnValue({ + ...stored(...sessions), + }); + + const result = await getAllSessionCookieIds(); + + expect(result).toEqual(["session-1", "session-2"]); + }); + + it("should filter expired sessions when cleanup is true", async () => { + const now = Date.now(); + const sessions: Cookie[] = [ + { + id: "session-valid", + token: "token-valid", + loginName: "valid@example.com", + creationTs: `${now}`, + expirationTs: `${now + 10000000}`, + changeTs: `${now}`, + }, + { + id: "session-expired", + token: "token-expired", + loginName: "expired@example.com", + creationTs: `${now - 10000000}`, + expirationTs: `${now - 1000}`, + changeTs: `${now - 10000000}`, + }, + ]; + + mockCookies.get.mockReturnValue({ + ...stored(...sessions), + }); + + vi.mocked(timestampDate).mockImplementation((ts: any) => new Date(Number(ts.seconds) * 1000)); + vi.mocked(timestampFromMs).mockImplementation((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any); + + const result = await getAllSessionCookieIds(true); + + expect(result).toEqual(["session-valid"]); + }); + + it("should return empty array when no sessions exist", async () => { + mockCookies.get.mockReturnValue(undefined); + + const result = await getAllSessionCookieIds(); + + expect(result).toEqual([]); + }); + }); + + describe("getAllSessions", () => { + it("should return all sessions", async () => { + const sessions: Cookie[] = [ + { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }, + { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000001000", + }, + ]; + + mockCookies.get.mockReturnValue({ + ...stored(...sessions), + }); + + const result = await getAllSessions(); + + expect(result).toEqual(sessions); + }); + + it("should filter expired sessions when cleanup is true", async () => { + const now = Date.now(); + const validSession: Cookie = { + id: "session-valid", + token: "token-valid", + loginName: "valid@example.com", + creationTs: `${now}`, + expirationTs: `${now + 10000000}`, + changeTs: `${now}`, + }; + + const expiredSession: Cookie = { + id: "session-expired", + token: "token-expired", + loginName: "expired@example.com", + creationTs: `${now - 10000000}`, + expirationTs: `${now - 1000}`, + changeTs: `${now - 10000000}`, + }; + + mockCookies.get.mockReturnValue({ + ...stored(validSession, expiredSession), + }); + + vi.mocked(timestampDate).mockImplementation((ts: any) => new Date(Number(ts.seconds) * 1000)); + vi.mocked(timestampFromMs).mockImplementation((ms: number) => ({ seconds: BigInt(Math.floor(ms / 1000)) }) as any); + + const result = await getAllSessions(true); + + expect(result).toHaveLength(1); + expect(result[0].id).toBe("session-valid"); + }); + + it("should return empty array when no sessions exist", async () => { + mockCookies.get.mockReturnValue(undefined); + + const result = await getAllSessions(); + + expect(result).toEqual([]); + expect(mockLogger.info).toHaveBeenCalledWith("getAllSessions: No session cookie found, returning empty array"); + }); + }); + + describe("getMostRecentCookieWithLoginname", () => { + it("should return most recent session for loginName", async () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000005000", // Most recent + }; + + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getMostRecentCookieWithLoginname({ + loginName: "user@example.com", + }); + + expect(result.id).toBe("session-2"); + }); + + it("should return undefined when no matching session found", async () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000005000", + }; + + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + await expect( + getMostRecentCookieWithLoginname({ + loginName: "other@example.com", + }), + ).resolves.toBeUndefined(); + }); + + it("should filter by organization when provided", async () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user@example.com", + organization: "org-1", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000005000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user@example.com", + organization: "org-2", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000010000", // More recent but different org + }; + + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getMostRecentCookieWithLoginname({ + loginName: "user@example.com", + organization: "org-1", + }); + + expect(result.id).toBe("session-1"); + expect(result.organization).toBe("org-1"); + }); + + it("should return most recent session when no loginName provided", async () => { + const session1: Cookie = { + id: "session-1", + token: "token-1", + loginName: "user1@example.com", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + const session2: Cookie = { + id: "session-2", + token: "token-2", + loginName: "user2@example.com", + creationTs: "1700000001000", + expirationTs: "1800000001000", + changeTs: "1700000005000", + }; + + mockCookies.get.mockReturnValue({ + ...stored(session1, session2), + }); + + const result = await getMostRecentCookieWithLoginname({}); + + expect(result.id).toBe("session-2"); + }); + + it("should return undefined when no session cookie exists", async () => { + mockCookies.get.mockReturnValue(undefined); + + await expect( + getMostRecentCookieWithLoginname({ + loginName: "user@example.com", + }), + ).resolves.toBeUndefined(); + }); + }); + + describe("session cookie HMAC", () => { + const victimSession: Cookie = { + id: "victim-session-id", + token: "victim-token", + loginName: "admin@example.com", + organization: "org-1", + creationTs: "1700000000000", + expirationTs: "1800000000000", + changeTs: "1700000000000", + }; + + it("ignores an unsigned guessed session id", async () => { + mockCookies.get.mockReturnValue({ + value: JSON.stringify([{ ...victimSession, token: "" }]), + }); + + await expect(getSessionCookieById({ sessionId: "victim-session-id" })).resolves.toBeUndefined(); + await expect(getAllSessionCookieIds()).resolves.toEqual([]); + }); + + it("ignores a session whose id was swapped after signing", async () => { + const signed = signSession({ ...victimSession, id: "attacker-session", token: "attacker-token" }); + mockCookies.get.mockReturnValue({ + value: JSON.stringify([{ ...signed, id: "victim-session-id", token: "" }]), + }); + + await expect(getSessionCookieById({ sessionId: "victim-session-id" })).resolves.toBeUndefined(); + }); + + it("does not update a session that is only present as a forged cookie entry", async () => { + mockCookies.get.mockReturnValue({ + value: JSON.stringify([{ ...victimSession, token: "" }]), + }); + + await expect( + updateSessionCookie({ + id: "victim-session-id", + session: { ...victimSession, token: "rotated-token" }, + }), + ).rejects.toThrow("updateSessionCookie: session id not found"); + expect(mockCookies.set).not.toHaveBeenCalled(); + }); + + it("still writes a newly created session when no cookie exists", async () => { + mockCookies.get.mockReturnValue(undefined); + + await addSessionToCookie({ session: victimSession }); + + const sessions = writtenSessions(); + expect(sessions).toHaveLength(1); + expect(sessions[0]).toMatchObject(victimSession); + expect(verifySession(sessions[0])).toBe(true); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/cookies.ts b/auth/ui/v2/apps/login/src/lib/server/cookies.ts new file mode 100644 index 0000000..dd56e08 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/cookies.ts @@ -0,0 +1,357 @@ +// Not a server action module: these helpers read and sign the httpOnly `sessions` cookie, so they +// must only be called by server code. Browser-facing actions live in `lib/server/*`. +import "server-only"; + +import { LANGUAGE_COOKIE_NAME } from "@/lib/i18n"; +import { createLogger } from "@/lib/server/logger"; +import { parseAndVerifySessions, signSession } from "@/lib/server/session-cookie-signature"; +import { timestampDate, timestampFromMs } from "@zitadel/client"; +import { cookies } from "next/headers"; + +const logger = createLogger("cookies"); + +const SESSIONS_COOKIE_NAME = "sessions"; + +// Browsers cap a single cookie at ~4096 bytes and silently drop a Set-Cookie above it, which leaves +// the previous cookie (with an outdated session token) in place. The budget applies to +// `name=value` as it is sent, i.e. after Next.js URL-encodes the value, and keeps a margin for the +// attributes (path, sameSite, secure, httpOnly) that some browsers count towards the limit. +const MAX_COOKIE_SIZE = 3800; + +export type Cookie = { + id: string; + token: string; + loginName: string; + organization?: string; + creationTs: string; + expirationTs: string; + changeTs: string; + requestId?: string; // if its linked to an OIDC flow + otpSmsSentTs?: string; // when the last OTP SMS was requested for this session, enforces the resend cooldown +}; + +type SessionCookie = Cookie & T; + +function isExpired(session: Cookie, now: Date): boolean { + return session.expirationTs ? timestampDate(timestampFromMs(Number(session.expirationTs))) <= now : false; +} + +function encodedCookieSize(value: string): number { + // encodeURIComponent only emits ASCII, so the string length equals the byte length + return `${SESSIONS_COOKIE_NAME}=${encodeURIComponent(value)}`.length; +} + +/** + * Signs the sessions and evicts entries until the cookie fits into MAX_COOKIE_SIZE. + * Entries the cookie considers expired go first, then the least recently changed ones. + * The entry with `keepId` (the session of the current flow) is never evicted. + */ +function serializeWithinBudget(sessions: SessionCookie[], keepId?: string): string { + const signed = sessions.map((session) => signSession(session)); + let kept = signed; + let value = JSON.stringify(kept); + + if (encodedCookieSize(value) <= MAX_COOKIE_SIZE) { + return value; + } + + const sizeBefore = encodedCookieSize(value); + const now = new Date(); + const evictionOrder = signed + .filter((session) => session.id !== keepId) + .sort((a, b) => { + const expiredA = isExpired(a, now); + if (expiredA !== isExpired(b, now)) { + return expiredA ? -1 : 1; + } + return Number(a.changeTs || 0) - Number(b.changeTs || 0); + }); + + for (const evicted of evictionOrder) { + kept = kept.filter((session) => session !== evicted); + value = JSON.stringify(kept); + if (encodedCookieSize(value) <= MAX_COOKIE_SIZE) { + break; + } + } + + const sizeAfter = encodedCookieSize(value); + const meta = { sizeBefore, sizeAfter, evicted: sessions.length - kept.length, remaining: kept.length }; + if (sizeAfter > MAX_COOKIE_SIZE) { + logger.error("sessions cookie exceeds the size budget even after evicting all other entries", meta); + } else { + logger.warn("sessions cookie exceeded the size budget, evicted the oldest entries", meta); + } + + return value; +} + +async function setSessionHttpOnlyCookie(sessions: SessionCookie[], iFrameEnabled: boolean = false, keepId?: string) { + const cookiesList = await cookies(); + + // "none" is required for iframe embedding (with secure flag) + let resolvedSameSite: "lax" | "strict" | "none"; + + if (iFrameEnabled) { + // When embedded in iframe, must use "none" with secure flag + resolvedSameSite = "none"; + } else { + // This allows cookies during top-level navigation while blocking cross-origin requests + resolvedSameSite = "lax"; + } + + return cookiesList.set({ + name: SESSIONS_COOKIE_NAME, + value: serializeWithinBudget(sessions, keepId), + httpOnly: true, + path: "/", + sameSite: resolvedSameSite, + // "none" is only accepted by browsers together with "secure", otherwise the cookie is silently dropped + secure: process.env.NODE_ENV === "production" || resolvedSameSite === "none", + }); +} + +function readSessionCookies(value: string | undefined): SessionCookie[] { + const sessions = parseAndVerifySessions>(value); + + if (value && sessions.length < countCookieEntries(value)) { + logger.warn( + `readSessionCookies: ignoring ${countCookieEntries(value) - sessions.length} session cookie entries with a missing or invalid signature (unsigned legacy cookie or signing secret changed)`, + ); + } + + return sessions; +} + +function countCookieEntries(value: string): number { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed.length : 0; + } catch { + return 0; + } +} + +export async function setLanguageCookie(language: string) { + const cookiesList = await cookies(); + + await cookiesList.set({ + name: LANGUAGE_COOKIE_NAME, + value: language, + httpOnly: true, + path: "/", + }); +} + +export async function getLanguageCookie(): Promise { + const cookiesList = await cookies(); + const languageCookie = cookiesList.get(LANGUAGE_COOKIE_NAME); + return languageCookie?.value; +} + +export async function addSessionToCookie({ + session, + cleanup, + iFrameEnabled, +}: { + session: SessionCookie; + cleanup?: boolean; + iFrameEnabled?: boolean; +}): Promise { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + let currentSessions: SessionCookie[] = readSessionCookies(stringifiedCookie?.value); + + const index = currentSessions.findIndex((s) => s.loginName === session.loginName); + + if (index > -1) { + currentSessions[index] = session; + } else { + // the size budget is enforced when the cookie is written + currentSessions = [session].concat(currentSessions); + } + + if (cleanup) { + const now = new Date(); + const filteredSessions = currentSessions.filter((s) => !isExpired(s, now)); + return setSessionHttpOnlyCookie(filteredSessions, iFrameEnabled, session.id); + } else { + return setSessionHttpOnlyCookie(currentSessions, iFrameEnabled, session.id); + } +} + +export async function updateSessionCookie({ + id, + session, + cleanup, + iFrameEnabled, +}: { + id: string; + session: SessionCookie; + cleanup?: boolean; + iFrameEnabled?: boolean; +}): Promise { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions: SessionCookie[] = stringifiedCookie?.value ? readSessionCookies(stringifiedCookie.value) : [session]; + + const foundIndex = sessions.findIndex((session) => session.id === id); + + if (foundIndex > -1) { + sessions[foundIndex] = session; + if (cleanup) { + const now = new Date(); + const filteredSessions = sessions.filter((s) => !isExpired(s, now)); + return setSessionHttpOnlyCookie(filteredSessions, iFrameEnabled, session.id); + } else { + return setSessionHttpOnlyCookie(sessions, iFrameEnabled, session.id); + } + } else { + throw "updateSessionCookie: session id not found"; + } +} + +export async function removeSessionFromCookie({ + session, + cleanup, + iFrameEnabled, +}: { + session: SessionCookie; + cleanup?: boolean; + iFrameEnabled?: boolean; +}) { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions: SessionCookie[] = stringifiedCookie?.value ? readSessionCookies(stringifiedCookie.value) : [session]; + + const reducedSessions = sessions.filter((s) => s.id !== session.id); + if (cleanup) { + const now = new Date(); + const filteredSessions = reducedSessions.filter((s) => !isExpired(s, now)); + return setSessionHttpOnlyCookie(filteredSessions, iFrameEnabled); + } else { + return setSessionHttpOnlyCookie(reducedSessions, iFrameEnabled); + } +} + +export async function getMostRecentSessionCookie(): Promise { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions = readSessionCookies(stringifiedCookie?.value); + if (!sessions.length) { + return undefined; + } + + return sessions.reduce((prev, current) => { + return prev.changeTs > current.changeTs ? prev : current; + }); +} + +export async function getSessionCookieById({ + sessionId, + organization, +}: { + sessionId: string; + organization?: string; +}): Promise | undefined> { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions = readSessionCookies(stringifiedCookie?.value); + return sessions.find((s) => (organization ? s.organization === organization && s.id === sessionId : s.id === sessionId)); +} + +export async function getSessionCookieByLoginName({ + loginName, + organization, +}: { + loginName?: string; + organization?: string; +}): Promise | undefined> { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions = readSessionCookies(stringifiedCookie?.value); + return sessions.find((s) => + organization ? s.organization === organization && s.loginName === loginName : s.loginName === loginName, + ); +} + +/** + * + * @param cleanup when true, excludes expired sessions from the result, default false + * @returns Session Cookies + */ +export async function getAllSessionCookieIds(cleanup: boolean = false): Promise { + const sessions = await getAllSessions(cleanup); + return sessions.map(({ id }) => id); +} + +/** + * + * @param cleanup when true, excludes expired sessions from the result, default false + * @returns Session Cookies + */ +export async function getAllSessions(cleanup: boolean = false): Promise[]> { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions = readSessionCookies(stringifiedCookie?.value); + + if (!sessions.length) { + logger.info("getAllSessions: No session cookie found, returning empty array"); + return []; + } + + if (cleanup) { + const now = new Date(); + return sessions.filter((session) => !isExpired(session, now)); + } + + return sessions; +} + +/** + * Returns most recent session filtered by optinal loginName + * @param loginName optional loginName to filter cookies, if non provided, returns most recent session + * @param organization optional organization to filter cookies + * @returns most recent session + */ +export async function getMostRecentCookieWithLoginname({ + loginName, + organization, +}: { + loginName?: string; + organization?: string; +}): Promise { + const cookiesList = await cookies(); + const stringifiedCookie = cookiesList.get("sessions"); + + const sessions = readSessionCookies(stringifiedCookie?.value); + + if (!sessions.length) { + return undefined; + } + + let filtered = sessions; + + if (loginName) { + filtered = filtered.filter((cookie) => cookie.loginName === loginName); + } + + if (organization) { + filtered = filtered.filter((cookie) => cookie.organization === organization); + } + + if (!filtered || !filtered.length) { + return undefined; + } + + return filtered.reduce((prev, current) => { + return prev.changeTs > current.changeTs ? prev : current; + }); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/csp.test.ts b/auth/ui/v2/apps/login/src/lib/server/csp.test.ts new file mode 100644 index 0000000..c0c9b09 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/csp.test.ts @@ -0,0 +1,64 @@ +import { buildCSP } from "@/lib/server/csp"; +import { describe, expect, test } from "vitest"; + +describe("buildCSP", () => { + test("returns all base directives with safe defaults", () => { + const csp = buildCSP(); + + expect(csp).toContain("default-src 'self'"); + expect(csp).toContain("script-src 'self' 'unsafe-inline' 'unsafe-eval'"); + expect(csp).toContain("connect-src 'self'"); + expect(csp).toContain("style-src 'self' 'unsafe-inline'"); + expect(csp).toContain("font-src 'self'"); + expect(csp).toContain("img-src 'self'"); + expect(csp).toContain("object-src 'none'"); + expect(csp).toContain("frame-ancestors 'none'"); + }); + + test("adds serviceUrl to img-src and font-src", () => { + const csp = buildCSP({ serviceUrl: "https://my-instance.zitadel.cloud" }); + + expect(csp).toContain("img-src 'self' https://my-instance.zitadel.cloud"); + expect(csp).toContain("font-src 'self' https://my-instance.zitadel.cloud"); + }); + + test("keeps frame-ancestors as 'none' when iframeOrigins is empty", () => { + const csp = buildCSP({ iframeOrigins: [] }); + + expect(csp).toContain("frame-ancestors 'none'"); + }); + + test("overrides frame-ancestors when iframeOrigins are provided", () => { + const csp = buildCSP({ + iframeOrigins: ["https://app.example.com", "https://other.example.com"], + }); + + expect(csp).toContain("frame-ancestors https://app.example.com https://other.example.com"); + expect(csp).not.toContain("frame-ancestors 'none'"); + }); + + test("combines serviceUrl and iframeOrigins", () => { + const csp = buildCSP({ + serviceUrl: "https://zitadel.mycompany.com", + iframeOrigins: ["https://portal.mycompany.com"], + }); + + expect(csp).toContain("img-src 'self' https://zitadel.mycompany.com"); + expect(csp).toContain("font-src 'self' https://zitadel.mycompany.com"); + expect(csp).toContain("frame-ancestors https://portal.mycompany.com"); + expect(csp).not.toContain("frame-ancestors 'none'"); + }); + + test("base directives are preserved when options are set", () => { + const csp = buildCSP({ + serviceUrl: "https://example.com", + iframeOrigins: ["https://embed.example.com"], + }); + + expect(csp).toContain("default-src 'self'"); + expect(csp).toContain("script-src 'self' 'unsafe-inline' 'unsafe-eval'"); + expect(csp).toContain("connect-src 'self'"); + expect(csp).toContain("style-src 'self' 'unsafe-inline'"); + expect(csp).toContain("object-src 'none'"); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/csp.ts b/auth/ui/v2/apps/login/src/lib/server/csp.ts new file mode 100644 index 0000000..a5ff91e --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/csp.ts @@ -0,0 +1,38 @@ +import "server-only"; + +const BASE_DIRECTIVES: Record = { + "default-src": ["'self'"], + "script-src": ["'self'", "'unsafe-inline'", "'unsafe-eval'"], + "connect-src": ["'self'"], + "style-src": ["'self'", "'unsafe-inline'"], + "font-src": ["'self'"], + "img-src": ["'self'"], + "frame-ancestors": ["'none'"], + "object-src": ["'none'"], +}; + +export interface CSPOptions { + serviceUrl?: string; + iframeOrigins?: string[] | null; +} + +export function buildCSP(options: CSPOptions = {}): string { + const directives: Record = { ...BASE_DIRECTIVES }; + + if (options.serviceUrl) { + directives["img-src"] = [...directives["img-src"], options.serviceUrl]; + directives["font-src"] = [...directives["font-src"], options.serviceUrl]; + } + + if (options.iframeOrigins && options.iframeOrigins.length > 0) { + directives["frame-ancestors"] = [...options.iframeOrigins]; + } + + return serializeCSP(directives); +} + +function serializeCSP(directives: Record): string { + return Object.entries(directives) + .map(([key, values]) => [key, ...values].join(" ")) + .join("; "); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/custom-headers.ts b/auth/ui/v2/apps/login/src/lib/server/custom-headers.ts new file mode 100644 index 0000000..907737d --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/custom-headers.ts @@ -0,0 +1,37 @@ +import "server-only"; + +import { createLogger } from "@/lib/server/logger"; + +const logger = createLogger("custom-headers"); + +/** + * Parses the CUSTOM_REQUEST_HEADERS environment variable and applies the + * headers to a mutable target via the provided `set` and `remove` callbacks. + * + * Format: comma-separated "key:value" pairs. + * - Non-empty values call `set(key, value)`. + * - Empty values (e.g., "X-Remove-Me:") call `remove(key)` to delete the header. + * - Malformed entries (no colon) are logged and skipped. + */ +export function applyCustomHeaders(actions: { + set: (key: string, value: string) => void; + remove: (key: string) => void; +}): void { + const raw = process.env.CUSTOM_REQUEST_HEADERS; + if (!raw) return; + + raw.split(",").forEach((header) => { + const kv = header.indexOf(":"); + if (kv > 0) { + const key = header.slice(0, kv).trim(); + const value = header.slice(kv + 1).trim(); + if (value) { + actions.set(key, value); + } else { + actions.remove(key); + } + } else { + logger.warn("Skipping malformed CUSTOM_REQUEST_HEADERS entry", { header }); + } + }); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/demos.ts b/auth/ui/v2/apps/login/src/lib/server/demos.ts new file mode 100644 index 0000000..cfeffd5 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/demos.ts @@ -0,0 +1,40 @@ +import "server-only"; + +export type Item = { + name: string; + slug: string; + description?: string; +}; + +export const demos: { name: string; items: Item[] }[] = [ + { + name: "Login", + items: [ + { + name: "Loginname", + slug: "loginname", + description: "Start the loginflow with loginname", + }, + { + name: "Accounts", + slug: "accounts", + description: "List active and inactive sessions", + }, + ], + }, + { + name: "Register", + items: [ + { + name: "Register", + slug: "register", + description: "Add a user with password or passkey", + }, + { + name: "IDP Register", + slug: "idp", + description: "Add a user from an external identity provider", + }, + ], + }, +]; diff --git a/auth/ui/v2/apps/login/src/lib/server/deployment.test.ts b/auth/ui/v2/apps/login/src/lib/server/deployment.test.ts new file mode 100644 index 0000000..a8f38db --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/deployment.test.ts @@ -0,0 +1,97 @@ +import { hasLoginClientKey, hasServiceUserToken, hasSystemUserCredentials } from "@/lib/server/deployment"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +describe("Deployment utilities", () => { + const originalEnv = process.env; + + beforeEach(() => { + // Reset environment before each test + process.env = { ...originalEnv }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + describe("hasSystemUserCredentials", () => { + test("should return true when all system user credentials are present", () => { + process.env.AUDIENCE = "https://api.zitadel.cloud"; + process.env.SYSTEM_USER_ID = "12345"; + process.env.SYSTEM_USER_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n..."; + + expect(hasSystemUserCredentials()).toBe(true); + }); + + test("should return false when AUDIENCE is missing", () => { + process.env.AUDIENCE = undefined as any; + process.env.SYSTEM_USER_ID = "12345"; + process.env.SYSTEM_USER_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n..."; + + expect(hasSystemUserCredentials()).toBe(false); + }); + + test("should return false when SYSTEM_USER_ID is missing", () => { + process.env.AUDIENCE = "https://api.zitadel.cloud"; + process.env.SYSTEM_USER_ID = undefined as any; + process.env.SYSTEM_USER_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n..."; + + expect(hasSystemUserCredentials()).toBe(false); + }); + + test("should return false when SYSTEM_USER_PRIVATE_KEY is missing", () => { + process.env.AUDIENCE = "https://api.zitadel.cloud"; + process.env.SYSTEM_USER_ID = "12345"; + process.env.SYSTEM_USER_PRIVATE_KEY = undefined as any; + + expect(hasSystemUserCredentials()).toBe(false); + }); + + test("should return false when all credentials are missing", () => { + process.env.AUDIENCE = undefined as any; + process.env.SYSTEM_USER_ID = undefined as any; + process.env.SYSTEM_USER_PRIVATE_KEY = undefined as any; + + expect(hasSystemUserCredentials()).toBe(false); + }); + }); + + describe("hasLoginClientKey", () => { + test("should return true when ZITADEL_LOGINCLIENT_KEYFILE is set", () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = "/path/to/key.pem"; + + expect(hasLoginClientKey()).toBe(true); + }); + + test("should return false when ZITADEL_LOGINCLIENT_KEYFILE is missing", () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = undefined as any; + + expect(hasLoginClientKey()).toBe(false); + }); + + test("should return false when ZITADEL_LOGINCLIENT_KEYFILE is empty string", () => { + process.env.ZITADEL_LOGINCLIENT_KEYFILE = ""; + + expect(hasLoginClientKey()).toBe(false); + }); + }); + + describe("hasServiceUserToken", () => { + test("should return true when ZITADEL_SERVICE_USER_TOKEN is present", () => { + process.env.ZITADEL_SERVICE_USER_TOKEN = "token123"; + + expect(hasServiceUserToken()).toBe(true); + }); + + test("should return false when ZITADEL_SERVICE_USER_TOKEN is not set", () => { + process.env.ZITADEL_SERVICE_USER_TOKEN = undefined as any; + + expect(hasServiceUserToken()).toBe(false); + }); + + test("should return false when ZITADEL_SERVICE_USER_TOKEN is empty string", () => { + process.env.ZITADEL_SERVICE_USER_TOKEN = ""; + + expect(hasServiceUserToken()).toBe(false); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/deployment.ts b/auth/ui/v2/apps/login/src/lib/server/deployment.ts new file mode 100644 index 0000000..731f036 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/deployment.ts @@ -0,0 +1,40 @@ +import "server-only"; + +/** + * Checks if system user credentials are available for JWT authentication. + * + * System user authentication requires: + * - AUDIENCE: The API audience for JWT authentication + * - SYSTEM_USER_ID: The system user's ID + * - SYSTEM_USER_PRIVATE_KEY: The private key for JWT signing + * - SYSTEM_USER_PRIVATE_KEY_FILE: The private key file path for JWT signing + * + * Both multi-tenant and self-hosted deployments can use system user authentication. + * + * @returns true if system user credentials are present, false otherwise + */ +export function hasSystemUserCredentials(): boolean { + return ( + !!process.env.AUDIENCE && + !!process.env.SYSTEM_USER_ID && + (!!process.env.SYSTEM_USER_PRIVATE_KEY || !!process.env.SYSTEM_USER_PRIVATE_KEY_FILE) + ); +} + +/** + * Checks if login client key file is available for JWT authentication. + * + * @returns true if ZITADEL_LOGINCLIENT_KEYFILE is present, false otherwise + */ +export function hasLoginClientKey(): boolean { + return !!process.env.ZITADEL_LOGINCLIENT_KEYFILE; +} + +/** + * Checks if service account token is available for authentication. + * + * @returns true if ZITADEL_SERVICE_USER_TOKEN is present, false otherwise + */ +export function hasServiceUserToken(): boolean { + return !!process.env.ZITADEL_SERVICE_USER_TOKEN; +} diff --git a/auth/ui/v2/apps/login/src/lib/server/device-code-check.test.ts b/auth/ui/v2/apps/login/src/lib/server/device-code-check.test.ts new file mode 100644 index 0000000..6255fb5 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/device-code-check.test.ts @@ -0,0 +1,113 @@ +import { + checkDeviceCodeCheckCookie, + createDeviceCodeCheck, + DEVICE_CODE_CHECK_MAX_AGE_SECONDS, + isDeviceCodeCheckValid, + setDeviceCodeCheckCookie, +} from "@/lib/server/device-code-check"; +import { createVerificationCheck } from "@/lib/server/verification-check"; +import { getSecuritySettings } from "@/lib/server/zitadel"; +import { createHash } from "crypto"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { jar, setCookie } = vi.hoisted(() => { + const jar = new Map(); + return { jar, setCookie: vi.fn(({ name, value }: { name: string; value: string }) => jar.set(name, value)) }; +}); + +vi.mock("next/headers", () => ({ + cookies: vi.fn(async () => ({ + get: (name: string) => (jar.has(name) ? { name, value: jar.get(name) } : undefined), + set: setCookie, + delete: (name: string) => jar.delete(name), + })), + headers: vi.fn(async () => new Headers()), +})); +vi.mock("./service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://api.example.com" } })), +})); +vi.mock("./zitadel", () => ({ + getSecuritySettings: vi.fn(), +})); + +describe("deviceCodeCheck cookie", () => { + beforeEach(() => { + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + jar.clear(); + jar.set("bindingId", "binding-id-1"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test("passes for the user code and browser that set it", async () => { + await setDeviceCodeCheckCookie("ABCD-1234"); + + expect(await checkDeviceCodeCheckCookie("ABCD-1234")).toBe(true); + expect(await checkDeviceCodeCheckCookie("WXYZ-9876")).toBe(false); + }); + + test("sets the cookie with SameSite and Secure so it also works in an iframe", async () => { + vi.mocked(getSecuritySettings).mockResolvedValueOnce({ embeddedIframe: { enabled: true } } as any); + + await setDeviceCodeCheckCookie("ABCD-1234"); + + expect(setCookie).toHaveBeenCalledWith( + expect.objectContaining({ + name: "deviceCodeCheck", + httpOnly: true, + maxAge: DEVICE_CODE_CHECK_MAX_AGE_SECONDS, + sameSite: "none", + secure: true, + }), + ); + }); + + test("fails when the binding id changed", async () => { + await setDeviceCodeCheckCookie("ABCD-1234"); + jar.set("bindingId", "binding-id-2"); + + expect(await checkDeviceCodeCheckCookie("ABCD-1234")).toBe(false); + }); + + test("fails without a binding id cookie", async () => { + await setDeviceCodeCheckCookie("ABCD-1234"); + jar.delete("bindingId"); + + expect(await checkDeviceCodeCheckCookie("ABCD-1234")).toBe(false); + }); + + test("rejects the previous unsigned sha256(userCode:fingerprintId) value", async () => { + jar.set("deviceCodeCheck", createHash("sha256").update("ABCD-1234:binding-id-1").digest("hex")); + + expect(await checkDeviceCodeCheckCookie("ABCD-1234")).toBe(false); + }); + + test("rejects a value signed with a secret the server does not know", () => { + const value = createDeviceCodeCheck("ABCD-1234", "binding-id-1"); + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "another-secret-".padEnd(32, "x")); + + expect(isDeviceCodeCheckValid(value, "ABCD-1234", "binding-id-1")).toBe(false); + }); + + test("enforces the expiry server side", () => { + const now = Date.now(); + const value = createDeviceCodeCheck("ABCD-1234", "binding-id-1", now); + + expect( + isDeviceCodeCheckValid(value, "ABCD-1234", "binding-id-1", now + (DEVICE_CODE_CHECK_MAX_AGE_SECONDS - 1) * 1000), + ).toBe(true); + expect( + isDeviceCodeCheckValid(value, "ABCD-1234", "binding-id-1", now + (DEVICE_CODE_CHECK_MAX_AGE_SECONDS + 1) * 1000), + ).toBe(false); + }); + + test("is not interchangeable with a verification check for the same values", () => { + const now = Date.now(); + // both proofs live 5 minutes, so the same fields and time give the same payload; only the purpose key differs + const verificationCheck = createVerificationCheck("ABCD-1234", "binding-id-1", now); + + expect(isDeviceCodeCheckValid(verificationCheck, "ABCD-1234", "binding-id-1", now)).toBe(false); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/device-code-check.ts b/auth/ui/v2/apps/login/src/lib/server/device-code-check.ts new file mode 100644 index 0000000..57b9fdb --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/device-code-check.ts @@ -0,0 +1,54 @@ +import "server-only"; + +import { getBindingIdCookie, getOrSetBindingId, setBrowserCookie } from "@/lib/server/fingerprint"; +import { createSignedProof, isSignedProofValid } from "@/lib/server/signed-proof"; +import { cookies } from "next/headers"; + +// Binds a device authorization user code to the browser that entered it, +// so consent can only be given in that browser. +const COOKIE_NAME = "deviceCodeCheck"; +export const DEVICE_CODE_CHECK_MAX_AGE_SECONDS = 300; // 5 minutes + +/** + * Creates the value of the device code check cookie: `v1..`. + * The signature is an HMAC over the user code, the binding id of the browser and expiry, keyed with a server-only secret, + * like the other proofs of the login (see signed-proof.ts). + */ +export function createDeviceCodeCheck(userCode: string, bindingId: string, now: number = Date.now()): string { + return createSignedProof("device-code", [userCode, bindingId], DEVICE_CODE_CHECK_MAX_AGE_SECONDS, now); +} + +export function isDeviceCodeCheckValid( + value: string | undefined, + userCode: string, + bindingId: string | undefined, + now: number = Date.now(), +): boolean { + return isSignedProofValid("device-code", value, [userCode, bindingId], now); +} + +export async function setDeviceCodeCheckCookie(userCode: string) { + const bindingId = await getOrSetBindingId(); + + await setBrowserCookie(COOKIE_NAME, createDeviceCodeCheck(userCode, bindingId), DEVICE_CODE_CHECK_MAX_AGE_SECONDS); +} + +export async function checkDeviceCodeCheckCookie(userCode: string): Promise { + const cookiesList = await cookies(); + + // only read cookies, this is also called from a page + const bindingIdCookie = await getBindingIdCookie(); + + const valid = isDeviceCodeCheckValid(cookiesList.get(COOKIE_NAME)?.value, userCode, bindingIdCookie?.value); + + if (!valid) { + console.warn("Device code check failed."); + } + + return valid; +} + +export async function deleteDeviceCodeCheckCookie() { + const cookiesList = await cookies(); + cookiesList.delete(COOKIE_NAME); +} diff --git a/auth/ui/v2/apps/login/src/lib/server/enrollment-guard.test.ts b/auth/ui/v2/apps/login/src/lib/server/enrollment-guard.test.ts new file mode 100644 index 0000000..41739dc --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/enrollment-guard.test.ts @@ -0,0 +1,136 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { getEnrollmentAuthorizationError } from "./enrollment-guard"; + +vi.mock("@zitadel/client", () => ({ + // Convert a {seconds} Timestamp-like object into a real Date for expiry checks. + timestampDate: vi.fn((ts: { seconds: bigint | number }) => new Date(Number(ts.seconds) * 1000)), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + listAuthenticationMethodTypes: vi.fn(), +})); + +vi.mock("@/lib/server/verify-helper", () => ({ + checkUserVerification: vi.fn(), +})); + +const serviceConfig = { baseUrl: "https://example.com" } as any; + +// A timestamp far in the future / past, expressed the way the proto client shapes them. +const future = { seconds: BigInt(Math.floor(Date.now() / 1000) + 3600), nanos: 0 }; +const past = { seconds: BigInt(Math.floor(Date.now() / 1000) - 3600), nanos: 0 }; + +describe("getEnrollmentAuthorizationError", () => { + let mockListAuthenticationMethodTypes: any; + let mockCheckUserVerification: any; + + beforeEach(async () => { + vi.clearAllMocks(); + const { listAuthenticationMethodTypes } = await import("@/lib/server/zitadel"); + const { checkUserVerification } = await import("@/lib/server/verify-helper"); + mockListAuthenticationMethodTypes = vi.mocked(listAuthenticationMethodTypes); + mockCheckUserVerification = vi.mocked(checkUserVerification); + }); + + test("allows enrollment when the session has a verified password factor", async () => { + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "user-1", + session: { factors: { user: { id: "user-1" }, password: { verifiedAt: future } } } as any, + }); + + expect(result).toBeNull(); + // an authenticated session must not trigger the fallback checks + expect(mockListAuthenticationMethodTypes).not.toHaveBeenCalled(); + expect(mockCheckUserVerification).not.toHaveBeenCalled(); + }); + + test("allows enrollment when the session has a user-verified passkey factor", async () => { + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "user-1", + session: { factors: { user: { id: "user-1" }, webAuthN: { verifiedAt: future, userVerified: true } } } as any, + }); + + expect(result).toBeNull(); + }); + + test("rejects a presence-only passkey factor (userVerified false, user has auth methods)", async () => { + // A WebAuthn assertion without user-verification is a second-factor (U2F) check, not + // primary authentication — it must not authorize attaching a new authenticator. + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [1] }); + + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "user-1", + session: { factors: { user: { id: "user-1" }, webAuthN: { verifiedAt: future, userVerified: false } } } as any, + }); + + expect(result).toBe("You have to authenticate or have a valid User Verification Check"); + }); + + test("allows enrollment when the session has a verified IDP intent factor", async () => { + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "user-1", + session: { factors: { user: { id: "user-1" }, intent: { verifiedAt: future } } } as any, + }); + + expect(result).toBeNull(); + }); + + test("rejects an expired session even if a primary factor was verified (user has auth methods)", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [1] }); + + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "user-1", + session: { + factors: { user: { id: "user-1" }, password: { verifiedAt: past } }, + expirationDate: past, + } as any, + }); + + expect(result).toBe("You have to authenticate or have a valid User Verification Check"); + }); + + test("rejects an identify-only session when the user already has auth methods", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [1] }); + + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "victim-1", + session: { factors: { user: { id: "victim-1" } } } as any, + }); + + expect(result).toBe("You have to authenticate or have a valid User Verification Check"); + expect(mockCheckUserVerification).not.toHaveBeenCalled(); + }); + + test("rejects an identify-only session with no auth methods when user verification is missing", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + mockCheckUserVerification.mockResolvedValue(false); + + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "new-user", + session: { factors: { user: { id: "new-user" } } } as any, + }); + + expect(result).toBe("User Verification Check has to be done"); + expect(mockCheckUserVerification).toHaveBeenCalledWith("new-user"); + }); + + test("allows onboarding: no auth methods and a valid prior user-verification check", async () => { + mockListAuthenticationMethodTypes.mockResolvedValue({ authMethodTypes: [] }); + mockCheckUserVerification.mockResolvedValue(true); + + const result = await getEnrollmentAuthorizationError({ + serviceConfig, + userId: "new-user", + session: { factors: { user: { id: "new-user" } } } as any, + }); + + expect(result).toBeNull(); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/enrollment-guard.ts b/auth/ui/v2/apps/login/src/lib/server/enrollment-guard.ts new file mode 100644 index 0000000..288313a --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/enrollment-guard.ts @@ -0,0 +1,55 @@ +import "server-only"; + +import { createLogger } from "@/lib/server/logger"; +import { hasVerifiedPrimaryFactor } from "@/lib/server/session"; +import { checkUserVerification } from "@/lib/server/verify-helper"; +import { listAuthenticationMethodTypes, ServiceConfig } from "@/lib/server/zitadel"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; + +const logger = createLogger("enrollment-guard"); + +/** + * Central authorization gate for credential-enrollment entry points. + * + * Returns `null` when enrollment is allowed, or an error message string explaining why it + * is not. Enrollment is allowed when EITHER: + * - the session already proves authentication (a verified primary factor, not expired), OR + * - the user has no authentication methods yet AND a prior user-verification check passed + * (the legitimate email/init-code onboarding path, mirroring `registerPasskeyLink`). + * + * This mirrors the gate that `apps/login/src/lib/server/passkeys.ts` already applies to + * passkey registration, so that U2F, TOTP and OTP enrollment share the exact same rules. + */ +export async function getEnrollmentAuthorizationError({ + serviceConfig, + session, + userId, +}: { + serviceConfig: ServiceConfig; + session: Partial; + userId: string; +}): Promise { + if (hasVerifiedPrimaryFactor(session).valid) { + return null; + } + + // The session is only "identified", not authenticated. + const authmethods = await listAuthenticationMethodTypes({ serviceConfig, userId }); + + // If the user already has any auth method configured, enrollment requires a real + // authentication (or a valid user-verification check) — reject the identify-only session. + if (authmethods.authMethodTypes.length !== 0) { + return "You have to authenticate or have a valid User Verification Check"; + } + + // No auth methods yet: allow only if a prior user-verification check was completed + // (e.g. the user just verified their email / redeemed an invite in this browser). + const hasValidUserVerificationCheck = await checkUserVerification(userId); + + logger.info("hasValidUserVerificationCheck", { hasValidUserVerificationCheck }); + if (!hasValidUserVerificationCheck) { + return "User Verification Check has to be done"; + } + + return null; +} diff --git a/auth/ui/v2/apps/login/src/lib/server/fingerprint.test.ts b/auth/ui/v2/apps/login/src/lib/server/fingerprint.test.ts new file mode 100644 index 0000000..28d2d93 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/fingerprint.test.ts @@ -0,0 +1,477 @@ +import { + addIdpFlowProof, + getBindingIdCookie, + getOrSetBindingId, + getOrSetFingerprintId, + getUserAgent, +} from "@/lib/server/fingerprint"; +import { isIdpFlowProofValid } from "@/lib/server/idp-flow-proof"; +import { v4 as uuidv4 } from "uuid"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { create } from "@zitadel/client"; +import { cookies, headers } from "next/headers"; +import { userAgent } from "next/server"; +import { getSecuritySettings } from "./zitadel"; + +// Mock dependencies +vi.mock("uuid"); +vi.mock("next/headers", () => ({ + cookies: vi.fn(), + headers: vi.fn(), +})); +vi.mock("next/server", () => ({ + userAgent: vi.fn(), +})); +vi.mock("@zitadel/client", () => ({ + create: vi.fn(), +})); +vi.mock("./service-url", () => ({ + getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://api.example.com" } })), +})); +vi.mock("./zitadel", () => ({ + getSecuritySettings: vi.fn(), +})); + +describe("fingerprint", () => { + beforeEach(() => { + vi.clearAllMocks(); + // default: login is not embedded in an iframe + vi.mocked(getSecuritySettings).mockResolvedValue(undefined); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + describe("getOrSetFingerprintId", () => { + it("should return existing cookie value if present", async () => { + const existingId = "existing-fingerprint-id"; + const mockGet = vi.fn().mockReturnValue({ + name: "fingerprintId", + value: existingId, + }); + const mockCookies = { get: mockGet, set: vi.fn() }; + vi.mocked(cookies).mockResolvedValue(mockCookies as any); + + const result = await getOrSetFingerprintId(); + + expect(result).toBe(existingId); + expect(mockCookies.set).not.toHaveBeenCalled(); + }); + + it("should generate and set new ID if cookie doesn't exist", async () => { + const newUuid = "new-generated-uuid"; + const mockGet = vi.fn().mockReturnValue(undefined); + const mockSet = vi.fn(); + const mockCookies = { get: mockGet, set: mockSet }; + vi.mocked(cookies).mockResolvedValue(mockCookies as any); + vi.mocked(uuidv4).mockReturnValue(newUuid as any); + + const result = await getOrSetFingerprintId(); + + expect(result).toBe(newUuid); + expect(mockSet).toHaveBeenCalledWith({ + name: "fingerprintId", + value: newUuid, + httpOnly: true, + path: "/", + maxAge: 31536000, + sameSite: "lax", + secure: false, + }); + }); + + it("should use sameSite none with secure when iframe embedding is enabled", async () => { + const mockSet = vi.fn(); + vi.mocked(cookies).mockResolvedValue({ get: vi.fn().mockReturnValue(undefined), set: mockSet } as any); + vi.mocked(getSecuritySettings).mockResolvedValue({ embeddedIframe: { enabled: true } } as any); + + await getOrSetFingerprintId(); + + const callArgs = mockSet.mock.calls[0][0]; + expect(callArgs.sameSite).toBe("none"); + expect(callArgs.secure).toBe(true); + }); + + it("should use sameSite lax when iframe embedding is disabled", async () => { + const mockSet = vi.fn(); + vi.mocked(cookies).mockResolvedValue({ get: vi.fn().mockReturnValue(undefined), set: mockSet } as any); + vi.mocked(getSecuritySettings).mockResolvedValue({ embeddedIframe: { enabled: false } } as any); + + await getOrSetFingerprintId(); + + expect(mockSet.mock.calls[0][0].sameSite).toBe("lax"); + }); + + it("should fall back to sameSite lax when the security settings can't be loaded", async () => { + const mockSet = vi.fn(); + vi.mocked(cookies).mockResolvedValue({ get: vi.fn().mockReturnValue(undefined), set: mockSet } as any); + vi.mocked(getSecuritySettings).mockRejectedValue(new Error("unavailable")); + + // must not throw, the fingerprint is still needed by every flow + await getOrSetFingerprintId(); + + expect(mockSet.mock.calls[0][0].sameSite).toBe("lax"); + }); + + it("should not regenerate ID on subsequent calls with existing cookie", async () => { + const existingId = "persistent-id"; + const mockGet = vi.fn().mockReturnValue({ + name: "fingerprintId", + value: existingId, + }); + const mockCookies = { get: mockGet, set: vi.fn() }; + vi.mocked(cookies).mockResolvedValue(mockCookies as any); + + const result1 = await getOrSetFingerprintId(); + const result2 = await getOrSetFingerprintId(); + + expect(result1).toBe(existingId); + expect(result2).toBe(existingId); + expect(uuidv4).not.toHaveBeenCalled(); + }); + }); + + describe("getOrSetBindingId", () => { + it("should return the existing binding id cookie", async () => { + const mockGet = vi.fn((name: string) => (name === "bindingId" ? { name, value: "binding-1" } : undefined)); + const mockSet = vi.fn(); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: mockSet } as any); + + expect(await getOrSetBindingId()).toBe("binding-1"); + expect(await getBindingIdCookie()).toEqual({ name: "bindingId", value: "binding-1" }); + expect(mockSet).not.toHaveBeenCalled(); + }); + + it("should set a new random binding id with the iframe-aware attributes", async () => { + const mockSet = vi.fn(); + vi.mocked(cookies).mockResolvedValue({ get: vi.fn().mockReturnValue(undefined), set: mockSet } as any); + vi.mocked(uuidv4).mockReturnValue("new-binding-id" as any); + vi.mocked(getSecuritySettings).mockResolvedValue({ embeddedIframe: { enabled: true } } as any); + + const result = await getOrSetBindingId(); + + expect(result).toBe("new-binding-id"); + expect(mockSet).toHaveBeenCalledWith({ + name: "bindingId", + value: "new-binding-id", + httpOnly: true, + path: "/", + maxAge: 31536000, + sameSite: "none", + secure: true, + }); + }); + }); + + describe("addIdpFlowProof", () => { + it("should set a flow proof bound to this browser and the session to link", async () => { + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + const mockGet = vi.fn((name: string) => (name === "bindingId" ? { name, value: "binding-1" } : undefined)); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + const params = new URLSearchParams(); + await addIdpFlowProof(params, "session-1"); + const signInParams = new URLSearchParams(); + await addIdpFlowProof(signInParams); + + expect(isIdpFlowProofValid(params.get("flowFingerprint") ?? undefined, "binding-1", "session-1")).toBe(true); + expect(isIdpFlowProofValid(signInParams.get("flowFingerprint") ?? undefined, "binding-1")).toBe(true); + }); + }); + + describe("getUserAgent", () => { + it("should send the fingerprintId but never the binding id to the API", async () => { + const mockGet = vi.fn((name: string) => ({ name, value: name === "bindingId" ? "secret-binding" : "public-fp" })); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + vi.mocked(headers).mockResolvedValue({ get: () => null } as any); + vi.mocked(userAgent).mockReturnValue({ device: {}, engine: {}, os: {}, browser: {} } as any); + + await getUserAgent(); + + const sent = vi.mocked(create).mock.calls[0][1]; + expect(sent).toEqual(expect.objectContaining({ fingerprintId: "public-fp" })); + expect(JSON.stringify(sent)).not.toContain("secret-binding"); + expect(mockGet).not.toHaveBeenCalledWith("bindingId"); + }); + + it("should create user agent with all components", async () => { + const mockFingerprintId = "test-fingerprint"; + const mockGet = vi.fn().mockReturnValue({ + name: "fingerprintId", + value: mockFingerprintId, + }); + const mockCookies = { get: mockGet, set: vi.fn() }; + vi.mocked(cookies).mockResolvedValue(mockCookies as any); + + const mockHeaders = new Map([ + ["user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"], + ["x-forwarded-for", "192.168.1.1"], + ]); + vi.mocked(headers).mockResolvedValue({ + get: (key: string) => mockHeaders.get(key) ?? null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: { type: "desktop", vendor: "Dell", model: "XPS" }, + engine: { name: "Blink", version: "120.0" }, + os: { name: "Windows", version: "10" }, + browser: { name: "Chrome", version: "120.0" }, + } as any); + + const mockUserAgent = { + ip: "192.168.1.1", + header: { + "user-agent": { + values: ["Mozilla/5.0 (Windows NT 10.0; Win64; x64)"], + }, + }, + description: "Chrome, 120.0, desktop, Dell, XPS, , Blink, 120.0, , Windows, 10, ", + fingerprintId: mockFingerprintId, + }; + vi.mocked(create).mockReturnValue(mockUserAgent as any); + + const result = await getUserAgent(); + + expect(result).toEqual(mockUserAgent); + expect(create).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + fingerprintId: mockFingerprintId, + ip: "192.168.1.1", + }), + ); + }); + + it("should use x-forwarded-for header for IP if available", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + const mockHeaders = new Map([ + ["x-forwarded-for", "203.0.113.1"], + ["remoteAddress", "192.168.1.1"], + ]); + vi.mocked(headers).mockResolvedValue({ + get: (key: string) => mockHeaders.get(key) ?? null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: {}, + engine: {}, + os: {}, + browser: {}, + } as any); + + await getUserAgent(); + + expect(create).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + ip: "203.0.113.1", + }), + ); + }); + + it("should fallback to remoteAddress if x-forwarded-for is not available", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + const mockHeaders = new Map([["remoteAddress", "192.168.1.100"]]); + vi.mocked(headers).mockResolvedValue({ + get: (key: string) => mockHeaders.get(key) ?? null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: {}, + engine: {}, + os: {}, + browser: {}, + } as any); + + await getUserAgent(); + + expect(create).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + ip: "192.168.1.100", + }), + ); + }); + + it("should use empty string for IP if no headers available", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + const mockHeaders = new Map(); + vi.mocked(headers).mockResolvedValue({ + get: (key: string) => mockHeaders.get(key) ?? null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: {}, + engine: {}, + os: {}, + browser: {}, + } as any); + + await getUserAgent(); + + expect(create).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + ip: "", + }), + ); + }); + + it("should parse user agent header values", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + const userAgentString = "Mozilla/5.0,AppleWebKit/537.36,Chrome/120.0"; + const mockHeaders = new Map([["user-agent", userAgentString]]); + vi.mocked(headers).mockResolvedValue({ + get: (key: string) => mockHeaders.get(key) ?? null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: {}, + engine: {}, + os: {}, + browser: {}, + } as any); + + await getUserAgent(); + + expect(create).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + header: { + "user-agent": { + values: ["Mozilla/5.0", "AppleWebKit/537.36", "Chrome/120.0"], + }, + }, + }), + ); + }); + + it("should build description from device components", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + vi.mocked(headers).mockResolvedValue({ + get: () => null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: { type: "mobile", vendor: "Apple", model: "iPhone 15" }, + engine: { name: "WebKit", version: "605.1.15" }, + os: { name: "iOS", version: "17.0" }, + browser: { name: "Safari", version: "17.0" }, + } as any); + + await getUserAgent(); + + const createCall = vi.mocked(create).mock.calls[0]?.[1]; + expect(createCall).toBeDefined(); + expect(createCall?.description).toContain("Safari"); + expect(createCall?.description).toContain("17.0"); + expect(createCall?.description).toContain("mobile"); + expect(createCall?.description).toContain("Apple"); + expect(createCall?.description).toContain("iPhone 15"); + expect(createCall?.description).toContain("WebKit"); + expect(createCall?.description).toContain("iOS"); + }); + + it("should handle missing device components gracefully", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + vi.mocked(headers).mockResolvedValue({ + get: () => null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: {}, + engine: {}, + os: {}, + browser: {}, + } as any); + + await getUserAgent(); + + expect(create).toHaveBeenCalled(); + const createCall = vi.mocked(create).mock.calls[0]?.[1]; + expect(createCall?.description).toBeDefined(); + }); + + it("should handle partial device information", async () => { + const mockGet = vi.fn().mockReturnValue({ + value: "test-id", + }); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: vi.fn() } as any); + + vi.mocked(headers).mockResolvedValue({ + get: () => null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: { vendor: "Samsung" }, + engine: { name: "Blink" }, + os: { name: "Android" }, + browser: { name: "Chrome" }, + } as any); + + await getUserAgent(); + + const createCall = vi.mocked(create).mock.calls[0]?.[1]; + expect(createCall).toBeDefined(); + expect(createCall?.description).toContain("Samsung"); + expect(createCall?.description).toContain("Blink"); + expect(createCall?.description).toContain("Android"); + expect(createCall?.description).toContain("Chrome"); + }); + + it("should generate new fingerprint ID if none exists", async () => { + const newUuid = "newly-generated-fingerprint"; + const mockGet = vi.fn().mockReturnValue(undefined); + const mockSet = vi.fn(); + vi.mocked(cookies).mockResolvedValue({ get: mockGet, set: mockSet } as any); + vi.mocked(uuidv4).mockReturnValue(newUuid as any); + + vi.mocked(headers).mockResolvedValue({ + get: () => null, + } as any); + + vi.mocked(userAgent).mockReturnValue({ + device: {}, + engine: {}, + os: {}, + browser: {}, + } as any); + + await getUserAgent(); + + expect(create).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + fingerprintId: newUuid, + }), + ); + }); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/fingerprint.ts b/auth/ui/v2/apps/login/src/lib/server/fingerprint.ts new file mode 100644 index 0000000..d0dfebc --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/fingerprint.ts @@ -0,0 +1,102 @@ +import "server-only"; + +import { create } from "@zitadel/client"; +import { UserAgent, UserAgentSchema } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { cookies, headers } from "next/headers"; +import { userAgent } from "next/server"; +import { v4 as uuidv4 } from "uuid"; +import { createIdpFlowProof } from "./idp-flow-proof"; +import { createLogger } from "./logger"; +import { getServiceConfig } from "./service-url"; +import { getSecuritySettings } from "./zitadel"; + +const logger = createLogger("fingerprint"); + +const BINDING_ID_COOKIE = "bindingId"; + +// sets an httpOnly browser cookie (1 year by default) that also works when the login is embedded in an iframe +export async function setBrowserCookie(name: string, value: string, maxAge: number = 31536000) { + const cookiesList = await cookies(); + + let iFrameEnabled = false; + try { + const { serviceConfig } = getServiceConfig(await headers()); + const securitySettings = await getSecuritySettings({ serviceConfig }); + iFrameEnabled = !!securitySettings?.embeddedIframe?.enabled; + } catch (error) { + logger.warn(`Could not load security settings, setting the ${name} cookie without iframe support`, { error }); + } + + return cookiesList.set({ + name, + value, + httpOnly: true, + path: "/", + maxAge, + // "none" is required for iframe embedding (with secure flag), "lax" allows cookies during top-level navigation + sameSite: iFrameEnabled ? "none" : "lax", + // "none" is only accepted by browsers together with "secure", otherwise the cookie is silently dropped + secure: process.env.NODE_ENV === "production" || iFrameEnabled, + }); +} + +// returns the value of the cookie, or sets it to a new random value +async function getOrSetBrowserCookie(name: string): Promise { + const cookie = (await cookies()).get(name); + if (cookie) { + return cookie.value; + } + + const value = uuidv4(); + await setBrowserCookie(name, value); + return value; +} + +export async function getOrSetFingerprintId(): Promise { + return getOrSetBrowserCookie("fingerprintId"); +} + +export async function getBindingIdCookie() { + const cookiesList = await cookies(); + return cookiesList.get(BINDING_ID_COOKIE); +} + +/** + * Returns the random binding id of this browser, which the signed proofs of the login (see + * signed-proof.ts) are bound to. Unlike the fingerprintId it is never sent to the API, so it can't + * be read back through a session and stays a secret of this browser. + */ +export async function getOrSetBindingId(): Promise { + return getOrSetBrowserCookie(BINDING_ID_COOKIE); +} + +// every external IdP flow start calls this, so no start can forget the browser binding +export async function addIdpFlowProof(params: URLSearchParams, linkToSessionId?: string): Promise { + params.set("flowFingerprint", createIdpFlowProof(await getOrSetBindingId(), linkToSessionId)); +} + +export async function getUserAgent(): Promise { + const _headers = await headers(); + + const fingerprintId = await getOrSetFingerprintId(); + + const { device, engine, os, browser } = userAgent({ headers: _headers }); + + const userAgentHeader = _headers.get("user-agent"); + + const userAgentHeaderValues = userAgentHeader?.split(","); + + const deviceDescription = `${device?.type ? `${device.type},` : ""} ${device?.vendor ? `${device.vendor},` : ""} ${device.model ? `${device.model},` : ""} `; + const osDescription = `${os?.name ? `${os.name},` : ""} ${os?.version ? `${os.version},` : ""} `; + const engineDescription = `${engine?.name ? `${engine.name},` : ""} ${engine?.version ? `${engine.version},` : ""} `; + const browserDescription = `${browser?.name ? `${browser.name},` : ""} ${browser.version ? `${browser.version},` : ""} `; + + const userAgentData: UserAgent = create(UserAgentSchema, { + ip: _headers.get("x-forwarded-for") ?? _headers.get("remoteAddress") ?? "", + header: { "user-agent": { values: userAgentHeaderValues } }, + description: `${browserDescription}, ${deviceDescription}, ${engineDescription}, ${osDescription}`, + fingerprintId: fingerprintId, + }); + + return userAgentData; +} diff --git a/auth/ui/v2/apps/login/src/lib/server/flow-initiation.test.ts b/auth/ui/v2/apps/login/src/lib/server/flow-initiation.test.ts new file mode 100644 index 0000000..c5309b7 --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/flow-initiation.test.ts @@ -0,0 +1,1136 @@ +import type { Cookie } from "@/lib/server/cookies"; +import { createIdpFlowProof, isIdpFlowProofValid } from "@/lib/server/idp-flow-proof"; +import { NextRequest } from "next/server"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { FlowInitiationParams, handleOIDCFlowInitiation } from "./flow-initiation"; + +vi.mock("@/lib/server/cookies", () => ({ + getLanguageCookie: vi.fn(), + setLanguageCookie: vi.fn(), +})); + +vi.mock("@/lib/server/auth-utils", () => ({ + getValidLocaleFromUILocales: vi.fn(), +})); + +vi.mock("@/lib/idp", () => ({ + idpTypeToSlug: vi.fn(), +})); + +vi.mock("@/lib/server/fingerprint", () => ({ + addIdpFlowProof: vi.fn(), +})); + +vi.mock("@/lib/actions/loginname", () => ({ + sendLoginname: vi.fn(), +})); + +vi.mock("@/lib/server/service-url", () => ({ + constructUrl: vi.fn(), +})); + +vi.mock("@/lib/server/session", () => ({ + findValidSession: vi.fn(), +})); + +vi.mock("@/lib/server/zitadel", () => ({ + createCallback: vi.fn(), + createResponse: vi.fn(), + getActiveIdentityProviders: vi.fn(), + getAuthRequest: vi.fn(), + getLoginSettings: vi.fn(), + getOrgsByDomain: vi.fn(), + getSAMLRequest: vi.fn(), + getSecuritySettings: vi.fn(), + startIdentityProviderFlow: vi.fn(), +})); + +vi.mock("@zitadel/client", () => ({ + create: vi.fn(), +})); + +vi.mock("escape-html", () => ({ + default: (s: string) => s, +})); + +function makeRequest(url = "https://example.com/login?requestId=oidc_abc123"): NextRequest { + return new NextRequest(url); +} + +function makeCookie(id: string, overrides?: Partial): Cookie { + return { id, token: "tok", loginName: "", creationTs: "", expirationTs: "", changeTs: "", ...overrides }; +} + +function makeBaseParams(overrides?: Partial): FlowInitiationParams { + return { + serviceConfig: { baseUrl: "https://api.example.com" } as any, + requestId: "oidc_abc123", + sessions: [], + sessionCookies: [], + request: makeRequest(), + ...overrides, + }; +} + +describe("handleOIDCFlowInitiation — locale / cookie handling", () => { + let mockGetLanguageCookie: ReturnType; + let mockSetLanguageCookie: ReturnType; + let mockGetValidLocaleFromUILocales: ReturnType; + let mockGetAuthRequest: ReturnType; + let mockConstructUrl: ReturnType; + let mockFindValidSession: ReturnType; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); + + const cookies = await import("@/lib/server/cookies"); + const authUtils = await import("@/lib/server/auth-utils"); + const zitadel = await import("@/lib/server/zitadel"); + const serviceUrl = await import("@/lib/server/service-url"); + const session = await import("@/lib/server/session"); + + mockGetLanguageCookie = vi.mocked(cookies.getLanguageCookie); + mockSetLanguageCookie = vi.mocked(cookies.setLanguageCookie); + mockGetValidLocaleFromUILocales = vi.mocked(authUtils.getValidLocaleFromUILocales); + mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest); + mockConstructUrl = vi.mocked(serviceUrl.constructUrl); + mockFindValidSession = vi.mocked(session.findValidSession); + + // Default auth request: no prompts, no special scopes + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: undefined, + }, + }); + + // constructUrl returns a real URL object so redirect paths resolve correctly + mockConstructUrl.mockImplementation((_req: any, path: string) => { + return new URL(`https://example.com${path}`); + }); + + mockFindValidSession.mockResolvedValue(null); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + describe("when uiLocales yields no valid locale", () => { + test("should not read or set the language cookie", async () => { + mockGetValidLocaleFromUILocales.mockReturnValue(null); + + await handleOIDCFlowInitiation(makeBaseParams()); + + expect(mockGetLanguageCookie).not.toHaveBeenCalled(); + expect(mockSetLanguageCookie).not.toHaveBeenCalled(); + }); + }); + + describe("when uiLocales yields a valid locale and ZITADEL_UI_LOCALES_OVERRIDE_COOKIE is unset (default)", () => { + beforeEach(() => { + mockGetValidLocaleFromUILocales.mockReturnValue("de"); + }); + + test("should set cookie when no existing language cookie is present", async () => { + mockGetLanguageCookie.mockResolvedValue(undefined); + + await handleOIDCFlowInitiation(makeBaseParams()); + + expect(mockGetLanguageCookie).toHaveBeenCalledOnce(); + expect(mockSetLanguageCookie).toHaveBeenCalledWith("de"); + }); + + test("should NOT overwrite an existing language cookie", async () => { + mockGetLanguageCookie.mockResolvedValue("fr"); + + await handleOIDCFlowInitiation(makeBaseParams()); + + expect(mockGetLanguageCookie).toHaveBeenCalledOnce(); + expect(mockSetLanguageCookie).not.toHaveBeenCalled(); + }); + }); + + describe("when uiLocales yields a valid locale and ZITADEL_UI_LOCALES_OVERRIDE_COOKIE=true", () => { + beforeEach(() => { + vi.stubEnv("ZITADEL_UI_LOCALES_OVERRIDE_COOKIE", "true"); + mockGetValidLocaleFromUILocales.mockReturnValue("ja"); + }); + + test("should set cookie even when an existing language cookie is already set", async () => { + mockGetLanguageCookie.mockResolvedValue("fr"); + + await handleOIDCFlowInitiation(makeBaseParams()); + + expect(mockSetLanguageCookie).toHaveBeenCalledWith("ja"); + }); + + test("should set cookie when no existing cookie is present", async () => { + mockGetLanguageCookie.mockResolvedValue(undefined); + + await handleOIDCFlowInitiation(makeBaseParams()); + + expect(mockSetLanguageCookie).toHaveBeenCalledWith("ja"); + }); + }); + + describe("when ZITADEL_UI_LOCALES_OVERRIDE_COOKIE is explicitly 'false'", () => { + test("should preserve an existing cookie", async () => { + vi.stubEnv("ZITADEL_UI_LOCALES_OVERRIDE_COOKIE", "false"); + mockGetValidLocaleFromUILocales.mockReturnValue("es"); + mockGetLanguageCookie.mockResolvedValue("it"); + + await handleOIDCFlowInitiation(makeBaseParams()); + + expect(mockSetLanguageCookie).not.toHaveBeenCalled(); + }); + }); +}); + +describe("handleOIDCFlowInitiation — org-scoped session filtering", () => { + let mockGetAuthRequest: ReturnType; + let mockConstructUrl: ReturnType; + let mockFindValidSession: ReturnType; + let mockSendLoginname: ReturnType; + let mockGetLoginSettings: ReturnType; + + const orgSession = { + id: "session-org", + factors: { user: { id: "user1", organizationId: "111111", loginName: "user@org.com" } }, + }; + const otherOrgSession = { + id: "session-other", + factors: { user: { id: "user2", organizationId: "999999", loginName: "user@other.com" } }, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); + + const zitadel = await import("@/lib/server/zitadel"); + const serviceUrl = await import("@/lib/server/service-url"); + const session = await import("@/lib/server/session"); + const authUtils = await import("@/lib/server/auth-utils"); + const loginname = await import("@/lib/actions/loginname"); + + mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest); + mockConstructUrl = vi.mocked(serviceUrl.constructUrl); + mockFindValidSession = vi.mocked(session.findValidSession); + mockSendLoginname = vi.mocked(loginname.sendLoginname); + mockGetLoginSettings = vi.mocked(zitadel.getLoginSettings); + mockGetLoginSettings.mockResolvedValue(undefined); + vi.mocked(authUtils.getValidLocaleFromUILocales).mockReturnValue(null); + + mockConstructUrl.mockImplementation((_req: any, path: string) => { + return new URL(`https://example.com${path}`); + }); + + mockFindValidSession.mockResolvedValue(null); + // Default: hint cannot be resolved to a redirect, exercising the prefilled + // /loginname fallback. Individual tests override this to assert the happy path. + mockSendLoginname.mockResolvedValue(undefined); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test("should redirect to /loginname when org scope filters out all sessions (default prompt)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [], + loginHint: undefined, + }, + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [makeCookie("session-other")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).not.toContain("/accounts"); + }); + + test("should resolve loginHint server-side (straight to next step) when org scope filters out all sessions", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [], + loginHint: "user@example.com", + }, + }); + + mockSendLoginname.mockResolvedValue({ + redirect: "/password?loginName=user%40example.com", + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [makeCookie("session-other")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/password"); + expect(location).not.toContain("/loginname"); + expect(location).not.toContain("/accounts"); + }); + + test("should prefill /loginname WITHOUT submit=true when loginHint cannot be resolved and org scope filters out all sessions", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [], + loginHint: "user@example.com", + }, + }); + + // mockSendLoginname resolves to undefined (default) → fallback path. + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [makeCookie("session-other")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).toContain("loginName=user%40example.com"); + expect(location).not.toContain("submit=true"); + expect(location).not.toContain("/accounts"); + }); + + test("should redirect to /accounts when org-eligible sessions exist but none are valid (default prompt)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [], + loginHint: undefined, + }, + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [orgSession] as any, + sessionCookies: [makeCookie("session-org")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/accounts"); + }); + + test("should resolve loginHint server-side when it matches no session but an unrelated session exists (default prompt)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@example.com", + }, + }); + + // An unrelated session is present (so eligibleSessions is non-empty), but + // findValidSession filtered by the hint returns nothing. + mockFindValidSession.mockResolvedValue(null); + + mockSendLoginname.mockResolvedValue({ + redirect: "/password?loginName=user%40example.com", + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [makeCookie("session-other")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/password"); + expect(location).not.toContain("/loginname"); + expect(location).not.toContain("/accounts"); + }); + + test("should fall back to prefilled /loginname (no submit) when loginHint cannot be resolved and an unrelated session exists (default prompt)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@example.com", + }, + }); + + mockFindValidSession.mockResolvedValue(null); + // mockSendLoginname resolves to undefined (default) → fallback path. + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [makeCookie("session-other")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).toContain("loginName=user%40example.com"); + expect(location).not.toContain("submit=true"); + expect(location).not.toContain("/accounts"); + }); + + test("should redirect to /loginname when org scope filters out all sessions (SELECT_ACCOUNT prompt)", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [Prompt.SELECT_ACCOUNT], + loginHint: undefined, + }, + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [makeCookie("session-other")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).not.toContain("/accounts"); + }); + + test("should redirect to /accounts when org-eligible sessions exist (SELECT_ACCOUNT prompt)", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [Prompt.SELECT_ACCOUNT], + loginHint: undefined, + }, + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [orgSession] as any, + sessionCookies: [makeCookie("session-org")], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/accounts"); + }); + + test("should redirect to /loginname when no org scope and no sessions", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: undefined, + }, + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + }); + + test("should resolve loginHint server-side when there are no sessions (default prompt)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@example.com", + }, + }); + + mockSendLoginname.mockResolvedValue({ + redirect: "/password?loginName=user%40example.com", + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/password"); + expect(location).not.toContain("/loginname"); + }); + + test("should prefill /loginname WITHOUT submit=true when there are no sessions and loginHint cannot be resolved", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@example.com", + }, + }); + + // mockSendLoginname resolves to undefined (default) → fallback path. + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).toContain("loginName=user%40example.com"); + expect(location).not.toContain("submit=true"); + }); + + test("should resolve loginHint without forwarding enumeration settings (derived server-side by sendLoginname)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "unknown@example.com", + }, + }); + + // Enumeration protection is derived inside sendLoginname from the request-context + // login settings; resolveLoginHint only passes the hint and the org context, and + // an unknown hint still redirects to the (fake) /password step. + mockSendLoginname.mockResolvedValue({ + redirect: "/password?loginName=unknown%40example.com", + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + expect(mockSendLoginname).toHaveBeenCalledWith( + expect.objectContaining({ + loginName: "unknown@example.com", + }), + ); + expect(mockSendLoginname).not.toHaveBeenCalledWith( + expect.objectContaining({ + ignoreUnknownUsernames: expect.anything(), + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/password"); + expect(location).not.toContain("/loginname"); + }); + + test("should redirect to an absolute IdP URL as-is without prepending the base path (domain discovery auto-redirect)", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@discovered-org.com", + }, + }); + + // Simulate a base path being configured, as in ZITADEL Cloud (/ui/v2/login). + mockConstructUrl.mockImplementation((_req: any, path: string) => { + return new URL(`https://example.com/ui/v2/login${path}`); + }); + + // sendLoginname resolved the hint via domain discovery to an org with a + // single external IdP and returns the absolute authorize URL of that IdP. + const idpUrl = "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize?client_id=xyz&state=abc"; + mockSendLoginname.mockResolvedValue({ redirect: idpUrl }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toBe(idpUrl); + // The base path must never be glued onto an absolute URL + // (regression: https:///ui/v2/loginhttps://login.microsoftonline.com/...). + expect(location).not.toContain("/ui/v2/login"); + expect(mockConstructUrl).not.toHaveBeenCalledWith(expect.anything(), idpUrl); + }); + + test("should render an auto-submit form when loginHint resolves to a SAML POST-binding IdP", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@discovered-org.com", + }, + }); + + // sendLoginname resolved the hint via domain discovery to an org whose + // single IdP is SAML with POST binding: the AuthnRequest is delivered as + // form fields, not a redirect URL. + mockSendLoginname.mockResolvedValue({ + samlData: { + url: "https://adfs.example.com/adfs/ls", + fields: { SAMLRequest: "PHNhbWxwOkF1dGhuUmVxdWVzdD4=", RelayState: "relay-123" }, + }, + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + // No redirect: the response is an HTML page auto-posting the form to the IdP. + expect(res.headers.get("location")).toBeNull(); + expect(res.headers.get("content-type")).toContain("text/html"); + + const html = await res.text(); + expect(html).toContain('action="https://adfs.example.com/adfs/ls"'); + expect(html).toContain('name="SAMLRequest"'); + expect(html).toContain('value="PHNhbWxwOkF1dGhuUmVxdWVzdD4="'); + expect(html).toContain('name="RelayState"'); + expect(html).toContain("document.forms[0].submit()"); + }); + + test("should block unsafe SAML post URLs from loginHint resolution and fall back to /loginname", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@example.com", + }, + }); + + mockSendLoginname.mockResolvedValue({ + samlData: { + url: "javascript:alert(1)", + fields: { SAMLRequest: "abc" }, + }, + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).not.toContain("javascript:"); + }); + + test("should block unsafe absolute redirect URLs from loginHint resolution and fall back to /loginname", async () => { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: "user@example.com", + }, + }); + + mockSendLoginname.mockResolvedValue({ redirect: "javascript:alert(1)" }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).not.toContain("javascript:"); + }); +}); + +describe("handleOIDCFlowInitiation — stale session cookie fallback (#12252)", () => { + let mockGetAuthRequest: ReturnType; + let mockConstructUrl: ReturnType; + let mockFindValidSession: ReturnType; + let mockSendLoginname: ReturnType; + + // Cookie entries left behind after an RP-initiated logout terminated the + // server-side sessions: no live Session objects, but loginName is still known. + const staleOrgCookie = makeCookie("session-stale-org", { loginName: "user@org.com", organization: "111111" }); + const staleOtherOrgCookie = makeCookie("session-stale-other", { loginName: "user@other.com", organization: "999999" }); + const otherOrgSession = { + id: "session-other", + factors: { user: { id: "user2", organizationId: "999999", loginName: "user@other.com" } }, + }; + + function authRequestWith(overrides: Record) { + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [], + loginHint: undefined, + ...overrides, + }, + }); + } + + beforeEach(async () => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); + + const zitadel = await import("@/lib/server/zitadel"); + const serviceUrl = await import("@/lib/server/service-url"); + const session = await import("@/lib/server/session"); + const authUtils = await import("@/lib/server/auth-utils"); + const loginname = await import("@/lib/actions/loginname"); + + mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest); + mockConstructUrl = vi.mocked(serviceUrl.constructUrl); + mockFindValidSession = vi.mocked(session.findValidSession); + mockSendLoginname = vi.mocked(loginname.sendLoginname); + vi.mocked(zitadel.getLoginSettings).mockResolvedValue(undefined); + vi.mocked(zitadel.getSecuritySettings).mockResolvedValue(undefined); + vi.mocked(authUtils.getValidLocaleFromUILocales).mockReturnValue(null); + + mockConstructUrl.mockImplementation((_req: any, path: string) => { + return new URL(`https://example.com${path}`); + }); + + mockFindValidSession.mockResolvedValue(null); + mockSendLoginname.mockResolvedValue(undefined); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test("should redirect to /accounts when there are no live sessions but the cookie references an account", async () => { + authRequestWith({}); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/accounts"); + expect(location).not.toContain("/loginname"); + }); + + test("should ignore cookie entries without a loginName", async () => { + authRequestWith({}); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ sessions: [], sessionCookies: [{ ...staleOrgCookie, loginName: "" }] }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + }); + + test("should prefer login_hint over the cookie fallback when there are no live sessions", async () => { + authRequestWith({ loginHint: "hinted@org.com" }); + mockSendLoginname.mockResolvedValue({ redirect: "/password?requestId=oidc_abc123" }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/password"); + expect(location).not.toContain("/accounts"); + }); + + test("should not show the account picker for prompt=none even if the cookie references an account", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + authRequestWith({ prompt: [Prompt.NONE] }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] })); + + const location = res.headers.get("location") ?? ""; + expect(location).not.toContain("/accounts"); + }); + + test("should redirect to /loginname when the cookie account belongs to a different org than the org scope", async () => { + authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOtherOrgCookie] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).not.toContain("/accounts"); + }); + + test("should redirect to /accounts when the cookie account matches the org scope", async () => { + authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/accounts"); + expect(location).toContain("organization=111111"); + }); + + test("should keep /accounts for SELECT_ACCOUNT when live sessions are filtered out by org but the cookie has a matching account", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"], prompt: [Prompt.SELECT_ACCOUNT] }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [{ ...staleOtherOrgCookie, id: "session-other" }, staleOrgCookie], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/accounts"); + }); + + test("should not show the account picker for prompt=login even if the cookie references an account", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + authRequestWith({ prompt: [Prompt.LOGIN] }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] })); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).not.toContain("/accounts"); + }); + + test("should let login_hint win over the cookie fallback for SELECT_ACCOUNT when no live session is eligible", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + authRequestWith({ + scope: ["urn:zitadel:iam:org:id:111111"], + prompt: [Prompt.SELECT_ACCOUNT], + loginHint: "hinted@org.com", + }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [ + makeCookie("session-other", { loginName: "user@other.com", organization: "999999" }), + staleOrgCookie, + ], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/loginname"); + expect(location).toContain("loginName=hinted%40org.com"); + expect(location).not.toContain("/accounts"); + }); + + test("should keep /accounts (default prompt) when live sessions are filtered out by org but the cookie has a matching account", async () => { + authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] }); + + const res = await handleOIDCFlowInitiation( + makeBaseParams({ + sessions: [otherOrgSession] as any, + sessionCookies: [{ ...staleOtherOrgCookie, id: "session-other" }, staleOrgCookie], + }), + ); + + const location = res.headers.get("location") ?? ""; + expect(location).toContain("/accounts"); + }); +}); + +describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix", () => { + let mockGetAuthRequest: ReturnType; + let mockConstructUrl: ReturnType; + let mockSendLoginname: ReturnType; + + const existingSession = { + id: "session-1", + factors: { user: { id: "user1", organizationId: "org1", loginName: "user@example.com" } }, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); + + const zitadel = await import("@/lib/server/zitadel"); + const serviceUrl = await import("@/lib/server/service-url"); + const authUtils = await import("@/lib/server/auth-utils"); + const loginname = await import("@/lib/actions/loginname"); + + mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest); + mockConstructUrl = vi.mocked(serviceUrl.constructUrl); + mockSendLoginname = vi.mocked(loginname.sendLoginname); + vi.mocked(authUtils.getValidLocaleFromUILocales).mockReturnValue(null); + + mockConstructUrl.mockImplementation((_req: any, path: string) => { + return new URL(`https://example.com${path}`); + }); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test("should pass requestId with oidc_ prefix to sendLoginname (not authRequest.id)", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [Prompt.LOGIN], + loginHint: "user@example.com", + }, + }); + + mockSendLoginname.mockResolvedValue({ + redirect: "/password?loginName=user%40example.com", + }); + + await handleOIDCFlowInitiation( + makeBaseParams({ + requestId: "oidc_abc123", + sessions: [existingSession] as any, + sessionCookies: [makeCookie("session-1")], + }), + ); + + expect(mockSendLoginname).toHaveBeenCalledWith( + expect.objectContaining({ + loginName: "user@example.com", + requestId: "oidc_abc123", + }), + ); + }); + + test("should NOT pass raw authRequest.id without oidc_ prefix to sendLoginname", async () => { + const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: [], + prompt: [Prompt.LOGIN], + loginHint: "user@example.com", + }, + }); + + mockSendLoginname.mockResolvedValue({ + redirect: "/password?loginName=user%40example.com", + }); + + await handleOIDCFlowInitiation( + makeBaseParams({ + requestId: "oidc_abc123", + sessions: [existingSession] as any, + sessionCookies: [makeCookie("session-1")], + }), + ); + + // Ensure the raw authRequest.id is NOT what's passed + expect(mockSendLoginname).not.toHaveBeenCalledWith( + expect.objectContaining({ + requestId: "abc123", + }), + ); + }); +}); + +describe("handleOIDCFlowInitiation — idp scope (urn:zitadel:iam:org:idp:id)", () => { + let mockGetAuthRequest: ReturnType; + let mockConstructUrl: ReturnType; + let mockGetActiveIdentityProviders: ReturnType; + let mockStartIdentityProviderFlow: ReturnType; + let mockIdpTypeToSlug: ReturnType; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); + + const zitadel = await import("@/lib/server/zitadel"); + const serviceUrl = await import("@/lib/server/service-url"); + const authUtils = await import("@/lib/server/auth-utils"); + const idpLib = await import("@/lib/idp"); + + mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest); + mockConstructUrl = vi.mocked(serviceUrl.constructUrl); + mockGetActiveIdentityProviders = vi.mocked(zitadel.getActiveIdentityProviders); + mockStartIdentityProviderFlow = vi.mocked(zitadel.startIdentityProviderFlow); + mockIdpTypeToSlug = vi.mocked(idpLib.idpTypeToSlug); + vi.mocked(authUtils.getValidLocaleFromUILocales).mockReturnValue(null); + + mockConstructUrl.mockImplementation((_req: any, path: string) => { + return new URL(`https://example.com${path}`); + }); + mockIdpTypeToSlug.mockReturnValue("azure"); + + vi.stubEnv("ZITADEL_SESSION_COOKIE_SECRET", "test-session-cookie-secret-at-least-32-chars"); + const fingerprint = await import("@/lib/server/fingerprint"); + // the real helper reads the binding id cookie, here the browser binding id is "fp123" + vi.mocked(fingerprint.addIdpFlowProof).mockImplementation(async (params, linkToSessionId) => { + params.set("flowFingerprint", createIdpFlowProof("fp123", linkToSessionId)); + }); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test("should use the type of the scoped IdP, not the first active IdP (multi-IdP org)", async () => { + const { IdentityProviderType } = await import("@zitadel/proto/zitadel/settings/v2/login_settings_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:idp:id:idp-2"], + prompt: [], + loginHint: undefined, + }, + }); + + // Two active IdPs: the scope selects the SECOND one. Regression: the slug + // was previously derived from identityProviders[0].type. + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [ + { id: "idp-1", type: IdentityProviderType.GITHUB }, + { id: "idp-2", type: IdentityProviderType.AZURE_AD }, + ], + }); + + mockStartIdentityProviderFlow.mockResolvedValue({ + url: "https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?client_id=xyz", + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + expect(mockIdpTypeToSlug).toHaveBeenCalledWith(IdentityProviderType.AZURE_AD); + expect(mockIdpTypeToSlug).not.toHaveBeenCalledWith(IdentityProviderType.GITHUB); + expect(res.headers.get("location")).toBe("https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?client_id=xyz"); + }); + + test("should block unsafe IdP URLs with a 400 instead of redirecting or rendering a form", async () => { + const { IdentityProviderType } = await import("@zitadel/proto/zitadel/settings/v2/login_settings_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:idp:id:idp-1"], + prompt: [], + loginHint: undefined, + }, + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp-1", type: IdentityProviderType.SAML }], + }); + + mockStartIdentityProviderFlow.mockResolvedValue({ + url: "javascript:alert(1)", + fields: { SAMLRequest: "abc" }, + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("Unsafe redirect URI"); + }); + + test("should render the auto-submit form for a scoped SAML POST-binding IdP", async () => { + const { IdentityProviderType } = await import("@zitadel/proto/zitadel/settings/v2/login_settings_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:idp:id:idp-1"], + prompt: [], + loginHint: undefined, + }, + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp-1", type: IdentityProviderType.SAML }], + }); + + mockStartIdentityProviderFlow.mockResolvedValue({ + url: "https://adfs.example.com/adfs/ls", + fields: { SAMLRequest: "PHNhbWxwOkF1dGhuUmVxdWVzdD4=", RelayState: "relay-123" }, + }); + + const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + expect(res.headers.get("location")).toBeNull(); + expect(res.headers.get("content-type")).toContain("text/html"); + const html = await res.text(); + expect(html).toContain('action="https://adfs.example.com/adfs/ls"'); + expect(html).toContain('name="SAMLRequest"'); + }); + + test("should pass the login_hint of the auth request on to the scoped IdP", async () => { + const { IdentityProviderType } = await import("@zitadel/proto/zitadel/settings/v2/login_settings_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:idp:id:idp-1"], + prompt: [], + loginHint: "user@example.com", + }, + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp-1", type: IdentityProviderType.AZURE_AD }], + }); + + mockStartIdentityProviderFlow.mockResolvedValue({ + url: "https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?client_id=xyz", + }); + + await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + expect(mockStartIdentityProviderFlow).toHaveBeenCalledWith( + expect.objectContaining({ + urls: expect.objectContaining({ loginHint: "user@example.com" }), + }), + ); + }); + + test("should bind the scoped IdP flow to this browser with a flowFingerprint in the success URL", async () => { + const { IdentityProviderType } = await import("@zitadel/proto/zitadel/settings/v2/login_settings_pb"); + + mockGetAuthRequest.mockResolvedValue({ + authRequest: { + id: "abc123", + uiLocales: [], + scope: ["urn:zitadel:iam:org:idp:id:idp-1"], + prompt: [], + loginHint: undefined, + }, + }); + + mockGetActiveIdentityProviders.mockResolvedValue({ + identityProviders: [{ id: "idp-1", type: IdentityProviderType.AZURE_AD }], + }); + + mockStartIdentityProviderFlow.mockResolvedValue({ + url: "https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?client_id=xyz", + }); + + await handleOIDCFlowInitiation(makeBaseParams({ sessions: [] })); + + const successUrl = new URL(mockStartIdentityProviderFlow.mock.calls[0][0].urls.successUrl); + expect(successUrl.pathname).toBe("/idp/azure/process"); + expect(successUrl.searchParams.get("requestId")).toBe("oidc_abc123"); + expect(isIdpFlowProofValid(successUrl.searchParams.get("flowFingerprint") ?? undefined, "fp123")).toBe(true); + expect(isIdpFlowProofValid(successUrl.searchParams.get("flowFingerprint") ?? undefined, "other-fp")).toBe(false); + }); +}); diff --git a/auth/ui/v2/apps/login/src/lib/server/flow-initiation.ts b/auth/ui/v2/apps/login/src/lib/server/flow-initiation.ts new file mode 100644 index 0000000..35239dc --- /dev/null +++ b/auth/ui/v2/apps/login/src/lib/server/flow-initiation.ts @@ -0,0 +1,690 @@ +import "server-only"; + +import { addIdpFlowProof } from "@/lib/server/fingerprint"; + +import { isExternalUrl, isSafeRedirectUri } from "@/lib/client-utils"; +import { getValidLocaleFromUILocales } from "@/lib/server/auth-utils"; +import { getLanguageCookie, setLanguageCookie, type Cookie } from "@/lib/server/cookies"; + +import { sendLoginname } from "@/lib/actions/loginname"; +import { shouldUILocalesOverrideCookie } from "@/lib/i18n"; +import { idpTypeToSlug } from "@/lib/idp"; +import { buildCSP } from "@/lib/server/csp"; +import { createLogger } from "@/lib/server/logger"; +import { constructUrl } from "@/lib/server/service-url"; +import { findValidSession } from "@/lib/server/session"; +import { + createCallback, + createResponse, + getActiveIdentityProviders, + getAuthRequest, + getOrgsByDomain, + getSAMLRequest, + getSecuritySettings, + ServiceConfig, + startIdentityProviderFlow, +} from "@/lib/server/zitadel"; +import { create } from "@zitadel/client"; +import { Prompt } from "@zitadel/proto/zitadel/oidc/v2/authorization_pb"; +import { CreateCallbackRequestSchema, SessionSchema } from "@zitadel/proto/zitadel/oidc/v2/oidc_service_pb"; +import { CreateResponseRequestSchema } from "@zitadel/proto/zitadel/saml/v2/saml_service_pb"; +import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; +import { IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb"; +import { SecuritySettings } from "@zitadel/proto/zitadel/settings/v2/security_settings_pb"; +import escapeHtml from "escape-html"; +import { NextRequest, NextResponse } from "next/server"; + +const logger = createLogger("flow-initiation"); + +const ORG_SCOPE_REGEX = /urn:zitadel:iam:org:id:([0-9]+)/; +const ORG_DOMAIN_SCOPE_REGEX = /urn:zitadel:iam:org:domain:primary:(.+)/; +const IDP_SCOPE_REGEX = /urn:zitadel:iam:org:idp:id:(.+)/; + +function setCSPHeaders( + response: NextResponse, + serviceConfig: ServiceConfig, + securitySettings: SecuritySettings | undefined, +): void { + const iframeOrigins = + securitySettings?.embeddedIframe?.enabled && securitySettings.embeddedIframe.allowedOrigins.length > 0 + ? securitySettings.embeddedIframe.allowedOrigins + : undefined; + + response.headers.set("Content-Security-Policy", buildCSP({ serviceUrl: serviceConfig.baseUrl, iframeOrigins })); + + if (!iframeOrigins) { + response.headers.set("X-Frame-Options", "deny"); + } +} + +/** + * Renders a minimal HTML page that immediately POSTs the given fields to + * `url`, with a