commit fc1f7259c5c3c0d8f8c8f7cfcdeb8280d761484c Author: Ole-Morten Duesund Date: Sun Mar 29 15:55:22 2026 +0200 feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation Go backend with server-rendered HTML/HTMX frontend, SQLite database, and filesystem image storage. Self-hostable single-binary architecture. Phase 1 — Authentication & project foundation: - Argon2id password hashing with timing-attack prevention - Session management with cookie-based auth and periodic cleanup - Login, signup (open/requests/closed modes), logout, forced password reset - CSRF double-submit cookie pattern with HTMX auto-inclusion - Proxy-aware real IP extraction (WireGuard/Tailscale support) - Configurable base path for subdomain and subpath deployment - Rate limiting on auth endpoints with background cleanup - Security headers (CSP, X-Frame-Options, Referrer-Policy) - Structured logging with slog, graceful shutdown - Pico CSS + HTMX vendored and embedded via go:embed Phase 2 — Faves CRUD with tags and images: - Full CRUD for favorites with ownership checks - Image upload with EXIF stripping, resize to 1920px, UUID filenames - Tag system with HTMX autocomplete (prefix search, popularity-sorted) - Privacy controls (public/private per fave, user-configurable default) - Tag browsing, pagination, batch tag loading (avoids N+1) - OpenGraph meta tags on public fave detail pages Includes code quality pass: extracted shared helpers, fixed signup request persistence bug, plugged rate limiter memory leak, removed dead code, and logged previously-swallowed errors. Co-Authored-By: Claude Opus 4.6 (1M context) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d10244a --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Build artifacts +/favoritter +/dist/ + +# Data (database and uploads) +/data/ + +# Go +*.exe +*.test +*.out +/vendor/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Environment +.env +*.env.local diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/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 +. diff --git a/cmd/favoritter/main.go b/cmd/favoritter/main.go new file mode 100644 index 0000000..c21e9cb --- /dev/null +++ b/cmd/favoritter/main.go @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "kode.naiv.no/olemd/favoritter/internal/config" + "kode.naiv.no/olemd/favoritter/internal/database" + "kode.naiv.no/olemd/favoritter/internal/handler" + "kode.naiv.no/olemd/favoritter/internal/middleware" + "kode.naiv.no/olemd/favoritter/internal/render" + "kode.naiv.no/olemd/favoritter/internal/store" +) + +var ( + version = "dev" + buildDate = "unknown" +) + +func main() { + // Handle -healthcheck flag for container health checks. + if len(os.Args) > 1 && os.Args[1] == "-healthcheck" { + runHealthCheck() + return + } + + // Handle -version flag. + if len(os.Args) > 1 && os.Args[1] == "-version" { + fmt.Printf("favoritter %s (built %s)\n", version, buildDate) + return + } + + cfg := config.Load() + + // Set up structured logging. + logLevel := slog.LevelInfo + if cfg.DevMode { + logLevel = slog.LevelDebug + } + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel})) + slog.SetDefault(logger) + + slog.Info("starting favoritter", "version", version, "build_date", buildDate) + + // Open database and run migrations. + db, err := database.Open(cfg.DBPath) + if err != nil { + slog.Error("failed to open database", "error", err) + os.Exit(1) + } + defer db.Close() + + if err := database.Migrate(db); err != nil { + slog.Error("failed to run migrations", "error", err) + os.Exit(1) + } + + // Initialize stores. + users := store.NewUserStore(db) + sessions := store.NewSessionStore(db) + settings := store.NewSettingsStore(db) + faves := store.NewFaveStore(db) + tags := store.NewTagStore(db) + signupRequests := store.NewSignupRequestStore(db) + + sessions.SetLifetime(cfg.SessionLifetime) + + // Ensure initial admin user exists. + if err := users.EnsureAdmin(cfg.AdminUsername, cfg.AdminPassword); err != nil { + slog.Error("failed to ensure admin user", "error", err) + os.Exit(1) + } + + // Initialize template renderer. + renderer, err := render.New(cfg) + if err != nil { + slog.Error("failed to initialize templates", "error", err) + os.Exit(1) + } + + // Configure Argon2 parameters from config. + store.Argon2Memory = cfg.Argon2Memory + store.Argon2Time = cfg.Argon2Time + store.Argon2Parallelism = cfg.Argon2Parallelism + + // Build the handler with all dependencies. + h := handler.New(handler.Deps{ + Config: cfg, + Users: users, + Sessions: sessions, + Settings: settings, + Faves: faves, + Tags: tags, + SignupRequests: signupRequests, + Renderer: renderer, + }) + + // Build the middleware chain. + mux := h.Routes() + chain := middleware.Chain( + mux, + middleware.Recovery, + middleware.SecurityHeaders, + middleware.BasePath(cfg.BasePath), + middleware.RealIP(cfg.TrustedProxies), + middleware.RequestLogger, + middleware.SessionLoader(sessions, users), + middleware.CSRFProtection(cfg), + ) + + srv := &http.Server{ + Addr: cfg.Listen, + Handler: chain, + ReadTimeout: 15 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 60 * time.Second, + } + + // Start background cleanup goroutines. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go sessions.CleanupLoop(ctx, 1*time.Hour) + go h.RateLimiterCleanupLoop(ctx, 5*time.Minute) + + // Start the server in a goroutine. + errCh := make(chan error, 1) + go func() { + slog.Info("listening", "addr", cfg.Listen, "base_path", cfg.BasePath) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- err + } + }() + + // Wait for interrupt signal or server error. + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + + select { + case sig := <-quit: + slog.Info("shutting down", "signal", sig) + case err := <-errCh: + slog.Error("server error", "error", err) + } + + // Graceful shutdown with 10-second timeout. + cancel() + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + slog.Error("shutdown error", "error", err) + } + + slog.Info("stopped") +} + +// runHealthCheck performs a health check by hitting the local health endpoint. +// It reads the configured listen address to determine the correct port. +func runHealthCheck() { + cfg := config.Load() + addr := cfg.Listen + // If addr is just ":port", use localhost. + if len(addr) > 0 && addr[0] == ':' { + addr = "127.0.0.1" + addr + } + resp, err := http.Get("http://" + addr + cfg.BasePath + "/health") + if err != nil { + os.Exit(1) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + os.Exit(1) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8b04c00 --- /dev/null +++ b/go.mod @@ -0,0 +1,20 @@ +module kode.naiv.no/olemd/favoritter + +go 1.26.1 + +require ( + github.com/google/uuid v1.6.0 + golang.org/x/crypto v0.49.0 + modernc.org/sqlite v1.48.0 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.42.0 // indirect + modernc.org/libc v1.70.0 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..22a6f85 --- /dev/null +++ b/go.sum @@ -0,0 +1,53 @@ +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +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/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= +golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis= +modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= +modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw= +modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo= +modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw= +modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= +modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.48.0 h1:ElZyLop3Q2mHYk5IFPPXADejZrlHu7APbpB0sF78bq4= +modernc.org/sqlite v1.48.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..bc85d59 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package config loads application configuration from environment variables. +package config + +import ( + "log/slog" + "net" + "net/url" + "os" + "strconv" + "strings" + "time" +) + +// Config holds all application configuration. +type Config struct { + // Database + DBPath string + + // Server + Listen string + BasePath string + ExternalURL string + TrustedProxies []*net.IPNet + + // Uploads + UploadDir string + MaxUploadSize int64 + + // Security + SessionLifetime time.Duration + Argon2Memory uint32 + Argon2Time uint32 + Argon2Parallelism uint8 + RateLimit int + + // Admin + AdminUsername string + AdminPassword string + + // Site + SiteName string + DevMode bool +} + +// Load reads configuration from environment variables with sensible defaults. +func Load() *Config { + cfg := &Config{ + DBPath: envOr("FAVORITTER_DB_PATH", "./data/favoritter.db"), + Listen: envOr("FAVORITTER_LISTEN", ":8080"), + BasePath: envOr("FAVORITTER_BASE_PATH", "/"), + ExternalURL: os.Getenv("FAVORITTER_EXTERNAL_URL"), + UploadDir: envOr("FAVORITTER_UPLOAD_DIR", "./data/uploads"), + MaxUploadSize: envInt64("FAVORITTER_MAX_UPLOAD_SIZE", 10<<20), // 10MB + SessionLifetime: envDuration("FAVORITTER_SESSION_LIFETIME", 720*time.Hour), + Argon2Memory: uint32(envInt("FAVORITTER_ARGON2_MEMORY", 65536)), + Argon2Time: uint32(envInt("FAVORITTER_ARGON2_TIME", 3)), + Argon2Parallelism: uint8(envInt("FAVORITTER_ARGON2_PARALLELISM", 2)), + RateLimit: envInt("FAVORITTER_RATE_LIMIT", 60), + AdminUsername: os.Getenv("FAVORITTER_ADMIN_USERNAME"), + AdminPassword: os.Getenv("FAVORITTER_ADMIN_PASSWORD"), + SiteName: envOr("FAVORITTER_SITE_NAME", "Favoritter"), + DevMode: envBool("FAVORITTER_DEV_MODE", false), + } + + // Normalize base path: ensure it starts with / and doesn't end with /. + cfg.BasePath = normalizePath(cfg.BasePath) + + // Normalize external URL: strip trailing slash. + cfg.ExternalURL = strings.TrimRight(cfg.ExternalURL, "/") + + // Parse trusted proxies. + cfg.TrustedProxies = parseCIDRs(envOr("FAVORITTER_TRUSTED_PROXIES", "127.0.0.1")) + + return cfg +} + +// BaseURL returns the external base URL for generating absolute URLs. +// If EXTERNAL_URL is set, it's used directly. Otherwise, falls back to +// constructing from the request (caller should pass the Host header). +func (c *Config) BaseURL(requestHost string) string { + if c.ExternalURL != "" { + return c.ExternalURL + } + // Fallback: construct from request host. + // Assume HTTPS unless we know otherwise. + return "https://" + requestHost + c.BasePath +} + +// IsExternalURLConfigured returns true if an explicit external URL was set. +func (c *Config) IsExternalURLConfigured() bool { + return c.ExternalURL != "" +} + +// ExternalHostname returns the hostname from the external URL, or empty string. +func (c *Config) ExternalHostname() string { + if c.ExternalURL == "" { + return "" + } + u, err := url.Parse(c.ExternalURL) + if err != nil { + return "" + } + return u.Hostname() +} + +func normalizePath(p string) string { + if p == "" || p == "/" { + return "" + } + if !strings.HasPrefix(p, "/") { + p = "/" + p + } + return strings.TrimRight(p, "/") +} + +func parseCIDRs(s string) []*net.IPNet { + var nets []*net.IPNet + for _, part := range strings.Split(s, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + // If no CIDR notation, add /32 for IPv4 or /128 for IPv6. + if !strings.Contains(part, "/") { + ip := net.ParseIP(part) + if ip == nil { + slog.Warn("invalid trusted proxy IP, skipping", "ip", part) + continue + } + if ip.To4() != nil { + part += "/32" + } else { + part += "/128" + } + } + _, ipNet, err := net.ParseCIDR(part) + if err != nil { + slog.Warn("invalid trusted proxy CIDR, skipping", "cidr", part, "error", err) + continue + } + nets = append(nets, ipNet) + } + return nets +} + +func envOr(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} + +func envInt(key string, fallback int) int { + v := os.Getenv(key) + if v == "" { + return fallback + } + n, err := strconv.Atoi(v) + if err != nil { + slog.Warn("invalid integer env var, using default", "key", key, "value", v, "default", fallback) + return fallback + } + return n +} + +func envInt64(key string, fallback int64) int64 { + v := os.Getenv(key) + if v == "" { + return fallback + } + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + slog.Warn("invalid int64 env var, using default", "key", key, "value", v, "default", fallback) + return fallback + } + return n +} + +func envDuration(key string, fallback time.Duration) time.Duration { + v := os.Getenv(key) + if v == "" { + return fallback + } + d, err := time.ParseDuration(v) + if err != nil { + slog.Warn("invalid duration env var, using default", "key", key, "value", v, "default", fallback) + return fallback + } + return d +} + +func envBool(key string, fallback bool) bool { + v := os.Getenv(key) + if v == "" { + return fallback + } + b, err := strconv.ParseBool(v) + if err != nil { + slog.Warn("invalid bool env var, using default", "key", key, "value", v, "default", fallback) + return fallback + } + return b +} diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..b39eef4 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package database manages the SQLite connection, PRAGMAs, and schema migrations. +package database + +import ( + "database/sql" + "embed" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strings" + + _ "modernc.org/sqlite" +) + +//go:embed migrations/*.sql +var migrationsFS embed.FS + +// Open creates a new SQLite database connection with recommended PRAGMAs +// for WAL mode, foreign keys, and performance tuning. +func Open(dbPath string) (*sql.DB, error) { + // Ensure the directory for the database file exists. + dir := filepath.Dir(dbPath) + if err := os.MkdirAll(dir, 0750); err != nil { + return nil, fmt.Errorf("create db directory: %w", err) + } + + db, err := sql.Open("sqlite", dbPath) + if err != nil { + return nil, fmt.Errorf("open sqlite: %w", err) + } + + // Apply recommended PRAGMAs. These must be set per-connection, and since + // database/sql may open multiple connections, we use ConnInitHook via DSN + // parameters where possible. However, journal_mode persists at the db level. + pragmas := []string{ + "PRAGMA journal_mode = WAL", + "PRAGMA busy_timeout = 5000", + "PRAGMA synchronous = NORMAL", + "PRAGMA foreign_keys = ON", + "PRAGMA cache_size = -20000", + } + for _, p := range pragmas { + if _, err := db.Exec(p); err != nil { + db.Close() + return nil, fmt.Errorf("set pragma %q: %w", p, err) + } + } + + // SQLite works best with a single writer connection. + db.SetMaxOpenConns(1) + + slog.Info("database opened", "path", dbPath) + return db, nil +} + +// Migrate runs all pending SQL migrations in order. Migrations are embedded +// SQL files named with a numeric prefix (e.g. 001_initial.sql). Each migration +// runs within a transaction. +func Migrate(db *sql.DB) error { + // Create the migrations tracking table if it doesn't exist. + _, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) + )`) + if err != nil { + return fmt.Errorf("create schema_migrations table: %w", err) + } + + // Read all migration files. + entries, err := migrationsFS.ReadDir("migrations") + if err != nil { + return fmt.Errorf("read migrations dir: %w", err) + } + + // Sort by filename to ensure correct order. + sort.Slice(entries, func(i, j int) bool { + return entries[i].Name() < entries[j].Name() + }) + + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") { + continue + } + + name := entry.Name() + + // Check if this migration has already been applied. + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", name).Scan(&count); err != nil { + return fmt.Errorf("check migration %s: %w", name, err) + } + if count > 0 { + continue + } + + // Read and execute the migration in a transaction. + content, err := migrationsFS.ReadFile("migrations/" + name) + if err != nil { + return fmt.Errorf("read migration %s: %w", name, err) + } + + tx, err := db.Begin() + if err != nil { + return fmt.Errorf("begin tx for %s: %w", name, err) + } + + if _, err := tx.Exec(string(content)); err != nil { + tx.Rollback() + return fmt.Errorf("execute migration %s: %w", name, err) + } + + if _, err := tx.Exec("INSERT INTO schema_migrations (version) VALUES (?)", name); err != nil { + tx.Rollback() + return fmt.Errorf("record migration %s: %w", name, err) + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit migration %s: %w", name, err) + } + + slog.Info("applied migration", "version", name) + } + + return nil +} diff --git a/internal/database/migrations/001_initial.sql b/internal/database/migrations/001_initial.sql new file mode 100644 index 0000000..f45a58a --- /dev/null +++ b/internal/database/migrations/001_initial.sql @@ -0,0 +1,72 @@ +-- Initial schema for Favoritter. +-- Creates core tables: users, sessions, signup_requests, faves, tags, fave_tags, site_settings. + +CREATE TABLE users ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + display_name TEXT NOT NULL DEFAULT '', + bio TEXT NOT NULL DEFAULT '', + avatar_path TEXT NOT NULL DEFAULT '', + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')), + profile_visibility TEXT NOT NULL DEFAULT 'public' CHECK (profile_visibility IN ('public', 'limited')), + default_fave_privacy TEXT NOT NULL DEFAULT 'public' CHECK (default_fave_privacy IN ('public', 'private')), + must_reset_password INTEGER NOT NULL DEFAULT 0, + disabled INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) +); + +CREATE TABLE sessions ( + token TEXT PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) +); +CREATE INDEX idx_sessions_user_id ON sessions(user_id); +CREATE INDEX idx_sessions_expires ON sessions(expires_at); + +CREATE TABLE signup_requests ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + reviewed_at TEXT, + reviewed_by INTEGER REFERENCES users(id) +); + +CREATE TABLE faves ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + description TEXT NOT NULL, + url TEXT NOT NULL DEFAULT '', + image_path TEXT NOT NULL DEFAULT '', + privacy TEXT NOT NULL DEFAULT 'public' CHECK (privacy IN ('public', 'private')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) +); +CREATE INDEX idx_faves_user_id ON faves(user_id); +CREATE INDEX idx_faves_privacy ON faves(privacy); +CREATE INDEX idx_faves_created ON faves(created_at); + +CREATE TABLE tags ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE COLLATE NOCASE +); + +CREATE TABLE fave_tags ( + fave_id INTEGER NOT NULL REFERENCES faves(id) ON DELETE CASCADE, + tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE, + PRIMARY KEY (fave_id, tag_id) +); +CREATE INDEX idx_fave_tags_tag_id ON fave_tags(tag_id); + +CREATE TABLE site_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + site_name TEXT NOT NULL DEFAULT 'Favoritter', + site_description TEXT NOT NULL DEFAULT '', + signup_mode TEXT NOT NULL DEFAULT 'open' CHECK (signup_mode IN ('open', 'requests', 'closed')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) +); +INSERT INTO site_settings (id) VALUES (1); diff --git a/internal/handler/auth.go b/internal/handler/auth.go new file mode 100644 index 0000000..3af28b2 --- /dev/null +++ b/internal/handler/auth.go @@ -0,0 +1,299 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package handler + +import ( + "errors" + "log/slog" + "net/http" + "regexp" + "strings" + + "kode.naiv.no/olemd/favoritter/internal/middleware" + "kode.naiv.no/olemd/favoritter/internal/render" + "kode.naiv.no/olemd/favoritter/internal/store" +) + +var usernameRegexp = regexp.MustCompile(`^[a-zA-Z0-9_-]{2,30}$`) + +func (h *Handler) handleLoginGet(w http.ResponseWriter, r *http.Request) { + // If already logged in, redirect to home. + if middleware.UserFromContext(r.Context()) != nil { + http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther) + return + } + + h.deps.Renderer.Page(w, r, "login", render.PageData{ + Title: "Logg inn", + }) +} + +func (h *Handler) handleLoginPost(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + h.flash(w, r, "login", "Ugyldig forespørsel.", "error", nil) + return + } + + username := strings.TrimSpace(r.FormValue("username")) + password := r.FormValue("password") + + user, err := h.deps.Users.Authenticate(username, password) + if err != nil { + if errors.Is(err, store.ErrInvalidCredentials) || errors.Is(err, store.ErrUserDisabled) { + h.flash(w, r, "login", "Feil brukernavn eller passord.", "error", nil) + return + } + slog.Error("login authentication error", "error", err) + h.flash(w, r, "login", "Noe gikk galt. Prøv igjen.", "error", nil) + return + } + + token, err := h.deps.Sessions.Create(user.ID) + if err != nil { + slog.Error("session create error", "error", err) + h.flash(w, r, "login", "Noe gikk galt. Prøv igjen.", "error", nil) + return + } + + h.setSessionCookie(w, r, token) + + // If user must reset password, redirect there. + if user.MustResetPassword { + http.Redirect(w, r, h.deps.Config.BasePath+"/reset-password", http.StatusSeeOther) + return + } + + http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther) +} + +func (h *Handler) handleSignupGet(w http.ResponseWriter, r *http.Request) { + if middleware.UserFromContext(r.Context()) != nil { + http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther) + return + } + + settings, err := h.deps.Settings.Get() + if err != nil { + slog.Error("get settings error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + h.deps.Renderer.Page(w, r, "signup", render.PageData{ + Title: "Registrer", + Data: map[string]string{"Mode": settings.SignupMode}, + }) +} + +func (h *Handler) handleSignupPost(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + h.flash(w, r, "signup", "Ugyldig forespørsel.", "error", signupData("open")) + return + } + + settings, err := h.deps.Settings.Get() + if err != nil { + slog.Error("get settings error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + if settings.SignupClosed() { + h.flash(w, r, "signup", "Registrering er stengt.", "error", signupData("closed")) + return + } + + username := strings.TrimSpace(r.FormValue("username")) + password := r.FormValue("password") + passwordConfirm := r.FormValue("password_confirm") + + // Validate input. + if !usernameRegexp.MatchString(username) { + h.flash(w, r, "signup", "Ugyldig brukernavn. Bruk 2-30 tegn: bokstaver, tall, bindestrek, understrek.", "error", signupData(settings.SignupMode)) + return + } + + if len(password) < 8 { + h.flash(w, r, "signup", "Passordet må være minst 8 tegn.", "error", signupData(settings.SignupMode)) + return + } + + if password != passwordConfirm { + h.flash(w, r, "signup", "Passordene er ikke like.", "error", signupData(settings.SignupMode)) + return + } + + if settings.SignupRequests() { + // Create a signup request for admin approval. + err := h.createSignupRequest(username, password) + if err != nil { + if errors.Is(err, store.ErrUserExists) { + h.flash(w, r, "signup", "Brukernavnet er allerede i bruk.", "error", signupData(settings.SignupMode)) + return + } + slog.Error("signup request error", "error", err) + h.flash(w, r, "signup", "Noe gikk galt. Prøv igjen.", "error", signupData(settings.SignupMode)) + return + } + h.flash(w, r, "login", "Forespørselen din er sendt. En administrator vil gjennomgå den.", "info", nil) + return + } + + // Open signup — create user directly. + user, err := h.deps.Users.Create(username, password, "user") + if err != nil { + if errors.Is(err, store.ErrUserExists) { + h.flash(w, r, "signup", "Brukernavnet er allerede i bruk.", "error", signupData(settings.SignupMode)) + return + } + slog.Error("user create error", "error", err) + h.flash(w, r, "signup", "Noe gikk galt. Prøv igjen.", "error", signupData(settings.SignupMode)) + return + } + + // Auto-login after signup. + token, err := h.deps.Sessions.Create(user.ID) + if err != nil { + slog.Error("session create error", "error", err) + http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther) + return + } + + h.setSessionCookie(w, r, token) + http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther) +} + +func (h *Handler) handleLogout(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie(middleware.SessionCookieName) + if err == nil { + if delErr := h.deps.Sessions.Delete(cookie.Value); delErr != nil { + slog.Error("session delete error", "error", delErr) + } + } + + middleware.ClearSessionCookie(w) + + http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther) +} + +func (h *Handler) handleResetPasswordGet(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + if user == nil { + http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther) + return + } + + if !user.MustResetPassword { + http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther) + return + } + + h.deps.Renderer.Page(w, r, "reset_password", render.PageData{ + Title: "Endre passord", + }) +} + +func (h *Handler) handleResetPasswordPost(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + if user == nil { + http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther) + return + } + + if err := r.ParseForm(); err != nil { + h.flash(w, r, "reset_password", "Ugyldig forespørsel.", "error", nil) + return + } + + password := r.FormValue("password") + passwordConfirm := r.FormValue("password_confirm") + + if len(password) < 8 { + h.flash(w, r, "reset_password", "Passordet må være minst 8 tegn.", "error", nil) + return + } + + if password != passwordConfirm { + h.flash(w, r, "reset_password", "Passordene er ikke like.", "error", nil) + return + } + + if err := h.deps.Users.UpdatePassword(user.ID, password); err != nil { + slog.Error("update password error", "error", err) + h.flash(w, r, "reset_password", "Noe gikk galt. Prøv igjen.", "error", nil) + return + } + + if delErr := h.deps.Sessions.DeleteAllForUser(user.ID); delErr != nil { + slog.Error("session cleanup error", "error", delErr) + } + + // Create a fresh session. + token, err := h.deps.Sessions.Create(user.ID) + if err != nil { + slog.Error("session create error", "error", err) + http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther) + return + } + + h.setSessionCookie(w, r, token) + http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther) +} + +func (h *Handler) handleHome(w http.ResponseWriter, r *http.Request) { + h.deps.Renderer.Page(w, r, "home", render.PageData{}) +} + +func (h *Handler) handleHealth(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"status":"ok"}`)) +} + +// setSessionCookie sets the session cookie with appropriate flags for +// both local and remote proxy deployments. +func (h *Handler) setSessionCookie(w http.ResponseWriter, r *http.Request, token string) { + cookie := &http.Cookie{ + Name: "session", + Value: token, + Path: "/", + MaxAge: int(h.deps.Config.SessionLifetime.Seconds()), + HttpOnly: true, + Secure: middleware.IsSecureRequest(r, h.deps.Config), + SameSite: http.SameSiteLaxMode, + } + + // Set domain from external URL if configured. + if hostname := h.deps.Config.ExternalHostname(); hostname != "" { + cookie.Domain = hostname + } + + http.SetCookie(w, cookie) +} + +// flash renders a page with a flash message. +func (h *Handler) flash(w http.ResponseWriter, r *http.Request, page, message, flashType string, data any) { + h.deps.Renderer.Page(w, r, page, render.PageData{ + Flash: message, + FlashType: flashType, + Data: data, + }) +} + +func signupData(mode string) map[string]string { + return map[string]string{"Mode": mode} +} + +func (h *Handler) createSignupRequest(username, password string) error { + // Check if username is already taken by an existing user. + _, err := h.deps.Users.GetByUsername(username) + if err == nil { + return store.ErrUserExists + } + + err = h.deps.SignupRequests.Create(username, password) + if errors.Is(err, store.ErrSignupRequestExists) { + return store.ErrUserExists + } + return err +} diff --git a/internal/handler/fave.go b/internal/handler/fave.go new file mode 100644 index 0000000..a739370 --- /dev/null +++ b/internal/handler/fave.go @@ -0,0 +1,416 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package handler + +import ( + "errors" + "log/slog" + "net/http" + "strconv" + "strings" + + "kode.naiv.no/olemd/favoritter/internal/image" + "kode.naiv.no/olemd/favoritter/internal/middleware" + "kode.naiv.no/olemd/favoritter/internal/render" + "kode.naiv.no/olemd/favoritter/internal/store" +) + +const defaultPageSize = 24 + +// handleFaveList shows the current user's faves. +func (h *Handler) handleFaveList(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + page := queryInt(r, "page", 1) + offset := (page - 1) * defaultPageSize + + faves, total, err := h.deps.Faves.ListByUser(user.ID, defaultPageSize, offset) + if err != nil { + slog.Error("list faves error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + // Load tags for each fave. + if err := h.deps.Faves.LoadTags(faves); err != nil { + slog.Error("load tags error", "error", err) + } + + totalPages := (total + defaultPageSize - 1) / defaultPageSize + + h.deps.Renderer.Page(w, r, "fave_list", render.PageData{ + Title: "Mine favoritter", + Data: map[string]any{ + "Faves": faves, + "Page": page, + "TotalPages": totalPages, + "Total": total, + }, + }) +} + +// handleFaveNew shows the form for creating a new fave. +func (h *Handler) handleFaveNew(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + + h.deps.Renderer.Page(w, r, "fave_form", render.PageData{ + Title: "Ny favoritt", + Data: map[string]any{ + "IsNew": true, + "DefaultPrivacy": user.DefaultFavePrivacy, + }, + }) +} + +// handleFaveCreate processes the form for creating a new fave. +func (h *Handler) handleFaveCreate(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + + if err := r.ParseMultipartForm(h.deps.Config.MaxUploadSize); err != nil { + h.flash(w, r, "fave_form", "Filen er for stor.", "error", map[string]any{"IsNew": true}) + return + } + + description := strings.TrimSpace(r.FormValue("description")) + url := strings.TrimSpace(r.FormValue("url")) + privacy := r.FormValue("privacy") + tagStr := r.FormValue("tags") + + if description == "" { + h.flash(w, r, "fave_form", "Beskrivelse er påkrevd.", "error", map[string]any{ + "IsNew": true, "Description": description, "URL": url, "Tags": tagStr, "Privacy": privacy, + }) + return + } + + if privacy != "public" && privacy != "private" { + privacy = user.DefaultFavePrivacy + } + + // Handle image upload. + var imagePath string + file, header, err := r.FormFile("image") + if err == nil { + defer file.Close() + result, err := image.Process(file, header, h.deps.Config.UploadDir) + if err != nil { + slog.Error("image process error", "error", err) + h.flash(w, r, "fave_form", "Kunne ikke behandle bildet. Sjekk at filen er et gyldig bilde (JPEG, PNG, GIF eller WebP).", "error", map[string]any{ + "IsNew": true, "Description": description, "URL": url, "Tags": tagStr, "Privacy": privacy, + }) + return + } + imagePath = result.Filename + } + + // Create the fave. + fave, err := h.deps.Faves.Create(user.ID, description, url, imagePath, privacy) + if err != nil { + slog.Error("create fave error", "error", err) + h.flash(w, r, "fave_form", "Noe gikk galt. Prøv igjen.", "error", map[string]any{"IsNew": true}) + return + } + + // Set tags. + if tagStr != "" { + tags := parseTags(tagStr) + if err := h.deps.Tags.SetFaveTags(fave.ID, tags); err != nil { + slog.Error("set tags error", "error", err) + } + } + + http.Redirect(w, r, h.deps.Config.BasePath+"/faves/"+strconv.FormatInt(fave.ID, 10), http.StatusSeeOther) +} + +// handleFaveDetail shows a single fave. +func (h *Handler) handleFaveDetail(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + fave, err := h.deps.Faves.GetByID(id) + if err != nil { + if errors.Is(err, store.ErrFaveNotFound) { + http.NotFound(w, r) + return + } + slog.Error("get fave error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + // Check access: private faves are only visible to their owner. + user := middleware.UserFromContext(r.Context()) + if fave.Privacy == "private" && (user == nil || user.ID != fave.UserID) { + http.NotFound(w, r) + return + } + + // Load tags. + tags, err := h.deps.Tags.ForFave(fave.ID) + if err != nil { + slog.Error("load tags error", "error", err) + } + fave.Tags = tags + + h.deps.Renderer.Page(w, r, "fave_detail", render.PageData{ + Title: fave.Description, + Data: map[string]any{ + "Fave": fave, + "IsOwner": user != nil && user.ID == fave.UserID, + }, + }) +} + +// handleFaveEdit shows the edit form for a fave. +func (h *Handler) handleFaveEdit(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + fave, err := h.deps.Faves.GetByID(id) + if err != nil { + if errors.Is(err, store.ErrFaveNotFound) { + http.NotFound(w, r) + return + } + slog.Error("get fave error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + // Only the owner can edit. + if user.ID != fave.UserID { + http.Error(w, "Forbidden", http.StatusForbidden) + return + } + + tags, _ := h.deps.Tags.ForFave(fave.ID) + fave.Tags = tags + + tagNames := make([]string, len(tags)) + for i, t := range tags { + tagNames[i] = t.Name + } + + h.deps.Renderer.Page(w, r, "fave_form", render.PageData{ + Title: "Rediger favoritt", + Data: map[string]any{ + "IsNew": false, + "Fave": fave, + "Description": fave.Description, + "URL": fave.URL, + "Privacy": fave.Privacy, + "Tags": strings.Join(tagNames, ", "), + }, + }) +} + +// handleFaveUpdate processes the edit form. +func (h *Handler) handleFaveUpdate(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + fave, err := h.deps.Faves.GetByID(id) + if err != nil { + if errors.Is(err, store.ErrFaveNotFound) { + http.NotFound(w, r) + return + } + slog.Error("get fave error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + if user.ID != fave.UserID { + http.Error(w, "Forbidden", http.StatusForbidden) + return + } + + if err := r.ParseMultipartForm(h.deps.Config.MaxUploadSize); err != nil { + h.flash(w, r, "fave_form", "Filen er for stor.", "error", map[string]any{"IsNew": false, "Fave": fave}) + return + } + + description := strings.TrimSpace(r.FormValue("description")) + url := strings.TrimSpace(r.FormValue("url")) + privacy := r.FormValue("privacy") + tagStr := r.FormValue("tags") + + if description == "" { + h.flash(w, r, "fave_form", "Beskrivelse er påkrevd.", "error", map[string]any{"IsNew": false, "Fave": fave}) + return + } + + if privacy != "public" && privacy != "private" { + privacy = fave.Privacy + } + + // Handle image upload (optional on edit). + imagePath := fave.ImagePath + file, header, err := r.FormFile("image") + if err == nil { + defer file.Close() + result, err := image.Process(file, header, h.deps.Config.UploadDir) + if err != nil { + slog.Error("image process error", "error", err) + h.flash(w, r, "fave_form", "Kunne ikke behandle bildet. Sjekk at filen er et gyldig bilde (JPEG, PNG, GIF eller WebP).", "error", map[string]any{"IsNew": false, "Fave": fave}) + return + } + if fave.ImagePath != "" { + if delErr := image.Delete(h.deps.Config.UploadDir, fave.ImagePath); delErr != nil { + slog.Error("image delete error", "error", delErr) + } + } + imagePath = result.Filename + } + + // Check if user wants to remove the existing image. + if r.FormValue("remove_image") == "1" && imagePath != "" { + if delErr := image.Delete(h.deps.Config.UploadDir, imagePath); delErr != nil { + slog.Error("image delete error", "error", delErr) + } + imagePath = "" + } + + if err := h.deps.Faves.Update(id, description, url, imagePath, privacy); err != nil { + slog.Error("update fave error", "error", err) + h.flash(w, r, "fave_form", "Noe gikk galt. Prøv igjen.", "error", map[string]any{"IsNew": false, "Fave": fave}) + return + } + + // Update tags. + tags := parseTags(tagStr) + if err := h.deps.Tags.SetFaveTags(id, tags); err != nil { + slog.Error("set tags error", "error", err) + } + + http.Redirect(w, r, h.deps.Config.BasePath+"/faves/"+strconv.FormatInt(id, 10), http.StatusSeeOther) +} + +// handleFaveDelete deletes a fave. +func (h *Handler) handleFaveDelete(w http.ResponseWriter, r *http.Request) { + user := middleware.UserFromContext(r.Context()) + + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + fave, err := h.deps.Faves.GetByID(id) + if err != nil { + if errors.Is(err, store.ErrFaveNotFound) { + http.NotFound(w, r) + return + } + slog.Error("get fave error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + if user.ID != fave.UserID { + http.Error(w, "Forbidden", http.StatusForbidden) + return + } + + if fave.ImagePath != "" { + if delErr := image.Delete(h.deps.Config.UploadDir, fave.ImagePath); delErr != nil { + slog.Error("image delete error", "error", delErr) + } + } + + if err := h.deps.Faves.Delete(id); err != nil { + slog.Error("delete fave error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + // If this was an HTMX request, return empty (the element is removed). + if r.Header.Get("HX-Request") == "true" { + w.WriteHeader(http.StatusOK) + return + } + + http.Redirect(w, r, h.deps.Config.BasePath+"/faves", http.StatusSeeOther) +} + +// handleTagSearch handles tag autocomplete HTMX requests. +func (h *Handler) handleTagSearch(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query().Get("q") + tags, err := h.deps.Tags.Search(q, 10) + if err != nil { + slog.Error("tag search error", "error", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := h.deps.Renderer.Partial(w, "tag_suggestions", tags); err != nil { + slog.Error("render tag suggestions error", "error", err) + } +} + +// handleTagBrowse shows all public faves with a given tag. +func (h *Handler) handleTagBrowse(w http.ResponseWriter, r *http.Request) { + tagName := r.PathValue("name") + page := queryInt(r, "page", 1) + offset := (page - 1) * defaultPageSize + + faves, total, err := h.deps.Faves.ListByTag(tagName, defaultPageSize, offset) + if err != nil { + slog.Error("list by tag error", "error", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + + if err := h.deps.Faves.LoadTags(faves); err != nil { + slog.Error("load tags error", "error", err) + } + + totalPages := (total + defaultPageSize - 1) / defaultPageSize + + h.deps.Renderer.Page(w, r, "tag_browse", render.PageData{ + Title: "Merkelapp: " + tagName, + Data: map[string]any{ + "TagName": tagName, + "Faves": faves, + "Page": page, + "TotalPages": totalPages, + "Total": total, + }, + }) +} + +// parseTags splits a comma-separated tag string into individual tag names. +func parseTags(s string) []string { + parts := strings.Split(s, ",") + var tags []string + for _, p := range parts { + p = strings.TrimSpace(p) + if p != "" { + tags = append(tags, p) + } + } + return tags +} + +// queryInt parses an integer query parameter with a default. +func queryInt(r *http.Request, key string, fallback int) int { + v := r.URL.Query().Get(key) + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + return fallback + } + return n +} diff --git a/internal/handler/handler.go b/internal/handler/handler.go new file mode 100644 index 0000000..d74680d --- /dev/null +++ b/internal/handler/handler.go @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package handler contains HTTP handlers for all web and API routes. +package handler + +import ( + "context" + "io/fs" + "net/http" + "time" + + "kode.naiv.no/olemd/favoritter/internal/config" + "kode.naiv.no/olemd/favoritter/internal/middleware" + "kode.naiv.no/olemd/favoritter/internal/render" + "kode.naiv.no/olemd/favoritter/internal/store" + "kode.naiv.no/olemd/favoritter/web" +) + +// Deps bundles all dependencies injected into handlers. +type Deps struct { + Config *config.Config + Users *store.UserStore + Sessions *store.SessionStore + Settings *store.SettingsStore + Faves *store.FaveStore + Tags *store.TagStore + SignupRequests *store.SignupRequestStore + Renderer *render.Renderer +} + +// Handler holds all HTTP handler methods and their dependencies. +type Handler struct { + deps Deps + rateLimiter *middleware.RateLimiter +} + +// New creates a new Handler with the given dependencies. +func New(deps Deps) *Handler { + return &Handler{ + deps: deps, + rateLimiter: middleware.NewRateLimiter(deps.Config.RateLimit), + } +} + +// RateLimiterCleanupLoop periodically evicts stale rate limiter entries. +func (h *Handler) RateLimiterCleanupLoop(ctx context.Context, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + h.rateLimiter.Cleanup() + } + } +} + +// Routes registers all routes on a new ServeMux and returns it. +func (h *Handler) Routes() *http.ServeMux { + mux := http.NewServeMux() + + // Static files (served from embedded filesystem). + staticFS, err := fs.Sub(web.StaticFS, "static") + if err != nil { + panic("embedded static filesystem missing: " + err.Error()) + } + mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))) + + // Uploaded images (served from the filesystem upload directory). + mux.Handle("GET /uploads/", http.StripPrefix("/uploads/", + http.FileServer(http.Dir(h.deps.Config.UploadDir)))) + + // Health check. + mux.HandleFunc("GET /health", h.handleHealth) + + // Auth routes (rate-limited). + mux.Handle("POST /login", h.rateLimiter.Limit(http.HandlerFunc(h.handleLoginPost))) + mux.Handle("POST /signup", h.rateLimiter.Limit(http.HandlerFunc(h.handleSignupPost))) + + mux.HandleFunc("GET /login", h.handleLoginGet) + mux.HandleFunc("GET /signup", h.handleSignupGet) + mux.HandleFunc("POST /logout", h.handleLogout) + + // Password reset (for must-reset-password flow). + mux.HandleFunc("GET /reset-password", h.handleResetPasswordGet) + mux.HandleFunc("POST /reset-password", h.handleResetPasswordPost) + + // Home page. + mux.HandleFunc("GET /{$}", h.handleHome) + + // Faves — authenticated routes use requireLogin wrapper. + requireLogin := middleware.RequireLogin(h.deps.Config.BasePath) + mux.Handle("GET /faves", requireLogin(http.HandlerFunc(h.handleFaveList))) + mux.Handle("GET /faves/new", requireLogin(http.HandlerFunc(h.handleFaveNew))) + mux.Handle("POST /faves", requireLogin(http.HandlerFunc(h.handleFaveCreate))) + mux.HandleFunc("GET /faves/{id}", h.handleFaveDetail) + mux.Handle("GET /faves/{id}/edit", requireLogin(http.HandlerFunc(h.handleFaveEdit))) + mux.Handle("POST /faves/{id}", requireLogin(http.HandlerFunc(h.handleFaveUpdate))) + mux.Handle("DELETE /faves/{id}", requireLogin(http.HandlerFunc(h.handleFaveDelete))) + + // Tags. + mux.HandleFunc("GET /tags/search", h.handleTagSearch) + mux.HandleFunc("GET /tags/{name}", h.handleTagBrowse) + + return mux +} diff --git a/internal/image/image.go b/internal/image/image.go new file mode 100644 index 0000000..cffdd96 --- /dev/null +++ b/internal/image/image.go @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package image handles uploaded image validation, processing, and storage. +// It strips EXIF metadata by re-encoding images and resizes to a maximum width. +package image + +import ( + "fmt" + "image" + "image/jpeg" + "image/png" + "io" + "mime/multipart" + "os" + "path/filepath" + "strings" + + "github.com/google/uuid" + + // Register image format decoders. + _ "image/gif" +) + +const ( + MaxWidth = 1920 + JPEGQuality = 85 +) + +// AllowedTypes maps MIME types to file extensions. +var AllowedTypes = map[string]string{ + "image/jpeg": ".jpg", + "image/png": ".png", + "image/gif": ".gif", + "image/webp": ".webp", +} + +// ProcessResult holds the result of processing an uploaded image. +type ProcessResult struct { + Filename string // UUID-based filename with extension + Path string // Full path where the image was saved +} + +// Process validates, re-encodes (stripping EXIF), and optionally resizes an +// uploaded image. It saves the result to uploadDir with a UUID filename. +// +// Re-encoding to JPEG or PNG strips all EXIF metadata including GPS coordinates, +// which is important for user privacy. +func Process(file multipart.File, header *multipart.FileHeader, uploadDir string) (*ProcessResult, error) { + // Validate content type. + contentType := header.Header.Get("Content-Type") + ext, ok := AllowedTypes[contentType] + if !ok { + return nil, fmt.Errorf("unsupported image type: %s (allowed: JPEG, PNG, GIF, WebP)", contentType) + } + + // Decode the image — this also validates it's a real image. + img, format, err := image.Decode(file) + if err != nil { + return nil, fmt.Errorf("invalid image: %w", err) + } + + // Resize if wider than MaxWidth, maintaining aspect ratio. + img = resizeIfNeeded(img) + + // Generate UUID filename. + filename := uuid.New().String() + ext + + // Ensure upload directory exists. + if err := os.MkdirAll(uploadDir, 0750); err != nil { + return nil, fmt.Errorf("create upload dir: %w", err) + } + + fullPath := filepath.Join(uploadDir, filename) + outFile, err := os.Create(fullPath) + if err != nil { + return nil, fmt.Errorf("create output file: %w", err) + } + defer outFile.Close() + + // Re-encode the image, which strips all EXIF metadata. + if err := encode(outFile, img, format, ext); err != nil { + os.Remove(fullPath) + return nil, fmt.Errorf("encode image: %w", err) + } + + return &ProcessResult{ + Filename: filename, + Path: fullPath, + }, nil +} + +// Delete removes an uploaded image file. +func Delete(uploadDir, filename string) error { + if filename == "" { + return nil + } + path := filepath.Join(uploadDir, filename) + // Only delete if the file is actually inside the upload directory + // to prevent path traversal. + absPath, err := filepath.Abs(path) + if err != nil { + return err + } + absDir, err := filepath.Abs(uploadDir) + if err != nil { + return err + } + if !strings.HasPrefix(absPath, absDir+string(filepath.Separator)) { + return fmt.Errorf("path traversal detected") + } + return os.Remove(absPath) +} + +// encode writes the image in the appropriate format. +// GIF and WebP are re-encoded as PNG since Go's stdlib can decode but not +// encode GIF animations or WebP. This is acceptable — we prioritize EXIF +// stripping over format preservation. +func encode(w io.Writer, img image.Image, format, ext string) error { + switch { + case format == "jpeg" || ext == ".jpg": + return jpeg.Encode(w, img, &jpeg.Options{Quality: JPEGQuality}) + default: + // PNG for everything else (png, gif, webp). + return png.Encode(w, img) + } +} + +// resizeIfNeeded scales the image down if it exceeds MaxWidth. +// Uses nearest-neighbor for simplicity — good enough for a favorites app. +func resizeIfNeeded(img image.Image) image.Image { + bounds := img.Bounds() + w := bounds.Dx() + h := bounds.Dy() + + if w <= MaxWidth { + return img + } + + newW := MaxWidth + newH := h * MaxWidth / w + + dst := image.NewRGBA(image.Rect(0, 0, newW, newH)) + + // Simple bilinear-ish downscale by sampling. + for y := 0; y < newH; y++ { + for x := 0; x < newW; x++ { + srcX := x * w / newW + srcY := y * h / newH + dst.Set(x, y, img.At(srcX+bounds.Min.X, srcY+bounds.Min.Y)) + } + } + + return dst +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go new file mode 100644 index 0000000..54c13a6 --- /dev/null +++ b/internal/middleware/auth.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "context" + "errors" + "net/http" + + "kode.naiv.no/olemd/favoritter/internal/store" +) + +const SessionCookieName = "session" + +// ClearSessionCookie sets an expired session cookie to remove it from the client. +func ClearSessionCookie(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: SessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + }) +} + +// SessionLoader loads the user from the session cookie on every request. +// If the session is valid, the user is attached to the request context. +func SessionLoader(sessions *store.SessionStore, users *store.UserStore) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie(SessionCookieName) + if err != nil { + next.ServeHTTP(w, r) + return + } + + session, err := sessions.Validate(cookie.Value) + if err != nil { + if errors.Is(err, store.ErrSessionNotFound) { + ClearSessionCookie(w) + } + next.ServeHTTP(w, r) + return + } + + user, err := users.GetByID(session.UserID) + if err != nil || user.Disabled { + sessions.Delete(cookie.Value) + ClearSessionCookie(w) + next.ServeHTTP(w, r) + return + } + + ctx := context.WithValue(r.Context(), userKey, user) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} diff --git a/internal/middleware/basepath.go b/internal/middleware/basepath.go new file mode 100644 index 0000000..3874a91 --- /dev/null +++ b/internal/middleware/basepath.go @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "net/http" + "strings" +) + +// BasePath strips a configured path prefix from incoming requests so the +// router sees paths without the prefix. This enables deployment at both +// faves.example.com (basePath="") and example.com/faves (basePath="/faves"). +func BasePath(prefix string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + if prefix == "" { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Strip the prefix from the URL path. + if strings.HasPrefix(r.URL.Path, prefix) { + r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix) + if r.URL.Path == "" { + r.URL.Path = "/" + } + // Also update RawPath if present. + if r.URL.RawPath != "" { + r.URL.RawPath = strings.TrimPrefix(r.URL.RawPath, prefix) + if r.URL.RawPath == "" { + r.URL.RawPath = "/" + } + } + } + next.ServeHTTP(w, r) + }) + } +} diff --git a/internal/middleware/context.go b/internal/middleware/context.go new file mode 100644 index 0000000..2b45659 --- /dev/null +++ b/internal/middleware/context.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "context" + "net/http" + + "kode.naiv.no/olemd/favoritter/internal/model" +) + +type contextKey string + +const ( + userKey contextKey = "user" + csrfTokenKey contextKey = "csrf_token" + realIPKey contextKey = "real_ip" +) + +// UserFromContext returns the authenticated user from the request context, or nil. +func UserFromContext(ctx context.Context) *model.User { + u, _ := ctx.Value(userKey).(*model.User) + return u +} + +// CSRFTokenFromContext returns the CSRF token from the request context. +func CSRFTokenFromContext(ctx context.Context) string { + s, _ := ctx.Value(csrfTokenKey).(string) + return s +} + +// RealIPFromContext returns the real client IP from the request context. +func RealIPFromContext(ctx context.Context) string { + s, _ := ctx.Value(realIPKey).(string) + return s +} + +// RequireLogin redirects to the login page if no user is authenticated. +func RequireLogin(basePath string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if UserFromContext(r.Context()) == nil { + http.Redirect(w, r, basePath+"/login", http.StatusSeeOther) + return + } + next.ServeHTTP(w, r) + }) + } +} + +// RequireAdmin returns 403 if the user is not an admin. +func RequireAdmin(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil || !user.IsAdmin() { + http.Error(w, "Forbidden", http.StatusForbidden) + return + } + next.ServeHTTP(w, r) + }) +} diff --git a/internal/middleware/csrf.go b/internal/middleware/csrf.go new file mode 100644 index 0000000..734989f --- /dev/null +++ b/internal/middleware/csrf.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net/http" + "strings" + + "kode.naiv.no/olemd/favoritter/internal/config" +) + +const ( + csrfCookieName = "csrf_token" + csrfFormField = "csrf_token" + csrfHeaderName = "X-CSRF-Token" +) + +// CSRFProtection implements double-submit cookie pattern for CSRF prevention. +// A token is stored in a cookie and must also be submitted in a form field +// or header on state-changing requests (POST, PUT, DELETE, PATCH). +func CSRFProtection(cfg *config.Config) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Read or generate the CSRF token. + token := "" + if cookie, err := r.Cookie(csrfCookieName); err == nil { + token = cookie.Value + } + if token == "" { + token = generateCSRFToken() + secure := IsSecureRequest(r, cfg) + http.SetCookie(w, &http.Cookie{ + Name: csrfCookieName, + Value: token, + Path: "/", + HttpOnly: false, // JS needs to read it for HTMX hx-headers + Secure: secure, + SameSite: http.SameSiteLaxMode, + }) + } + + // Attach token to context for templates. + ctx := context.WithValue(r.Context(), csrfTokenKey, token) + r = r.WithContext(ctx) + + // Validate on state-changing methods. + if isStateChangingMethod(r.Method) { + // Skip CSRF check for API routes that use Bearer auth (future). + if !strings.HasPrefix(r.URL.Path, "/api/") { + submitted := r.FormValue(csrfFormField) + if submitted == "" { + submitted = r.Header.Get(csrfHeaderName) + } + if submitted != token { + http.Error(w, "CSRF token mismatch", http.StatusForbidden) + return + } + } + } + + next.ServeHTTP(w, r) + }) + } +} + +func isStateChangingMethod(method string) bool { + switch method { + case http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch: + return true + } + return false +} + +func generateCSRFToken() string { + b := make([]byte, 32) + rand.Read(b) + return hex.EncodeToString(b) +} + +// IsSecureRequest determines if the original client request used HTTPS, +// checking X-Forwarded-Proto from trusted proxies. +func IsSecureRequest(r *http.Request, cfg *config.Config) bool { + if cfg.ExternalURL != "" { + return strings.HasPrefix(cfg.ExternalURL, "https://") + } + if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" { + return proto == "https" + } + return r.TLS != nil +} diff --git a/internal/middleware/logger.go b/internal/middleware/logger.go new file mode 100644 index 0000000..a302366 --- /dev/null +++ b/internal/middleware/logger.go @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "log/slog" + "net/http" + "time" +) + +// responseWriter wraps http.ResponseWriter to capture the status code. +type responseWriter struct { + http.ResponseWriter + statusCode int +} + +func (rw *responseWriter) WriteHeader(code int) { + rw.statusCode = code + rw.ResponseWriter.WriteHeader(code) +} + +// RequestLogger logs each HTTP request with method, path, status, and duration. +func RequestLogger(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK} + + next.ServeHTTP(rw, r) + + slog.Debug("request", + "method", r.Method, + "path", r.URL.Path, + "status", rw.statusCode, + "duration", time.Since(start), + "ip", RealIPFromContext(r.Context()), + ) + }) +} diff --git a/internal/middleware/middleware.go b/internal/middleware/middleware.go new file mode 100644 index 0000000..538fbf4 --- /dev/null +++ b/internal/middleware/middleware.go @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package middleware provides HTTP middleware for auth, security, and request processing. +package middleware + +import "net/http" + +// Chain wraps a handler with a stack of middleware, applied in order +// (the last middleware listed is the outermost wrapper). +func Chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler { + for _, m := range middlewares { + h = m(h) + } + return h +} diff --git a/internal/middleware/ratelimit.go b/internal/middleware/ratelimit.go new file mode 100644 index 0000000..9a2f8a3 --- /dev/null +++ b/internal/middleware/ratelimit.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "net/http" + "sync" + "time" +) + +// RateLimiter implements a simple per-IP token bucket rate limiter for +// protecting auth endpoints from brute-force attacks. +type RateLimiter struct { + mu sync.Mutex + visitors map[string]*bucket + rate int + window time.Duration +} + +type bucket struct { + tokens int + lastReset time.Time +} + +// NewRateLimiter creates a rate limiter that allows `rate` requests per minute per IP. +func NewRateLimiter(rate int) *RateLimiter { + return &RateLimiter{ + visitors: make(map[string]*bucket), + rate: rate, + window: time.Minute, + } +} + +// Limit wraps a handler with rate limiting based on the real client IP. +func (rl *RateLimiter) Limit(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ip := RealIPFromContext(r.Context()) + if ip == "" { + ip = r.RemoteAddr + } + + if !rl.allow(ip) { + http.Error(w, "Too many requests. Please try again later.", http.StatusTooManyRequests) + return + } + + next.ServeHTTP(w, r) + }) +} + +func (rl *RateLimiter) allow(ip string) bool { + rl.mu.Lock() + defer rl.mu.Unlock() + + now := time.Now() + + b, ok := rl.visitors[ip] + if !ok { + rl.visitors[ip] = &bucket{tokens: rl.rate - 1, lastReset: now} + return true + } + + // Reset tokens if the window has passed. + if now.Sub(b.lastReset) >= rl.window { + b.tokens = rl.rate - 1 + b.lastReset = now + return true + } + + if b.tokens <= 0 { + return false + } + + b.tokens-- + return true +} + +// Cleanup removes stale entries. Call periodically from a goroutine. +func (rl *RateLimiter) Cleanup() { + rl.mu.Lock() + defer rl.mu.Unlock() + + now := time.Now() + for ip, b := range rl.visitors { + if now.Sub(b.lastReset) >= 2*rl.window { + delete(rl.visitors, ip) + } + } +} diff --git a/internal/middleware/realip.go b/internal/middleware/realip.go new file mode 100644 index 0000000..4069538 --- /dev/null +++ b/internal/middleware/realip.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "context" + "net" + "net/http" + "strings" +) + +// RealIP extracts the real client IP from X-Forwarded-For, but only if the +// direct connection comes from a trusted proxy. This is essential when Caddy +// runs on a different machine (e.g. connected via WireGuard/Tailscale). +func RealIP(trustedProxies []*net.IPNet) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ip := extractRealIP(r, trustedProxies) + ctx := context.WithValue(r.Context(), realIPKey, ip) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +func extractRealIP(r *http.Request, trusted []*net.IPNet) string { + // Get the direct connection IP. + directIP, _, _ := net.SplitHostPort(r.RemoteAddr) + if directIP == "" { + directIP = r.RemoteAddr + } + + // Only trust X-Forwarded-For if the direct connection is from a trusted proxy. + if !isTrusted(directIP, trusted) { + return directIP + } + + // Parse X-Forwarded-For: client, proxy1, proxy2 + // The rightmost non-trusted IP is the real client. + xff := r.Header.Get("X-Forwarded-For") + if xff == "" { + return directIP + } + + ips := strings.Split(xff, ",") + // Walk from right to left, finding the first non-trusted IP. + for i := len(ips) - 1; i >= 0; i-- { + ip := strings.TrimSpace(ips[i]) + if !isTrusted(ip, trusted) { + return ip + } + } + + // All IPs in the chain are trusted; use the leftmost. + return strings.TrimSpace(ips[0]) +} + +func isTrusted(ipStr string, nets []*net.IPNet) bool { + ip := net.ParseIP(ipStr) + if ip == nil { + return false + } + for _, n := range nets { + if n.Contains(ip) { + return true + } + } + return false +} diff --git a/internal/middleware/recovery.go b/internal/middleware/recovery.go new file mode 100644 index 0000000..9518e74 --- /dev/null +++ b/internal/middleware/recovery.go @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import ( + "log/slog" + "net/http" + "runtime/debug" +) + +// Recovery catches panics in HTTP handlers and returns a 500 error +// instead of crashing the server. +func Recovery(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + slog.Error("panic recovered", + "error", err, + "path", r.URL.Path, + "stack", string(debug.Stack()), + ) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + }() + next.ServeHTTP(w, r) + }) +} diff --git a/internal/middleware/security.go b/internal/middleware/security.go new file mode 100644 index 0000000..a663d9e --- /dev/null +++ b/internal/middleware/security.go @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package middleware + +import "net/http" + +// SecurityHeaders adds security-related HTTP headers to every response. +func SecurityHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + h.Set("X-Frame-Options", "DENY") + h.Set("Referrer-Policy", "strict-origin-when-cross-origin") + h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + // CSP allows inline styles from Pico CSS and scripts from self only. + // The 'unsafe-inline' for style-src is needed for Pico CSS. + h.Set("Content-Security-Policy", + "default-src 'self'; "+ + "style-src 'self' 'unsafe-inline'; "+ + "img-src 'self' data:; "+ + "frame-ancestors 'none'") + next.ServeHTTP(w, r) + }) +} diff --git a/internal/model/fave.go b/internal/model/fave.go new file mode 100644 index 0000000..6b81290 --- /dev/null +++ b/internal/model/fave.go @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package model + +import "time" + +type Fave struct { + ID int64 + UserID int64 + Description string + URL string + ImagePath string + Privacy string + Tags []Tag + CreatedAt time.Time + UpdatedAt time.Time + + // Joined fields for display. + Username string + DisplayName string +} + +// IsPublic returns true if the fave is publicly visible. +func (f *Fave) IsPublic() bool { + return f.Privacy == "public" +} diff --git a/internal/model/session.go b/internal/model/session.go new file mode 100644 index 0000000..3acac38 --- /dev/null +++ b/internal/model/session.go @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package model + +import "time" + +type Session struct { + Token string + UserID int64 + ExpiresAt time.Time + CreatedAt time.Time +} diff --git a/internal/model/settings.go b/internal/model/settings.go new file mode 100644 index 0000000..c787033 --- /dev/null +++ b/internal/model/settings.go @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package model + +import "time" + +type SiteSettings struct { + SiteName string + SiteDescription string + SignupMode string + UpdatedAt time.Time +} + +// SignupOpen returns true if self-registration is allowed. +func (s *SiteSettings) SignupOpen() bool { + return s.SignupMode == "open" +} + +// SignupRequests returns true if signup requires admin approval. +func (s *SiteSettings) SignupRequests() bool { + return s.SignupMode == "requests" +} + +// SignupClosed returns true if no new signups are allowed. +func (s *SiteSettings) SignupClosed() bool { + return s.SignupMode == "closed" +} diff --git a/internal/model/tag.go b/internal/model/tag.go new file mode 100644 index 0000000..4bfc129 --- /dev/null +++ b/internal/model/tag.go @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package model + +type Tag struct { + ID int64 + Name string +} diff --git a/internal/model/user.go b/internal/model/user.go new file mode 100644 index 0000000..cd75406 --- /dev/null +++ b/internal/model/user.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package model + +import "time" + +type User struct { + ID int64 + Username string + DisplayName string + Bio string + AvatarPath string + PasswordHash string + Role string + ProfileVisibility string + DefaultFavePrivacy string + MustResetPassword bool + Disabled bool + CreatedAt time.Time + UpdatedAt time.Time +} + +// IsAdmin returns true if the user has the admin role. +func (u *User) IsAdmin() bool { + return u.Role == "admin" +} + +// DisplayNameOrUsername returns the display name if set, otherwise the username. +func (u *User) DisplayNameOrUsername() string { + if u.DisplayName != "" { + return u.DisplayName + } + return u.Username +} diff --git a/internal/render/render.go b/internal/render/render.go new file mode 100644 index 0000000..7ecb6e8 --- /dev/null +++ b/internal/render/render.go @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package render provides HTML template rendering with layout support. +package render + +import ( + "fmt" + "html/template" + "io" + "io/fs" + "log/slog" + "net/http" + "os" + "path/filepath" + "strings" + + "kode.naiv.no/olemd/favoritter/internal/config" + "kode.naiv.no/olemd/favoritter/internal/middleware" + "kode.naiv.no/olemd/favoritter/internal/model" + "kode.naiv.no/olemd/favoritter/internal/store" + "kode.naiv.no/olemd/favoritter/web" +) + +// Renderer parses and executes HTML templates. +type Renderer struct { + templates map[string]*template.Template + cfg *config.Config +} + +// PageData holds data passed to page templates. +type PageData struct { + Title string + User *model.User + CSRFToken string + BasePath string + SiteName string + Flash string + FlashType string // "success", "error", "info" + ExternalURL string + Data any +} + +// New creates a Renderer, parsing all templates from the embedded filesystem. +func New(cfg *config.Config) (*Renderer, error) { + r := &Renderer{ + cfg: cfg, + } + + if err := r.parseTemplates(); err != nil { + return nil, err + } + + return r, nil +} + +func (r *Renderer) parseTemplates() error { + r.templates = make(map[string]*template.Template) + + var templateFS fs.FS + if r.cfg.DevMode { + // In dev mode, read templates from disk for live reload. + templateFS = os.DirFS(filepath.Join("web", "templates")) + } else { + sub, err := fs.Sub(web.TemplatesFS, "templates") + if err != nil { + return fmt.Errorf("sub templates fs: %w", err) + } + templateFS = sub + } + + funcMap := r.templateFuncs() + + // Parse the base layout. + baseLayout, err := template.New("base.html").Funcs(funcMap).ParseFS(templateFS, "layouts/base.html") + if err != nil { + return fmt.Errorf("parse base layout: %w", err) + } + + // Parse each page template with the base layout. + pages, err := fs.Glob(templateFS, "pages/*.html") + if err != nil { + return fmt.Errorf("glob pages: %w", err) + } + + for _, page := range pages { + name := strings.TrimPrefix(page, "pages/") + name = strings.TrimSuffix(name, ".html") + + t, err := baseLayout.Clone() + if err != nil { + return fmt.Errorf("clone base for %s: %w", name, err) + } + + _, err = t.ParseFS(templateFS, page) + if err != nil { + return fmt.Errorf("parse page %s: %w", name, err) + } + + r.templates[name] = t + } + + // Parse partial templates (for HTMX responses). + partials, err := fs.Glob(templateFS, "partials/*.html") + if err != nil { + return fmt.Errorf("glob partials: %w", err) + } + + for _, partial := range partials { + name := "partial:" + strings.TrimPrefix(partial, "partials/") + name = strings.TrimSuffix(name, ".html") + + t, err := template.New(filepath.Base(partial)).Funcs(funcMap).ParseFS(templateFS, partial) + if err != nil { + return fmt.Errorf("parse partial %s: %w", name, err) + } + + r.templates[name] = t + } + + slog.Info("templates loaded", "pages", len(pages), "partials", len(partials)) + return nil +} + +// Page renders a full page with the base layout. +func (r *Renderer) Page(w http.ResponseWriter, req *http.Request, name string, data PageData) { + if r.cfg.DevMode { + // Reparse templates on every request in dev mode. + if err := r.parseTemplates(); err != nil { + slog.Error("template reparse failed", "error", err) + http.Error(w, "Template error", http.StatusInternalServerError) + return + } + } + + // Populate common data from context. + data.User = middleware.UserFromContext(req.Context()) + data.CSRFToken = middleware.CSRFTokenFromContext(req.Context()) + data.BasePath = r.cfg.BasePath + data.SiteName = r.cfg.SiteName + data.ExternalURL = r.cfg.ExternalURL + + t, ok := r.templates[name] + if !ok { + slog.Error("template not found", "name", name) + http.Error(w, "Template not found", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := t.ExecuteTemplate(w, "base.html", data); err != nil { + slog.Error("template execute failed", "name", name, "error", err) + } +} + +// Partial renders a partial template (for HTMX responses). +func (r *Renderer) Partial(w io.Writer, name string, data any) error { + key := "partial:" + name + t, ok := r.templates[key] + if !ok { + return fmt.Errorf("partial template %q not found", name) + } + return t.Execute(w, data) +} + +func (r *Renderer) templateFuncs() template.FuncMap { + return template.FuncMap{ + // basePath returns the configured base path for URL construction. + "basePath": func() string { + return r.cfg.BasePath + }, + // externalURL returns the configured external URL. + "externalURL": func() string { + return r.cfg.ExternalURL + }, + // truncate truncates a string to n characters. + "truncate": func(n int, s string) string { + if len(s) <= n { + return s + } + return s[:n] + "..." + }, + // join joins strings with a separator. + "join": strings.Join, + // contains checks if a string contains a substring. + "contains": strings.Contains, + // add returns a + b. + "add": func(a, b int) int { return a + b }, + // subtract returns a - b. + "subtract": func(a, b int) int { return a - b }, + // maxTags returns the maximum number of tags per fave. + "maxTags": func() int { return store.MaxTagsPerFave }, + } +} diff --git a/internal/store/fave.go b/internal/store/fave.go new file mode 100644 index 0000000..b429581 --- /dev/null +++ b/internal/store/fave.go @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "kode.naiv.no/olemd/favoritter/internal/model" +) + +var ErrFaveNotFound = errors.New("fave not found") + +type FaveStore struct { + db *sql.DB +} + +func NewFaveStore(db *sql.DB) *FaveStore { + return &FaveStore{db: db} +} + +// Create inserts a new fave and returns it with its ID populated. +func (s *FaveStore) Create(userID int64, description, url, imagePath, privacy string) (*model.Fave, error) { + result, err := s.db.Exec( + `INSERT INTO faves (user_id, description, url, image_path, privacy) + VALUES (?, ?, ?, ?, ?)`, + userID, description, url, imagePath, privacy, + ) + if err != nil { + return nil, fmt.Errorf("insert fave: %w", err) + } + + id, _ := result.LastInsertId() + return s.GetByID(id) +} + +// GetByID returns a fave by its ID, including joined user info. +func (s *FaveStore) GetByID(id int64) (*model.Fave, error) { + f := &model.Fave{} + var createdAt, updatedAt string + err := s.db.QueryRow( + `SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy, + f.created_at, f.updated_at, u.username, u.display_name + FROM faves f + JOIN users u ON u.id = f.user_id + WHERE f.id = ?`, id, + ).Scan( + &f.ID, &f.UserID, &f.Description, &f.URL, &f.ImagePath, &f.Privacy, + &createdAt, &updatedAt, &f.Username, &f.DisplayName, + ) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrFaveNotFound + } + if err != nil { + return nil, fmt.Errorf("query fave: %w", err) + } + f.CreatedAt, _ = time.Parse(time.RFC3339, createdAt) + f.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt) + return f, nil +} + +// Update modifies an existing fave's fields. +func (s *FaveStore) Update(id int64, description, url, imagePath, privacy string) error { + _, err := s.db.Exec( + `UPDATE faves SET description = ?, url = ?, image_path = ?, privacy = ?, + updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + WHERE id = ?`, + description, url, imagePath, privacy, id, + ) + return err +} + +// Delete removes a fave by its ID. The cascade will clean up fave_tags. +func (s *FaveStore) Delete(id int64) error { + result, err := s.db.Exec("DELETE FROM faves WHERE id = ?", id) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n == 0 { + return ErrFaveNotFound + } + return nil +} + +// ListByUser returns all faves for a user (both public and private), +// ordered by newest first, with pagination. +func (s *FaveStore) ListByUser(userID int64, limit, offset int) ([]*model.Fave, int, error) { + var total int + err := s.db.QueryRow("SELECT COUNT(*) FROM faves WHERE user_id = ?", userID).Scan(&total) + if err != nil { + return nil, 0, err + } + + rows, err := s.db.Query( + `SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy, + f.created_at, f.updated_at, u.username, u.display_name + FROM faves f + JOIN users u ON u.id = f.user_id + WHERE f.user_id = ? + ORDER BY f.created_at DESC + LIMIT ? OFFSET ?`, + userID, limit, offset, + ) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + faves, err := s.scanFaves(rows) + return faves, total, err +} + +// ListPublicByUser returns only public faves for a user, with pagination. +func (s *FaveStore) ListPublicByUser(userID int64, limit, offset int) ([]*model.Fave, int, error) { + var total int + err := s.db.QueryRow( + "SELECT COUNT(*) FROM faves WHERE user_id = ? AND privacy = 'public'", userID, + ).Scan(&total) + if err != nil { + return nil, 0, err + } + + rows, err := s.db.Query( + `SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy, + f.created_at, f.updated_at, u.username, u.display_name + FROM faves f + JOIN users u ON u.id = f.user_id + WHERE f.user_id = ? AND f.privacy = 'public' + ORDER BY f.created_at DESC + LIMIT ? OFFSET ?`, + userID, limit, offset, + ) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + faves, err := s.scanFaves(rows) + return faves, total, err +} + +// ListPublic returns all public faves across all users, with pagination. +func (s *FaveStore) ListPublic(limit, offset int) ([]*model.Fave, int, error) { + var total int + err := s.db.QueryRow("SELECT COUNT(*) FROM faves WHERE privacy = 'public'").Scan(&total) + if err != nil { + return nil, 0, err + } + + rows, err := s.db.Query( + `SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy, + f.created_at, f.updated_at, u.username, u.display_name + FROM faves f + JOIN users u ON u.id = f.user_id + WHERE f.privacy = 'public' + ORDER BY f.created_at DESC + LIMIT ? OFFSET ?`, + limit, offset, + ) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + faves, err := s.scanFaves(rows) + return faves, total, err +} + +// ListByTag returns all public faves with a given tag, with pagination. +func (s *FaveStore) ListByTag(tagName string, limit, offset int) ([]*model.Fave, int, error) { + var total int + err := s.db.QueryRow( + `SELECT COUNT(*) FROM faves f + JOIN fave_tags ft ON ft.fave_id = f.id + JOIN tags t ON t.id = ft.tag_id + WHERE t.name = ? AND f.privacy = 'public'`, tagName, + ).Scan(&total) + if err != nil { + return nil, 0, err + } + + rows, err := s.db.Query( + `SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy, + f.created_at, f.updated_at, u.username, u.display_name + FROM faves f + JOIN users u ON u.id = f.user_id + JOIN fave_tags ft ON ft.fave_id = f.id + JOIN tags t ON t.id = ft.tag_id + WHERE t.name = ? AND f.privacy = 'public' + ORDER BY f.created_at DESC + LIMIT ? OFFSET ?`, + tagName, limit, offset, + ) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + faves, err := s.scanFaves(rows) + return faves, total, err +} + +// Count returns the total number of faves. +func (s *FaveStore) Count() (int, error) { + var n int + err := s.db.QueryRow("SELECT COUNT(*) FROM faves").Scan(&n) + return n, err +} + +// LoadTags populates the Tags field on each fave. +func (s *FaveStore) LoadTags(faves []*model.Fave) error { + if len(faves) == 0 { + return nil + } + + // Build a map for fast lookup. + faveMap := make(map[int64]*model.Fave, len(faves)) + ids := make([]any, len(faves)) + placeholders := make([]string, len(faves)) + for i, f := range faves { + faveMap[f.ID] = f + ids[i] = f.ID + placeholders[i] = "?" + } + + query := fmt.Sprintf( + `SELECT ft.fave_id, t.id, t.name + FROM fave_tags ft + JOIN tags t ON t.id = ft.tag_id + WHERE ft.fave_id IN (%s) + ORDER BY t.name COLLATE NOCASE`, + strings.Join(placeholders, ","), + ) + + rows, err := s.db.Query(query, ids...) + if err != nil { + return fmt.Errorf("load tags: %w", err) + } + defer rows.Close() + + for rows.Next() { + var faveID int64 + var tag model.Tag + if err := rows.Scan(&faveID, &tag.ID, &tag.Name); err != nil { + return fmt.Errorf("scan tag: %w", err) + } + if f, ok := faveMap[faveID]; ok { + f.Tags = append(f.Tags, tag) + } + } + return rows.Err() +} + +func (s *FaveStore) scanFaves(rows *sql.Rows) ([]*model.Fave, error) { + var faves []*model.Fave + for rows.Next() { + f := &model.Fave{} + var createdAt, updatedAt string + err := rows.Scan( + &f.ID, &f.UserID, &f.Description, &f.URL, &f.ImagePath, &f.Privacy, + &createdAt, &updatedAt, &f.Username, &f.DisplayName, + ) + if err != nil { + return nil, fmt.Errorf("scan fave: %w", err) + } + f.CreatedAt, _ = time.Parse(time.RFC3339, createdAt) + f.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt) + faves = append(faves, f) + } + return faves, rows.Err() +} + diff --git a/internal/store/fave_test.go b/internal/store/fave_test.go new file mode 100644 index 0000000..7779b3d --- /dev/null +++ b/internal/store/fave_test.go @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "testing" +) + +func TestFaveCRUD(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + faves := NewFaveStore(db) + tags := NewTagStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { Argon2Memory = 65536; Argon2Time = 3 }() + + // Create a user first. + user, err := users.Create("testuser", "password123", "user") + if err != nil { + t.Fatalf("create user: %v", err) + } + + // Create a fave. + fave, err := faves.Create(user.ID, "Blade Runner 2049", "https://example.com", "", "public") + if err != nil { + t.Fatalf("create fave: %v", err) + } + if fave.Description != "Blade Runner 2049" { + t.Errorf("description = %q, want %q", fave.Description, "Blade Runner 2049") + } + if fave.Username != "testuser" { + t.Errorf("username = %q, want %q", fave.Username, "testuser") + } + + // Get by ID. + got, err := faves.GetByID(fave.ID) + if err != nil { + t.Fatalf("get fave: %v", err) + } + if got.Description != fave.Description { + t.Errorf("got description = %q, want %q", got.Description, fave.Description) + } + + // Update. + err = faves.Update(fave.ID, "Blade Runner 2049 (Final Cut)", "https://example.com/br2049", "", "private") + if err != nil { + t.Fatalf("update fave: %v", err) + } + updated, _ := faves.GetByID(fave.ID) + if updated.Description != "Blade Runner 2049 (Final Cut)" { + t.Errorf("updated description = %q", updated.Description) + } + if updated.Privacy != "private" { + t.Errorf("updated privacy = %q, want private", updated.Privacy) + } + + // Set tags. + err = tags.SetFaveTags(fave.ID, []string{"film", "sci-fi", "favoritt"}) + if err != nil { + t.Fatalf("set tags: %v", err) + } + faveTags, err := tags.ForFave(fave.ID) + if err != nil { + t.Fatalf("for fave: %v", err) + } + if len(faveTags) != 3 { + t.Errorf("tag count = %d, want 3", len(faveTags)) + } + + // List by user. + list, total, err := faves.ListByUser(user.ID, 10, 0) + if err != nil { + t.Fatalf("list by user: %v", err) + } + if total != 1 || len(list) != 1 { + t.Errorf("list by user: total=%d, len=%d", total, len(list)) + } + + // Load tags for list. + err = faves.LoadTags(list) + if err != nil { + t.Fatalf("load tags: %v", err) + } + if len(list[0].Tags) != 3 { + t.Errorf("loaded tags = %d, want 3", len(list[0].Tags)) + } + + // Public list should be empty (fave is now private). + pubList, pubTotal, err := faves.ListPublicByUser(user.ID, 10, 0) + if err != nil { + t.Fatalf("list public: %v", err) + } + if pubTotal != 0 || len(pubList) != 0 { + t.Errorf("public list should be empty: total=%d, len=%d", pubTotal, len(pubList)) + } + + // Delete. + err = faves.Delete(fave.ID) + if err != nil { + t.Fatalf("delete fave: %v", err) + } + _, err = faves.GetByID(fave.ID) + if err != ErrFaveNotFound { + t.Errorf("deleted fave error = %v, want ErrFaveNotFound", err) + } +} + +func TestListByTag(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + faves := NewFaveStore(db) + tags := NewTagStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { Argon2Memory = 65536; Argon2Time = 3 }() + + user, _ := users.Create("testuser", "password123", "user") + + // Create two public faves with overlapping tags. + f1, _ := faves.Create(user.ID, "Fave 1", "", "", "public") + f2, _ := faves.Create(user.ID, "Fave 2", "", "", "public") + f3, _ := faves.Create(user.ID, "Private Fave", "", "", "private") + + tags.SetFaveTags(f1.ID, []string{"music", "jazz"}) + tags.SetFaveTags(f2.ID, []string{"music", "rock"}) + tags.SetFaveTags(f3.ID, []string{"music", "secret"}) + + // ListByTag only returns public faves. + list, total, err := faves.ListByTag("music", 10, 0) + if err != nil { + t.Fatalf("list by tag: %v", err) + } + if total != 2 { + t.Errorf("total = %d, want 2 (private fave should be excluded)", total) + } + if len(list) != 2 { + t.Errorf("len = %d, want 2", len(list)) + } +} + +func TestFavePagination(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + faves := NewFaveStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { Argon2Memory = 65536; Argon2Time = 3 }() + + user, _ := users.Create("testuser", "password123", "user") + + // Create 5 faves. + for i := 0; i < 5; i++ { + faves.Create(user.ID, "Fave "+string(rune('A'+i)), "", "", "public") + } + + // Page 1 with limit 2. + page1, total, err := faves.ListByUser(user.ID, 2, 0) + if err != nil { + t.Fatalf("page 1: %v", err) + } + if total != 5 { + t.Errorf("total = %d, want 5", total) + } + if len(page1) != 2 { + t.Errorf("page 1 len = %d, want 2", len(page1)) + } + + // Page 3 with limit 2 should have 1 item. + page3, _, err := faves.ListByUser(user.ID, 2, 4) + if err != nil { + t.Fatalf("page 3: %v", err) + } + if len(page3) != 1 { + t.Errorf("page 3 len = %d, want 1", len(page3)) + } +} diff --git a/internal/store/session.go b/internal/store/session.go new file mode 100644 index 0000000..c74cf86 --- /dev/null +++ b/internal/store/session.go @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "time" + + "kode.naiv.no/olemd/favoritter/internal/model" +) + +var ErrSessionNotFound = errors.New("session not found") + +type SessionStore struct { + db *sql.DB + lifetime time.Duration +} + +func NewSessionStore(db *sql.DB) *SessionStore { + return &SessionStore{db: db, lifetime: 720 * time.Hour} // default 30 days +} + +// SetLifetime configures the session lifetime. +func (s *SessionStore) SetLifetime(d time.Duration) { + s.lifetime = d +} + +// Create generates a new session token for the given user. +func (s *SessionStore) Create(userID int64) (string, error) { + tokenBytes := make([]byte, 32) + if _, err := rand.Read(tokenBytes); err != nil { + return "", fmt.Errorf("generate session token: %w", err) + } + token := hex.EncodeToString(tokenBytes) + + expiresAt := time.Now().UTC().Add(s.lifetime) + _, err := s.db.Exec( + `INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`, + token, userID, expiresAt.Format(time.RFC3339), + ) + if err != nil { + return "", fmt.Errorf("insert session: %w", err) + } + + return token, nil +} + +// Validate checks if a session token is valid and not expired. +// Returns the session if valid. +func (s *SessionStore) Validate(token string) (*model.Session, error) { + var session model.Session + var expiresAt, createdAt string + err := s.db.QueryRow( + `SELECT token, user_id, expires_at, created_at + FROM sessions WHERE token = ?`, token, + ).Scan(&session.Token, &session.UserID, &expiresAt, &createdAt) + + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrSessionNotFound + } + if err != nil { + return nil, fmt.Errorf("query session: %w", err) + } + + session.ExpiresAt, _ = time.Parse(time.RFC3339, expiresAt) + session.CreatedAt, _ = time.Parse(time.RFC3339, createdAt) + + if time.Now().UTC().After(session.ExpiresAt) { + // Session has expired — delete it. + s.Delete(token) + return nil, ErrSessionNotFound + } + + return &session, nil +} + +// Delete removes a session by its token. +func (s *SessionStore) Delete(token string) error { + _, err := s.db.Exec("DELETE FROM sessions WHERE token = ?", token) + return err +} + +// DeleteAllForUser removes all sessions for a given user (e.g., on password change). +func (s *SessionStore) DeleteAllForUser(userID int64) error { + _, err := s.db.Exec("DELETE FROM sessions WHERE user_id = ?", userID) + return err +} + +// CleanupLoop periodically removes expired sessions. It runs until the +// context is canceled. +func (s *SessionStore) CleanupLoop(ctx context.Context, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + result, err := s.db.Exec( + `DELETE FROM sessions WHERE expires_at < strftime('%Y-%m-%dT%H:%M:%SZ', 'now')`, + ) + if err != nil { + slog.Error("session cleanup failed", "error", err) + continue + } + n, _ := result.RowsAffected() + if n > 0 { + slog.Info("cleaned up expired sessions", "count", n) + } + } + } +} diff --git a/internal/store/settings.go b/internal/store/settings.go new file mode 100644 index 0000000..894c2f4 --- /dev/null +++ b/internal/store/settings.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "database/sql" + "fmt" + "time" + + "kode.naiv.no/olemd/favoritter/internal/model" +) + +type SettingsStore struct { + db *sql.DB +} + +func NewSettingsStore(db *sql.DB) *SettingsStore { + return &SettingsStore{db: db} +} + +// Get returns the current site settings. +func (s *SettingsStore) Get() (*model.SiteSettings, error) { + var settings model.SiteSettings + var updatedAt string + err := s.db.QueryRow( + `SELECT site_name, site_description, signup_mode, updated_at + FROM site_settings WHERE id = 1`, + ).Scan(&settings.SiteName, &settings.SiteDescription, &settings.SignupMode, &updatedAt) + if err != nil { + return nil, fmt.Errorf("query site settings: %w", err) + } + + settings.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt) + return &settings, nil +} + +// Update updates the site settings. +func (s *SettingsStore) Update(siteName, siteDescription, signupMode string) error { + _, err := s.db.Exec( + `UPDATE site_settings SET site_name = ?, site_description = ?, signup_mode = ?, + updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + WHERE id = 1`, + siteName, siteDescription, signupMode, + ) + return err +} diff --git a/internal/store/signup_request.go b/internal/store/signup_request.go new file mode 100644 index 0000000..15fcdd5 --- /dev/null +++ b/internal/store/signup_request.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "database/sql" + "errors" + "fmt" + "strings" +) + +var ErrSignupRequestExists = errors.New("signup request already exists") + +type SignupRequestStore struct { + db *sql.DB +} + +func NewSignupRequestStore(db *sql.DB) *SignupRequestStore { + return &SignupRequestStore{db: db} +} + +// Create stores a pending signup request with a hashed password. +func (s *SignupRequestStore) Create(username, password string) error { + hash, err := hashPassword(password) + if err != nil { + return fmt.Errorf("hash password: %w", err) + } + + _, err = s.db.Exec( + `INSERT INTO signup_requests (username, password_hash) VALUES (?, ?)`, + username, hash, + ) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE constraint failed") { + return ErrSignupRequestExists + } + return fmt.Errorf("insert signup request: %w", err) + } + return nil +} + +// PendingCount returns the number of pending signup requests. +func (s *SignupRequestStore) PendingCount() (int, error) { + var n int + err := s.db.QueryRow("SELECT COUNT(*) FROM signup_requests WHERE status = 'pending'").Scan(&n) + return n, err +} diff --git a/internal/store/tag.go b/internal/store/tag.go new file mode 100644 index 0000000..7c33804 --- /dev/null +++ b/internal/store/tag.go @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "database/sql" + "errors" + "fmt" + "strings" + + "kode.naiv.no/olemd/favoritter/internal/model" +) + +const ( + MaxTagsPerFave = 20 + MaxTagLength = 50 +) + +var ErrTagNotFound = errors.New("tag not found") + +type TagStore struct { + db *sql.DB +} + +func NewTagStore(db *sql.DB) *TagStore { + return &TagStore{db: db} +} + +// Search returns tags matching a prefix query, for autocomplete. +// Results are ordered by how many faves use each tag (most popular first). +func (s *TagStore) Search(query string, limit int) ([]model.Tag, error) { + query = strings.TrimSpace(strings.ToLower(query)) + if query == "" { + return nil, nil + } + + rows, err := s.db.Query( + `SELECT t.id, t.name + FROM tags t + LEFT JOIN fave_tags ft ON ft.tag_id = t.id + WHERE t.name LIKE ? || '%' + GROUP BY t.id + ORDER BY COUNT(ft.fave_id) DESC, t.name COLLATE NOCASE + LIMIT ?`, + query, limit, + ) + if err != nil { + return nil, fmt.Errorf("search tags: %w", err) + } + defer rows.Close() + return scanTags(rows) +} + +func scanTags(rows *sql.Rows) ([]model.Tag, error) { + var tags []model.Tag + for rows.Next() { + var t model.Tag + if err := rows.Scan(&t.ID, &t.Name); err != nil { + return nil, err + } + tags = append(tags, t) + } + return tags, rows.Err() +} + +// GetOrCreate returns an existing tag by name, or creates it if it doesn't exist. +// Tag names are normalized to lowercase and trimmed. +func (s *TagStore) GetOrCreate(name string) (*model.Tag, error) { + name = NormalizeTagName(name) + if name == "" { + return nil, fmt.Errorf("empty tag name") + } + if len(name) > MaxTagLength { + return nil, fmt.Errorf("tag name too long (max %d characters)", MaxTagLength) + } + + // Try to find existing tag first (COLLATE NOCASE handles case). + var tag model.Tag + err := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name) + if err == nil { + return &tag, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return nil, err + } + + // Create new tag. + result, err := s.db.Exec("INSERT INTO tags (name) VALUES (?)", name) + if err != nil { + // Race condition: another request may have created it. + if strings.Contains(err.Error(), "UNIQUE constraint failed") { + err2 := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name) + if err2 != nil { + return nil, err2 + } + return &tag, nil + } + return nil, err + } + + tag.ID, _ = result.LastInsertId() + tag.Name = name + return &tag, nil +} + +// GetByID returns a tag by ID. +func (s *TagStore) GetByID(id int64) (*model.Tag, error) { + var tag model.Tag + err := s.db.QueryRow("SELECT id, name FROM tags WHERE id = ?", id).Scan(&tag.ID, &tag.Name) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrTagNotFound + } + return &tag, err +} + +// GetByName returns a tag by its name (case-insensitive). +func (s *TagStore) GetByName(name string) (*model.Tag, error) { + var tag model.Tag + err := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrTagNotFound + } + return &tag, err +} + +// AttachToFave links a tag to a fave. No-op if already attached. +func (s *TagStore) AttachToFave(faveID, tagID int64) error { + _, err := s.db.Exec( + "INSERT OR IGNORE INTO fave_tags (fave_id, tag_id) VALUES (?, ?)", + faveID, tagID, + ) + return err +} + +// DetachFromFave removes a tag from a fave. +func (s *TagStore) DetachFromFave(faveID, tagID int64) error { + _, err := s.db.Exec( + "DELETE FROM fave_tags WHERE fave_id = ? AND tag_id = ?", + faveID, tagID, + ) + return err +} + +// SetFaveTags replaces all tags on a fave with the given tag names. +// Creates new tags as needed. Enforces MaxTagsPerFave. +func (s *TagStore) SetFaveTags(faveID int64, tagNames []string) error { + if len(tagNames) > MaxTagsPerFave { + tagNames = tagNames[:MaxTagsPerFave] + } + + // Remove all existing tags for this fave. + if _, err := s.db.Exec("DELETE FROM fave_tags WHERE fave_id = ?", faveID); err != nil { + return err + } + + // Attach new tags. + for _, name := range tagNames { + name = NormalizeTagName(name) + if name == "" { + continue + } + + tag, err := s.GetOrCreate(name) + if err != nil { + return fmt.Errorf("get or create tag %q: %w", name, err) + } + + if err := s.AttachToFave(faveID, tag.ID); err != nil { + return fmt.Errorf("attach tag %q: %w", name, err) + } + } + + return nil +} + +// ForFave returns all tags attached to a fave. +func (s *TagStore) ForFave(faveID int64) ([]model.Tag, error) { + rows, err := s.db.Query( + `SELECT t.id, t.name FROM tags t + JOIN fave_tags ft ON ft.tag_id = t.id + WHERE ft.fave_id = ? + ORDER BY t.name COLLATE NOCASE`, + faveID, + ) + if err != nil { + return nil, err + } + defer rows.Close() + return scanTags(rows) +} + +// ListAll returns all tags ordered by name. +func (s *TagStore) ListAll() ([]model.Tag, error) { + rows, err := s.db.Query("SELECT id, name FROM tags ORDER BY name COLLATE NOCASE") + if err != nil { + return nil, err + } + defer rows.Close() + return scanTags(rows) +} + +// Rename changes a tag's name. Returns error if the new name already exists. +func (s *TagStore) Rename(id int64, newName string) error { + newName = NormalizeTagName(newName) + if newName == "" { + return fmt.Errorf("empty tag name") + } + _, err := s.db.Exec("UPDATE tags SET name = ? WHERE id = ?", newName, id) + return err +} + +// Delete removes a tag and all its fave associations (via cascade). +func (s *TagStore) Delete(id int64) error { + // fave_tags rows are cleaned up by ON DELETE CASCADE. + result, err := s.db.Exec("DELETE FROM tags WHERE id = ?", id) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n == 0 { + return ErrTagNotFound + } + return nil +} + +// CleanupOrphans removes tags that are not attached to any faves. +func (s *TagStore) CleanupOrphans() (int64, error) { + result, err := s.db.Exec( + `DELETE FROM tags WHERE id NOT IN (SELECT DISTINCT tag_id FROM fave_tags)`, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +// NormalizeTagName lowercases and trims a tag name. +func NormalizeTagName(name string) string { + return strings.TrimSpace(strings.ToLower(name)) +} diff --git a/internal/store/tag_test.go b/internal/store/tag_test.go new file mode 100644 index 0000000..1e967fd --- /dev/null +++ b/internal/store/tag_test.go @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "testing" +) + +func TestTagGetOrCreate(t *testing.T) { + db := testDB(t) + tags := NewTagStore(db) + + // Create a new tag. + tag1, err := tags.GetOrCreate("Film") + if err != nil { + t.Fatalf("get or create: %v", err) + } + if tag1.Name != "film" { + t.Errorf("name = %q, want %q (should be normalized to lowercase)", tag1.Name, "film") + } + + // Get the same tag again (case-insensitive). + tag2, err := tags.GetOrCreate("FILM") + if err != nil { + t.Fatalf("get or create duplicate: %v", err) + } + if tag2.ID != tag1.ID { + t.Errorf("duplicate tag got different ID: %d vs %d", tag2.ID, tag1.ID) + } +} + +func TestTagSearch(t *testing.T) { + db := testDB(t) + tags := NewTagStore(db) + users := NewUserStore(db) + faves := NewFaveStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { Argon2Memory = 65536; Argon2Time = 3 }() + + user, _ := users.Create("testuser", "password123", "user") + + // Create some tags via faves to give them usage counts. + f1, _ := faves.Create(user.ID, "F1", "", "", "public") + f2, _ := faves.Create(user.ID, "F2", "", "", "public") + + tags.SetFaveTags(f1.ID, []string{"music", "movies", "misc"}) + tags.SetFaveTags(f2.ID, []string{"music", "manga"}) + + // Search for "mu" should return "music" first (2 faves) then nothing else. + results, err := tags.Search("mu", 10) + if err != nil { + t.Fatalf("search: %v", err) + } + if len(results) != 1 { + t.Fatalf("search results = %d, want 1", len(results)) + } + if results[0].Name != "music" { + t.Errorf("first result = %q, want %q", results[0].Name, "music") + } + + // Search for "m" should return music (2), manga (1), misc (1), movies (1). + results, err = tags.Search("m", 10) + if err != nil { + t.Fatalf("search: %v", err) + } + if len(results) != 4 { + t.Errorf("search results = %d, want 4", len(results)) + } + // Music should be first due to highest usage count. + if results[0].Name != "music" { + t.Errorf("first result = %q, want %q (most used)", results[0].Name, "music") + } + + // Empty search returns nothing. + results, err = tags.Search("", 10) + if err != nil { + t.Fatalf("empty search: %v", err) + } + if len(results) != 0 { + t.Errorf("empty search results = %d, want 0", len(results)) + } +} + +func TestTagSetFaveTagsLimit(t *testing.T) { + db := testDB(t) + tags := NewTagStore(db) + users := NewUserStore(db) + faves := NewFaveStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { Argon2Memory = 65536; Argon2Time = 3 }() + + user, _ := users.Create("testuser", "password123", "user") + fave, _ := faves.Create(user.ID, "Test", "", "", "public") + + // Try to set more than MaxTagsPerFave tags. + manyTags := make([]string, 30) + for i := range manyTags { + manyTags[i] = "tag" + string(rune('a'+i%26)) + } + + err := tags.SetFaveTags(fave.ID, manyTags) + if err != nil { + t.Fatalf("set many tags: %v", err) + } + + attached, _ := tags.ForFave(fave.ID) + if len(attached) > MaxTagsPerFave { + t.Errorf("attached %d tags, max should be %d", len(attached), MaxTagsPerFave) + } +} + +func TestTagCleanupOrphans(t *testing.T) { + db := testDB(t) + tags := NewTagStore(db) + users := NewUserStore(db) + faves := NewFaveStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { Argon2Memory = 65536; Argon2Time = 3 }() + + user, _ := users.Create("testuser", "password123", "user") + fave, _ := faves.Create(user.ID, "Test", "", "", "public") + + tags.SetFaveTags(fave.ID, []string{"keep", "orphan"}) + + // Remove the fave — "keep" and "orphan" are now orphaned. + faves.Delete(fave.ID) + + removed, err := tags.CleanupOrphans() + if err != nil { + t.Fatalf("cleanup: %v", err) + } + if removed != 2 { + t.Errorf("removed = %d, want 2", removed) + } + + all, _ := tags.ListAll() + if len(all) != 0 { + t.Errorf("remaining tags = %d, want 0", len(all)) + } +} + +func TestTagRenameAndDelete(t *testing.T) { + db := testDB(t) + tags := NewTagStore(db) + + tag, _ := tags.GetOrCreate("oldname") + + err := tags.Rename(tag.ID, "NewName") + if err != nil { + t.Fatalf("rename: %v", err) + } + + renamed, _ := tags.GetByID(tag.ID) + if renamed.Name != "newname" { + t.Errorf("renamed = %q, want %q", renamed.Name, "newname") + } + + err = tags.Delete(tag.ID) + if err != nil { + t.Fatalf("delete: %v", err) + } + + _, err = tags.GetByID(tag.ID) + if err != ErrTagNotFound { + t.Errorf("deleted tag error = %v, want ErrTagNotFound", err) + } +} diff --git a/internal/store/user.go b/internal/store/user.go new file mode 100644 index 0000000..74e41b2 --- /dev/null +++ b/internal/store/user.go @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "crypto/rand" + "crypto/subtle" + "database/sql" + "encoding/base64" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "golang.org/x/crypto/argon2" + + "kode.naiv.no/olemd/favoritter/internal/model" +) + +// Argon2id parameters. Defaults match OWASP recommendations. +var ( + Argon2Memory uint32 = 65536 // 64 MB + Argon2Time uint32 = 3 + Argon2Parallelism uint8 = 2 + Argon2KeyLength uint32 = 32 + Argon2SaltLength = 16 +) + +var ( + ErrUserNotFound = errors.New("user not found") + ErrUserExists = errors.New("username already taken") + ErrUserDisabled = errors.New("user account is disabled") + ErrInvalidCredentials = errors.New("invalid username or password") +) + +type UserStore struct { + db *sql.DB +} + +func NewUserStore(db *sql.DB) *UserStore { + return &UserStore{db: db} +} + +// Create creates a new user with the given username and plaintext password. +func (s *UserStore) Create(username, password, role string) (*model.User, error) { + hash, err := hashPassword(password) + if err != nil { + return nil, fmt.Errorf("hash password: %w", err) + } + + result, err := s.db.Exec( + `INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)`, + username, hash, role, + ) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE constraint failed") { + return nil, ErrUserExists + } + return nil, fmt.Errorf("insert user: %w", err) + } + + id, _ := result.LastInsertId() + return s.GetByID(id) +} + +// CreateWithReset creates a new user that must reset their password on first login. +func (s *UserStore) CreateWithReset(username, tempPassword, role string) (*model.User, error) { + hash, err := hashPassword(tempPassword) + if err != nil { + return nil, fmt.Errorf("hash password: %w", err) + } + + result, err := s.db.Exec( + `INSERT INTO users (username, password_hash, role, must_reset_password) VALUES (?, ?, ?, 1)`, + username, hash, role, + ) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE constraint failed") { + return nil, ErrUserExists + } + return nil, fmt.Errorf("insert user: %w", err) + } + + id, _ := result.LastInsertId() + return s.GetByID(id) +} + +// Authenticate verifies credentials and returns the user if valid. +func (s *UserStore) Authenticate(username, password string) (*model.User, error) { + user, err := s.GetByUsername(username) + if err != nil { + if errors.Is(err, ErrUserNotFound) { + // Still do a dummy hash comparison to prevent timing attacks. + dummyHash(password) + return nil, ErrInvalidCredentials + } + return nil, err + } + + if user.Disabled { + return nil, ErrUserDisabled + } + + if !verifyPassword(password, user.PasswordHash) { + return nil, ErrInvalidCredentials + } + + return user, nil +} + +// GetByID retrieves a user by their ID. +func (s *UserStore) GetByID(id int64) (*model.User, error) { + return scanUserFrom(s.db.QueryRow( + `SELECT id, username, display_name, bio, avatar_path, password_hash, + role, profile_visibility, default_fave_privacy, + must_reset_password, disabled, created_at, updated_at + FROM users WHERE id = ?`, id, + )) +} + +// GetByUsername retrieves a user by their username (case-insensitive). +func (s *UserStore) GetByUsername(username string) (*model.User, error) { + return scanUserFrom(s.db.QueryRow( + `SELECT id, username, display_name, bio, avatar_path, password_hash, + role, profile_visibility, default_fave_privacy, + must_reset_password, disabled, created_at, updated_at + FROM users WHERE username = ?`, username, + )) +} + +// UpdatePassword changes a user's password and clears the must_reset_password flag. +func (s *UserStore) UpdatePassword(userID int64, newPassword string) error { + hash, err := hashPassword(newPassword) + if err != nil { + return fmt.Errorf("hash password: %w", err) + } + + _, err = s.db.Exec( + `UPDATE users SET password_hash = ?, must_reset_password = 0, + updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + WHERE id = ?`, + hash, userID, + ) + return err +} + +// UpdateProfile updates a user's profile fields. +func (s *UserStore) UpdateProfile(userID int64, displayName, bio, profileVisibility, defaultFavePrivacy string) error { + _, err := s.db.Exec( + `UPDATE users SET display_name = ?, bio = ?, profile_visibility = ?, + default_fave_privacy = ?, + updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + WHERE id = ?`, + displayName, bio, profileVisibility, defaultFavePrivacy, userID, + ) + return err +} + +// UpdateAvatar updates a user's avatar path. +func (s *UserStore) UpdateAvatar(userID int64, avatarPath string) error { + _, err := s.db.Exec( + `UPDATE users SET avatar_path = ?, + updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + WHERE id = ?`, + avatarPath, userID, + ) + return err +} + +// SetDisabled enables or disables a user account. +func (s *UserStore) SetDisabled(userID int64, disabled bool) error { + val := 0 + if disabled { + val = 1 + } + _, err := s.db.Exec( + `UPDATE users SET disabled = ?, + updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + WHERE id = ?`, + val, userID, + ) + return err +} + +// ListAll returns all users, ordered by username. +func (s *UserStore) ListAll() ([]*model.User, error) { + rows, err := s.db.Query( + `SELECT id, username, display_name, bio, avatar_path, password_hash, + role, profile_visibility, default_fave_privacy, + must_reset_password, disabled, created_at, updated_at + FROM users ORDER BY username COLLATE NOCASE`, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + var users []*model.User + for rows.Next() { + u, err := scanUserFrom(rows) + if err != nil { + return nil, err + } + users = append(users, u) + } + return users, rows.Err() +} + +// Count returns the total number of users. +func (s *UserStore) Count() (int, error) { + var n int + err := s.db.QueryRow("SELECT COUNT(*) FROM users").Scan(&n) + return n, err +} + +// EnsureAdmin creates the initial admin user if no users exist yet. +// This is called on startup with the configured admin credentials. +func (s *UserStore) EnsureAdmin(username, password string) error { + if username == "" || password == "" { + // No admin credentials configured — only skip if users already exist. + count, err := s.Count() + if err != nil { + return err + } + if count == 0 { + slog.Warn("no admin credentials configured and no users exist — set FAVORITTER_ADMIN_USERNAME and FAVORITTER_ADMIN_PASSWORD") + } + return nil + } + + // Check if this admin already exists. + _, err := s.GetByUsername(username) + if err == nil { + return nil // Already exists. + } + if !errors.Is(err, ErrUserNotFound) { + return err + } + + _, err = s.Create(username, password, "admin") + if err != nil { + return fmt.Errorf("create admin user: %w", err) + } + + slog.Info("created initial admin user", "username", username) + return nil +} + +// scanner is implemented by both *sql.Row and *sql.Rows. +type scanner interface { + Scan(dest ...any) error +} + +func scanUserFrom(s scanner) (*model.User, error) { + u := &model.User{} + var createdAt, updatedAt string + err := s.Scan( + &u.ID, &u.Username, &u.DisplayName, &u.Bio, &u.AvatarPath, + &u.PasswordHash, &u.Role, &u.ProfileVisibility, &u.DefaultFavePrivacy, + &u.MustResetPassword, &u.Disabled, &createdAt, &updatedAt, + ) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrUserNotFound + } + if err != nil { + return nil, fmt.Errorf("scan user: %w", err) + } + u.CreatedAt, _ = time.Parse(time.RFC3339, createdAt) + u.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt) + return u, nil +} + +// Password hashing with Argon2id. +// Format: $argon2id$v=19$m=65536,t=3,p=2$$ + +func hashPassword(password string) (string, error) { + salt := make([]byte, Argon2SaltLength) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("generate salt: %w", err) + } + + hash := argon2.IDKey([]byte(password), salt, Argon2Time, Argon2Memory, Argon2Parallelism, Argon2KeyLength) + + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, + Argon2Memory, Argon2Time, Argon2Parallelism, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(hash), + ), nil +} + +func verifyPassword(password, encodedHash string) bool { + parts := strings.Split(encodedHash, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return false + } + + var memory uint32 + var iterations uint32 + var parallelism uint8 + _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism) + if err != nil { + return false + } + + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + return false + } + + expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + return false + } + + hash := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expectedHash))) + + return subtle.ConstantTimeCompare(hash, expectedHash) == 1 +} + +// dummyHash performs a hash operation to prevent timing-based username enumeration. +func dummyHash(password string) { + salt := make([]byte, Argon2SaltLength) + argon2.IDKey([]byte(password), salt, Argon2Time, Argon2Memory, Argon2Parallelism, Argon2KeyLength) +} diff --git a/internal/store/user_test.go b/internal/store/user_test.go new file mode 100644 index 0000000..ec5f5f0 --- /dev/null +++ b/internal/store/user_test.go @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package store + +import ( + "database/sql" + "testing" + + _ "modernc.org/sqlite" + + "kode.naiv.no/olemd/favoritter/internal/database" +) + +func testDB(t *testing.T) *sql.DB { + t.Helper() + db, err := database.Open(":memory:") + if err != nil { + t.Fatalf("open test db: %v", err) + } + if err := database.Migrate(db); err != nil { + t.Fatalf("migrate test db: %v", err) + } + t.Cleanup(func() { db.Close() }) + return db +} + +func TestCreateAndAuthenticate(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + + // Use fast Argon2 parameters for tests. + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { + Argon2Memory = 65536 + Argon2Time = 3 + }() + + // Create a user. + user, err := users.Create("testuser", "password123", "user") + if err != nil { + t.Fatalf("create user: %v", err) + } + if user.Username != "testuser" { + t.Errorf("username = %q, want %q", user.Username, "testuser") + } + if user.Role != "user" { + t.Errorf("role = %q, want %q", user.Role, "user") + } + + // Authenticate with correct password. + authed, err := users.Authenticate("testuser", "password123") + if err != nil { + t.Fatalf("authenticate: %v", err) + } + if authed.ID != user.ID { + t.Errorf("authenticated user ID = %d, want %d", authed.ID, user.ID) + } + + // Authenticate with wrong password. + _, err = users.Authenticate("testuser", "wrongpassword") + if err != ErrInvalidCredentials { + t.Errorf("wrong password error = %v, want ErrInvalidCredentials", err) + } + + // Authenticate with non-existent user. + _, err = users.Authenticate("nouser", "password123") + if err != ErrInvalidCredentials { + t.Errorf("non-existent user error = %v, want ErrInvalidCredentials", err) + } +} + +func TestCreateDuplicate(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { + Argon2Memory = 65536 + Argon2Time = 3 + }() + + _, err := users.Create("testuser", "password123", "user") + if err != nil { + t.Fatalf("create user: %v", err) + } + + _, err = users.Create("testuser", "password456", "user") + if err != ErrUserExists { + t.Errorf("duplicate error = %v, want ErrUserExists", err) + } + + // Case-insensitive duplicate. + _, err = users.Create("TestUser", "password456", "user") + if err != ErrUserExists { + t.Errorf("case-insensitive duplicate error = %v, want ErrUserExists", err) + } +} + +func TestUpdatePassword(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { + Argon2Memory = 65536 + Argon2Time = 3 + }() + + user, err := users.CreateWithReset("admin", "temppass", "admin") + if err != nil { + t.Fatalf("create user: %v", err) + } + if !user.MustResetPassword { + t.Error("expected must_reset_password to be true") + } + + err = users.UpdatePassword(user.ID, "newpassword123") + if err != nil { + t.Fatalf("update password: %v", err) + } + + // Verify old password no longer works. + _, err = users.Authenticate("admin", "temppass") + if err != ErrInvalidCredentials { + t.Error("old password should not work after reset") + } + + // Verify new password works and reset flag is cleared. + updated, err := users.Authenticate("admin", "newpassword123") + if err != nil { + t.Fatalf("authenticate with new password: %v", err) + } + if updated.MustResetPassword { + t.Error("must_reset_password should be false after update") + } +} + +func TestEnsureAdmin(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { + Argon2Memory = 65536 + Argon2Time = 3 + }() + + // First call creates the admin. + err := users.EnsureAdmin("admin", "adminpass") + if err != nil { + t.Fatalf("ensure admin: %v", err) + } + + admin, err := users.GetByUsername("admin") + if err != nil { + t.Fatalf("get admin: %v", err) + } + if !admin.IsAdmin() { + t.Error("expected admin role") + } + + // Second call is a no-op. + err = users.EnsureAdmin("admin", "adminpass") + if err != nil { + t.Fatalf("ensure admin (second call): %v", err) + } + + count, _ := users.Count() + if count != 1 { + t.Errorf("user count = %d, want 1", count) + } +} + +func TestDisabledUser(t *testing.T) { + db := testDB(t) + users := NewUserStore(db) + + Argon2Memory = 1024 + Argon2Time = 1 + defer func() { + Argon2Memory = 65536 + Argon2Time = 3 + }() + + user, err := users.Create("testuser", "password123", "user") + if err != nil { + t.Fatalf("create user: %v", err) + } + + // Disable the user. + err = users.SetDisabled(user.ID, true) + if err != nil { + t.Fatalf("disable user: %v", err) + } + + // Authentication should fail. + _, err = users.Authenticate("testuser", "password123") + if err != ErrUserDisabled { + t.Errorf("disabled user error = %v, want ErrUserDisabled", err) + } +} diff --git a/web/embed.go b/web/embed.go new file mode 100644 index 0000000..0d5d76f --- /dev/null +++ b/web/embed.go @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package web embeds static assets and templates into the binary. +package web + +import "embed" + +//go:embed templates +var TemplatesFS embed.FS + +//go:embed static +var StaticFS embed.FS diff --git a/web/static/css/style.css b/web/static/css/style.css new file mode 100644 index 0000000..fa55f47 --- /dev/null +++ b/web/static/css/style.css @@ -0,0 +1,162 @@ +/* Favoritter — custom styles on top of Pico CSS */ + +/* Skip navigation link for accessibility */ +.skip-link { + position: absolute; + top: -100%; + left: 0; + padding: 0.5rem 1rem; + background: var(--pico-primary-background); + color: var(--pico-primary-inverse); + z-index: 1000; + text-decoration: none; +} + +.skip-link:focus { + top: 0; +} + +/* Inline forms (e.g. logout button in nav) */ +.inline-form { + display: inline; + margin: 0; + padding: 0; +} + +.nav-button { + margin: 0; + padding: 0.25rem 0.75rem; + font-size: 0.875rem; +} + +/* Flash messages */ +.flash { + padding: 1rem; + border-radius: var(--pico-border-radius); + margin-bottom: 1rem; +} + +.flash-success { + background: color-mix(in srgb, var(--pico-ins-color) 15%, transparent); + border: 1px solid var(--pico-ins-color); +} + +.flash-error { + background: color-mix(in srgb, var(--pico-del-color) 15%, transparent); + border: 1px solid var(--pico-del-color); +} + +.flash-info { + background: color-mix(in srgb, var(--pico-primary) 10%, transparent); + border: 1px solid var(--pico-primary); +} + +/* Fave card grid */ +.fave-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 1rem; + list-style: none; + padding: 0; +} + +.fave-card { + margin: 0; +} + +.fave-card img { + width: 100%; + height: 200px; + object-fit: cover; + border-radius: var(--pico-border-radius) var(--pico-border-radius) 0 0; +} + +.fave-card header { + padding: 0.5rem 1rem 0; +} + +.fave-card footer { + padding: 0 1rem 0.5rem; +} + +/* Privacy badge */ +.badge-private { + background: var(--pico-muted-border-color); + padding: 0.1rem 0.4rem; + border-radius: var(--pico-border-radius); + font-size: 0.75rem; + vertical-align: middle; +} + +/* Tag chips */ +.tag-chip { + display: inline-block; + background: var(--pico-primary-focus); + color: var(--pico-primary); + padding: 0.15rem 0.5rem; + border-radius: 1rem; + font-size: 0.8rem; + text-decoration: none; + margin: 0.1rem; +} + +.tag-chip:hover { + background: var(--pico-primary); + color: var(--pico-primary-inverse); +} + +/* Tag autocomplete suggestions */ +.tag-suggestions { + list-style: none; + padding: 0; + margin: 0; + border: 1px solid var(--pico-muted-border-color); + border-radius: var(--pico-border-radius); + max-height: 200px; + overflow-y: auto; +} + +.tag-suggestions:empty { + display: none; +} + +.tag-suggestion { + padding: 0.5rem 0.75rem; + cursor: pointer; +} + +.tag-suggestion:hover, +.tag-suggestion:focus { + background: var(--pico-primary-focus); + outline: none; +} + +/* Fave detail actions */ +.fave-actions { + display: flex; + gap: 0.5rem; + margin-top: 0.5rem; +} + +.fave-actions a, +.fave-actions button { + margin: 0; +} + +/* Current image preview in edit form */ +.current-image { + margin-bottom: 1rem; +} + +.current-image img { + border-radius: var(--pico-border-radius); +} + +/* Respect reduced motion preference */ +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} diff --git a/web/static/js/app.js b/web/static/js/app.js new file mode 100644 index 0000000..8d2ad83 --- /dev/null +++ b/web/static/js/app.js @@ -0,0 +1,71 @@ +// Favoritter — minimal JavaScript for HTMX configuration and form helpers. +// SPDX-License-Identifier: AGPL-3.0-or-later + +(function () { + "use strict"; + + // Auto-include the CSRF token in all HTMX requests. + document.body.addEventListener("htmx:configRequest", function (event) { + var csrfCookie = getCookie("csrf_token"); + if (csrfCookie) { + event.detail.headers["X-CSRF-Token"] = csrfCookie; + } + + // For the tag search input, send the current value of the last + // comma-separated segment as the 'q' parameter. + var elt = event.detail.elt; + if (elt && elt.id === "tags") { + var val = elt.value; + var parts = val.split(","); + var lastPart = parts[parts.length - 1].trim(); + event.detail.parameters["q"] = lastPart; + } + }); + + // Focus management after HTMX content swaps for accessibility. + document.body.addEventListener("htmx:afterSwap", function (event) { + var target = event.detail.target; + if (target) { + var autoFocus = target.querySelector("[autofocus]"); + if (autoFocus) { + autoFocus.focus(); + } + } + }); + + // After a successful HTMX DELETE, redirect if the element has a data-redirect attribute. + document.body.addEventListener("htmx:afterRequest", function (event) { + if (event.detail.successful && event.detail.verb === "delete") { + var redirect = event.detail.elt.getAttribute("data-redirect"); + if (redirect) { + window.location.href = redirect; + } + } + }); + + // Tag autocomplete: add a selected tag to the tag input. + window.addTag = function (element, tagName) { + var input = document.getElementById("tags"); + if (!input) return; + + var parts = input.value.split(",").map(function (s) { return s.trim(); }); + // Replace the last (incomplete) segment with the selected tag. + parts[parts.length - 1] = tagName; + // Add a trailing separator so the user can keep typing. + input.value = parts.join(", ") + ", "; + input.focus(); + + // Clear suggestions by removing all child elements. + var suggestions = document.getElementById("tag-suggestions"); + if (suggestions) { + while (suggestions.firstChild) { + suggestions.removeChild(suggestions.firstChild); + } + } + }; + + function getCookie(name) { + var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)")); + return match ? match[2] : null; + } +})(); diff --git a/web/static/vendor/htmx.min.js b/web/static/vendor/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/web/static/vendor/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/web/static/vendor/pico.min.css b/web/static/vendor/pico.min.css new file mode 100644 index 0000000..e10ec26 --- /dev/null +++ b/web/static/vendor/pico.min.css @@ -0,0 +1,4 @@ +@charset "UTF-8";/*! + * Pico CSS ✨ v2.1.1 (https://picocss.com) + * Copyright 2019-2025 - Licensed under MIT + */:host,:root{--pico-font-family-emoji:"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--pico-font-family-sans-serif:system-ui,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,Helvetica,Arial,"Helvetica Neue",sans-serif,var(--pico-font-family-emoji);--pico-font-family-monospace:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace,var(--pico-font-family-emoji);--pico-font-family:var(--pico-font-family-sans-serif);--pico-line-height:1.5;--pico-font-weight:400;--pico-font-size:100%;--pico-text-underline-offset:0.1rem;--pico-border-radius:0.25rem;--pico-border-width:0.0625rem;--pico-outline-width:0.125rem;--pico-transition:0.2s ease-in-out;--pico-spacing:1rem;--pico-typography-spacing-vertical:1rem;--pico-block-spacing-vertical:var(--pico-spacing);--pico-block-spacing-horizontal:var(--pico-spacing);--pico-grid-column-gap:var(--pico-spacing);--pico-grid-row-gap:var(--pico-spacing);--pico-form-element-spacing-vertical:0.75rem;--pico-form-element-spacing-horizontal:1rem;--pico-group-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-primary-focus);--pico-group-box-shadow-focus-with-input:0 0 0 0.0625rem var(--pico-form-element-border-color);--pico-modal-overlay-backdrop-filter:blur(0.375rem);--pico-nav-element-spacing-vertical:1rem;--pico-nav-element-spacing-horizontal:0.5rem;--pico-nav-link-spacing-vertical:0.5rem;--pico-nav-link-spacing-horizontal:0.5rem;--pico-nav-breadcrumb-divider:">";--pico-icon-checkbox:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-minus:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='5' y1='12' x2='19' y2='12'%3E%3C/line%3E%3C/svg%3E");--pico-icon-chevron:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-date:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='16' y1='2' x2='16' y2='6'%3E%3C/line%3E%3Cline x1='8' y1='2' x2='8' y2='6'%3E%3C/line%3E%3Cline x1='3' y1='10' x2='21' y2='10'%3E%3C/line%3E%3C/svg%3E");--pico-icon-time:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-search:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");--pico-icon-close:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='18' y1='6' x2='6' y2='18'%3E%3C/line%3E%3Cline x1='6' y1='6' x2='18' y2='18'%3E%3C/line%3E%3C/svg%3E");--pico-icon-loading:url("data:image/svg+xml,%3Csvg fill='none' height='24' width='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' %3E%3Cstyle%3E g %7B animation: rotate 2s linear infinite; transform-origin: center center; %7D circle %7B stroke-dasharray: 75,100; stroke-dashoffset: -5; animation: dash 1.5s ease-in-out infinite; stroke-linecap: round; %7D @keyframes rotate %7B 0%25 %7B transform: rotate(0deg); %7D 100%25 %7B transform: rotate(360deg); %7D %7D @keyframes dash %7B 0%25 %7B stroke-dasharray: 1,100; stroke-dashoffset: 0; %7D 50%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -17.5; %7D 100%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -62; %7D %7D %3C/style%3E%3Cg%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='rgb(136, 145, 164)' stroke-width='4' /%3E%3C/g%3E%3C/svg%3E")}@media (min-width:576px){:host,:root{--pico-font-size:106.25%}}@media (min-width:768px){:host,:root{--pico-font-size:112.5%}}@media (min-width:1024px){:host,:root{--pico-font-size:118.75%}}@media (min-width:1280px){:host,:root{--pico-font-size:125%}}@media (min-width:1536px){:host,:root{--pico-font-size:131.25%}}a{--pico-text-decoration:underline}a.contrast,a.secondary{--pico-text-decoration:underline}small{--pico-font-size:0.875em}h1,h2,h3,h4,h5,h6{--pico-font-weight:700}h1{--pico-font-size:2rem;--pico-line-height:1.125;--pico-typography-spacing-top:3rem}h2{--pico-font-size:1.75rem;--pico-line-height:1.15;--pico-typography-spacing-top:2.625rem}h3{--pico-font-size:1.5rem;--pico-line-height:1.175;--pico-typography-spacing-top:2.25rem}h4{--pico-font-size:1.25rem;--pico-line-height:1.2;--pico-typography-spacing-top:1.874rem}h5{--pico-font-size:1.125rem;--pico-line-height:1.225;--pico-typography-spacing-top:1.6875rem}h6{--pico-font-size:1rem;--pico-line-height:1.25;--pico-typography-spacing-top:1.5rem}tfoot td,tfoot th,thead td,thead th{--pico-font-weight:600;--pico-border-width:0.1875rem}code,kbd,pre,samp{--pico-font-family:var(--pico-font-family-monospace)}kbd{--pico-font-weight:bolder}:where(select,textarea),input:not([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-outline-width:0.0625rem}[type=search]{--pico-border-radius:5rem}[type=checkbox],[type=radio]{--pico-border-width:0.125rem}[type=checkbox][role=switch]{--pico-border-width:0.1875rem}details.dropdown summary:not([role=button]){--pico-outline-width:0.0625rem}nav details.dropdown summary:focus-visible{--pico-outline-width:0.125rem}[role=search]{--pico-border-radius:5rem}[role=group]:has(button.secondary:focus,[type=submit].secondary:focus,[type=button].secondary:focus,[role=button].secondary:focus),[role=search]:has(button.secondary:focus,[type=submit].secondary:focus,[type=button].secondary:focus,[role=button].secondary:focus){--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-secondary-focus)}[role=group]:has(button.contrast:focus,[type=submit].contrast:focus,[type=button].contrast:focus,[role=button].contrast:focus),[role=search]:has(button.contrast:focus,[type=submit].contrast:focus,[type=button].contrast:focus,[role=button].contrast:focus){--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-contrast-focus)}[role=group] [role=button],[role=group] [type=button],[role=group] [type=submit],[role=group] button,[role=search] [role=button],[role=search] [type=button],[role=search] [type=submit],[role=search] button{--pico-form-element-spacing-horizontal:2rem}details summary[role=button]:not(.outline)::after{filter:brightness(0) invert(1)}[aria-busy=true]:not(input,select,textarea):is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before{filter:brightness(0) invert(1)}:host(:not([data-theme=dark])),:root:not([data-theme=dark]),[data-theme=light]{color-scheme:light;--pico-background-color:#fff;--pico-color:#373c44;--pico-text-selection-color:rgba(2, 154, 232, 0.25);--pico-muted-color:#646b79;--pico-muted-border-color:rgb(231, 234, 239.5);--pico-primary:#0172ad;--pico-primary-background:#0172ad;--pico-primary-border:var(--pico-primary-background);--pico-primary-underline:rgba(1, 114, 173, 0.5);--pico-primary-hover:#015887;--pico-primary-hover-background:#02659a;--pico-primary-hover-border:var(--pico-primary-hover-background);--pico-primary-hover-underline:var(--pico-primary-hover);--pico-primary-focus:rgba(2, 154, 232, 0.5);--pico-primary-inverse:#fff;--pico-secondary:#5d6b89;--pico-secondary-background:#525f7a;--pico-secondary-border:var(--pico-secondary-background);--pico-secondary-underline:rgba(93, 107, 137, 0.5);--pico-secondary-hover:#48536b;--pico-secondary-hover-background:#48536b;--pico-secondary-hover-border:var(--pico-secondary-hover-background);--pico-secondary-hover-underline:var(--pico-secondary-hover);--pico-secondary-focus:rgba(93, 107, 137, 0.25);--pico-secondary-inverse:#fff;--pico-contrast:#181c25;--pico-contrast-background:#181c25;--pico-contrast-border:var(--pico-contrast-background);--pico-contrast-underline:rgba(24, 28, 37, 0.5);--pico-contrast-hover:#000;--pico-contrast-hover-background:#000;--pico-contrast-hover-border:var(--pico-contrast-hover-background);--pico-contrast-hover-underline:var(--pico-secondary-hover);--pico-contrast-focus:rgba(93, 107, 137, 0.25);--pico-contrast-inverse:#fff;--pico-box-shadow:0.0145rem 0.029rem 0.174rem rgba(129, 145, 181, 0.01698),0.0335rem 0.067rem 0.402rem rgba(129, 145, 181, 0.024),0.0625rem 0.125rem 0.75rem rgba(129, 145, 181, 0.03),0.1125rem 0.225rem 1.35rem rgba(129, 145, 181, 0.036),0.2085rem 0.417rem 2.502rem rgba(129, 145, 181, 0.04302),0.5rem 1rem 6rem rgba(129, 145, 181, 0.06),0 0 0 0.0625rem rgba(129, 145, 181, 0.015);--pico-h1-color:#2d3138;--pico-h2-color:#373c44;--pico-h3-color:#424751;--pico-h4-color:#4d535e;--pico-h5-color:#5c6370;--pico-h6-color:#646b79;--pico-mark-background-color:rgb(252.5, 230.5, 191.5);--pico-mark-color:#0f1114;--pico-ins-color:rgb(28.5, 105.5, 84);--pico-del-color:rgb(136, 56.5, 53);--pico-blockquote-border-color:var(--pico-muted-border-color);--pico-blockquote-footer-color:var(--pico-muted-color);--pico-button-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-button-hover-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-table-border-color:var(--pico-muted-border-color);--pico-table-row-stripped-background-color:rgba(111, 120, 135, 0.0375);--pico-code-background-color:rgb(243, 244.5, 246.75);--pico-code-color:#646b79;--pico-code-kbd-background-color:var(--pico-color);--pico-code-kbd-color:var(--pico-background-color);--pico-form-element-background-color:rgb(251, 251.5, 252.25);--pico-form-element-selected-background-color:#dfe3eb;--pico-form-element-border-color:#cfd5e2;--pico-form-element-color:#23262c;--pico-form-element-placeholder-color:var(--pico-muted-color);--pico-form-element-active-background-color:#fff;--pico-form-element-active-border-color:var(--pico-primary-border);--pico-form-element-focus-color:var(--pico-primary-border);--pico-form-element-disabled-opacity:0.5;--pico-form-element-invalid-border-color:rgb(183.5, 105.5, 106.5);--pico-form-element-invalid-active-border-color:rgb(200.25, 79.25, 72.25);--pico-form-element-invalid-focus-color:var(--pico-form-element-invalid-active-border-color);--pico-form-element-valid-border-color:rgb(76, 154.5, 137.5);--pico-form-element-valid-active-border-color:rgb(39, 152.75, 118.75);--pico-form-element-valid-focus-color:var(--pico-form-element-valid-active-border-color);--pico-switch-background-color:#bfc7d9;--pico-switch-checked-background-color:var(--pico-primary-background);--pico-switch-color:#fff;--pico-switch-thumb-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-range-border-color:#dfe3eb;--pico-range-active-border-color:#bfc7d9;--pico-range-thumb-border-color:var(--pico-background-color);--pico-range-thumb-color:var(--pico-secondary-background);--pico-range-thumb-active-color:var(--pico-primary-background);--pico-accordion-border-color:var(--pico-muted-border-color);--pico-accordion-active-summary-color:var(--pico-primary-hover);--pico-accordion-close-summary-color:var(--pico-color);--pico-accordion-open-summary-color:var(--pico-muted-color);--pico-card-background-color:var(--pico-background-color);--pico-card-border-color:var(--pico-muted-border-color);--pico-card-box-shadow:var(--pico-box-shadow);--pico-card-sectioning-background-color:rgb(251, 251.5, 252.25);--pico-dropdown-background-color:#fff;--pico-dropdown-border-color:#eff1f4;--pico-dropdown-box-shadow:var(--pico-box-shadow);--pico-dropdown-color:var(--pico-color);--pico-dropdown-hover-background-color:#eff1f4;--pico-loading-spinner-opacity:0.5;--pico-modal-overlay-background-color:rgba(232, 234, 237, 0.75);--pico-progress-background-color:#dfe3eb;--pico-progress-color:var(--pico-primary-background);--pico-tooltip-background-color:var(--pico-contrast-background);--pico-tooltip-color:var(--pico-contrast-inverse);--pico-icon-valid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-invalid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(200.25, 79.25, 72.25)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E")}:host(:not([data-theme=dark])) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]),:root:not([data-theme=dark]) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]),[data-theme=light] input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-form-element-focus-color:var(--pico-primary-focus)}@media only screen and (prefers-color-scheme:dark){:host(:not([data-theme])),:root:not([data-theme]){color-scheme:dark;--pico-background-color:rgb(19, 22.5, 30.5);--pico-color:#c2c7d0;--pico-text-selection-color:rgba(1, 170, 255, 0.1875);--pico-muted-color:#7b8495;--pico-muted-border-color:#202632;--pico-primary:#01aaff;--pico-primary-background:#0172ad;--pico-primary-border:var(--pico-primary-background);--pico-primary-underline:rgba(1, 170, 255, 0.5);--pico-primary-hover:#79c0ff;--pico-primary-hover-background:#017fc0;--pico-primary-hover-border:var(--pico-primary-hover-background);--pico-primary-hover-underline:var(--pico-primary-hover);--pico-primary-focus:rgba(1, 170, 255, 0.375);--pico-primary-inverse:#fff;--pico-secondary:#969eaf;--pico-secondary-background:#525f7a;--pico-secondary-border:var(--pico-secondary-background);--pico-secondary-underline:rgba(150, 158, 175, 0.5);--pico-secondary-hover:#b3b9c5;--pico-secondary-hover-background:#5d6b89;--pico-secondary-hover-border:var(--pico-secondary-hover-background);--pico-secondary-hover-underline:var(--pico-secondary-hover);--pico-secondary-focus:rgba(144, 158, 190, 0.25);--pico-secondary-inverse:#fff;--pico-contrast:#dfe3eb;--pico-contrast-background:#eff1f4;--pico-contrast-border:var(--pico-contrast-background);--pico-contrast-underline:rgba(223, 227, 235, 0.5);--pico-contrast-hover:#fff;--pico-contrast-hover-background:#fff;--pico-contrast-hover-border:var(--pico-contrast-hover-background);--pico-contrast-hover-underline:var(--pico-contrast-hover);--pico-contrast-focus:rgba(207, 213, 226, 0.25);--pico-contrast-inverse:#000;--pico-box-shadow:0.0145rem 0.029rem 0.174rem rgba(7, 8.5, 12, 0.01698),0.0335rem 0.067rem 0.402rem rgba(7, 8.5, 12, 0.024),0.0625rem 0.125rem 0.75rem rgba(7, 8.5, 12, 0.03),0.1125rem 0.225rem 1.35rem rgba(7, 8.5, 12, 0.036),0.2085rem 0.417rem 2.502rem rgba(7, 8.5, 12, 0.04302),0.5rem 1rem 6rem rgba(7, 8.5, 12, 0.06),0 0 0 0.0625rem rgba(7, 8.5, 12, 0.015);--pico-h1-color:#f0f1f3;--pico-h2-color:#e0e3e7;--pico-h3-color:#c2c7d0;--pico-h4-color:#b3b9c5;--pico-h5-color:#a4acba;--pico-h6-color:#8891a4;--pico-mark-background-color:#014063;--pico-mark-color:#fff;--pico-ins-color:#62af9a;--pico-del-color:rgb(205.5, 126, 123);--pico-blockquote-border-color:var(--pico-muted-border-color);--pico-blockquote-footer-color:var(--pico-muted-color);--pico-button-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-button-hover-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-table-border-color:var(--pico-muted-border-color);--pico-table-row-stripped-background-color:rgba(111, 120, 135, 0.0375);--pico-code-background-color:rgb(26, 30.5, 40.25);--pico-code-color:#8891a4;--pico-code-kbd-background-color:var(--pico-color);--pico-code-kbd-color:var(--pico-background-color);--pico-form-element-background-color:rgb(28, 33, 43.5);--pico-form-element-selected-background-color:#2a3140;--pico-form-element-border-color:#2a3140;--pico-form-element-color:#e0e3e7;--pico-form-element-placeholder-color:#8891a4;--pico-form-element-active-background-color:rgb(26, 30.5, 40.25);--pico-form-element-active-border-color:var(--pico-primary-border);--pico-form-element-focus-color:var(--pico-primary-border);--pico-form-element-disabled-opacity:0.5;--pico-form-element-invalid-border-color:rgb(149.5, 74, 80);--pico-form-element-invalid-active-border-color:rgb(183.25, 63.5, 59);--pico-form-element-invalid-focus-color:var(--pico-form-element-invalid-active-border-color);--pico-form-element-valid-border-color:#2a7b6f;--pico-form-element-valid-active-border-color:rgb(22, 137, 105.5);--pico-form-element-valid-focus-color:var(--pico-form-element-valid-active-border-color);--pico-switch-background-color:#333c4e;--pico-switch-checked-background-color:var(--pico-primary-background);--pico-switch-color:#fff;--pico-switch-thumb-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-range-border-color:#202632;--pico-range-active-border-color:#2a3140;--pico-range-thumb-border-color:var(--pico-background-color);--pico-range-thumb-color:var(--pico-secondary-background);--pico-range-thumb-active-color:var(--pico-primary-background);--pico-accordion-border-color:var(--pico-muted-border-color);--pico-accordion-active-summary-color:var(--pico-primary-hover);--pico-accordion-close-summary-color:var(--pico-color);--pico-accordion-open-summary-color:var(--pico-muted-color);--pico-card-background-color:#181c25;--pico-card-border-color:var(--pico-card-background-color);--pico-card-box-shadow:var(--pico-box-shadow);--pico-card-sectioning-background-color:rgb(26, 30.5, 40.25);--pico-dropdown-background-color:#181c25;--pico-dropdown-border-color:#202632;--pico-dropdown-box-shadow:var(--pico-box-shadow);--pico-dropdown-color:var(--pico-color);--pico-dropdown-hover-background-color:#202632;--pico-loading-spinner-opacity:0.5;--pico-modal-overlay-background-color:rgba(7.5, 8.5, 10, 0.75);--pico-progress-background-color:#202632;--pico-progress-color:var(--pico-primary-background);--pico-tooltip-background-color:var(--pico-contrast-background);--pico-tooltip-color:var(--pico-contrast-inverse);--pico-icon-valid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(42, 123, 111)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-invalid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(149.5, 74, 80)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E")}:host(:not([data-theme])) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]),:root:not([data-theme]) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-form-element-focus-color:var(--pico-primary-focus)}:host(:not([data-theme])) details summary[role=button].contrast:not(.outline)::after,:root:not([data-theme]) details summary[role=button].contrast:not(.outline)::after{filter:brightness(0)}:host(:not([data-theme])) [aria-busy=true]:not(input,select,textarea).contrast:is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before,:root:not([data-theme]) [aria-busy=true]:not(input,select,textarea).contrast:is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before{filter:brightness(0)}}[data-theme=dark]{color-scheme:dark;--pico-background-color:rgb(19, 22.5, 30.5);--pico-color:#c2c7d0;--pico-text-selection-color:rgba(1, 170, 255, 0.1875);--pico-muted-color:#7b8495;--pico-muted-border-color:#202632;--pico-primary:#01aaff;--pico-primary-background:#0172ad;--pico-primary-border:var(--pico-primary-background);--pico-primary-underline:rgba(1, 170, 255, 0.5);--pico-primary-hover:#79c0ff;--pico-primary-hover-background:#017fc0;--pico-primary-hover-border:var(--pico-primary-hover-background);--pico-primary-hover-underline:var(--pico-primary-hover);--pico-primary-focus:rgba(1, 170, 255, 0.375);--pico-primary-inverse:#fff;--pico-secondary:#969eaf;--pico-secondary-background:#525f7a;--pico-secondary-border:var(--pico-secondary-background);--pico-secondary-underline:rgba(150, 158, 175, 0.5);--pico-secondary-hover:#b3b9c5;--pico-secondary-hover-background:#5d6b89;--pico-secondary-hover-border:var(--pico-secondary-hover-background);--pico-secondary-hover-underline:var(--pico-secondary-hover);--pico-secondary-focus:rgba(144, 158, 190, 0.25);--pico-secondary-inverse:#fff;--pico-contrast:#dfe3eb;--pico-contrast-background:#eff1f4;--pico-contrast-border:var(--pico-contrast-background);--pico-contrast-underline:rgba(223, 227, 235, 0.5);--pico-contrast-hover:#fff;--pico-contrast-hover-background:#fff;--pico-contrast-hover-border:var(--pico-contrast-hover-background);--pico-contrast-hover-underline:var(--pico-contrast-hover);--pico-contrast-focus:rgba(207, 213, 226, 0.25);--pico-contrast-inverse:#000;--pico-box-shadow:0.0145rem 0.029rem 0.174rem rgba(7, 8.5, 12, 0.01698),0.0335rem 0.067rem 0.402rem rgba(7, 8.5, 12, 0.024),0.0625rem 0.125rem 0.75rem rgba(7, 8.5, 12, 0.03),0.1125rem 0.225rem 1.35rem rgba(7, 8.5, 12, 0.036),0.2085rem 0.417rem 2.502rem rgba(7, 8.5, 12, 0.04302),0.5rem 1rem 6rem rgba(7, 8.5, 12, 0.06),0 0 0 0.0625rem rgba(7, 8.5, 12, 0.015);--pico-h1-color:#f0f1f3;--pico-h2-color:#e0e3e7;--pico-h3-color:#c2c7d0;--pico-h4-color:#b3b9c5;--pico-h5-color:#a4acba;--pico-h6-color:#8891a4;--pico-mark-background-color:#014063;--pico-mark-color:#fff;--pico-ins-color:#62af9a;--pico-del-color:rgb(205.5, 126, 123);--pico-blockquote-border-color:var(--pico-muted-border-color);--pico-blockquote-footer-color:var(--pico-muted-color);--pico-button-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-button-hover-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-table-border-color:var(--pico-muted-border-color);--pico-table-row-stripped-background-color:rgba(111, 120, 135, 0.0375);--pico-code-background-color:rgb(26, 30.5, 40.25);--pico-code-color:#8891a4;--pico-code-kbd-background-color:var(--pico-color);--pico-code-kbd-color:var(--pico-background-color);--pico-form-element-background-color:rgb(28, 33, 43.5);--pico-form-element-selected-background-color:#2a3140;--pico-form-element-border-color:#2a3140;--pico-form-element-color:#e0e3e7;--pico-form-element-placeholder-color:#8891a4;--pico-form-element-active-background-color:rgb(26, 30.5, 40.25);--pico-form-element-active-border-color:var(--pico-primary-border);--pico-form-element-focus-color:var(--pico-primary-border);--pico-form-element-disabled-opacity:0.5;--pico-form-element-invalid-border-color:rgb(149.5, 74, 80);--pico-form-element-invalid-active-border-color:rgb(183.25, 63.5, 59);--pico-form-element-invalid-focus-color:var(--pico-form-element-invalid-active-border-color);--pico-form-element-valid-border-color:#2a7b6f;--pico-form-element-valid-active-border-color:rgb(22, 137, 105.5);--pico-form-element-valid-focus-color:var(--pico-form-element-valid-active-border-color);--pico-switch-background-color:#333c4e;--pico-switch-checked-background-color:var(--pico-primary-background);--pico-switch-color:#fff;--pico-switch-thumb-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-range-border-color:#202632;--pico-range-active-border-color:#2a3140;--pico-range-thumb-border-color:var(--pico-background-color);--pico-range-thumb-color:var(--pico-secondary-background);--pico-range-thumb-active-color:var(--pico-primary-background);--pico-accordion-border-color:var(--pico-muted-border-color);--pico-accordion-active-summary-color:var(--pico-primary-hover);--pico-accordion-close-summary-color:var(--pico-color);--pico-accordion-open-summary-color:var(--pico-muted-color);--pico-card-background-color:#181c25;--pico-card-border-color:var(--pico-card-background-color);--pico-card-box-shadow:var(--pico-box-shadow);--pico-card-sectioning-background-color:rgb(26, 30.5, 40.25);--pico-dropdown-background-color:#181c25;--pico-dropdown-border-color:#202632;--pico-dropdown-box-shadow:var(--pico-box-shadow);--pico-dropdown-color:var(--pico-color);--pico-dropdown-hover-background-color:#202632;--pico-loading-spinner-opacity:0.5;--pico-modal-overlay-background-color:rgba(7.5, 8.5, 10, 0.75);--pico-progress-background-color:#202632;--pico-progress-color:var(--pico-primary-background);--pico-tooltip-background-color:var(--pico-contrast-background);--pico-tooltip-color:var(--pico-contrast-inverse);--pico-icon-valid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(42, 123, 111)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-invalid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(149.5, 74, 80)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E")}[data-theme=dark] input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-form-element-focus-color:var(--pico-primary-focus)}[data-theme=dark] details summary[role=button].contrast:not(.outline)::after{filter:brightness(0)}[data-theme=dark] [aria-busy=true]:not(input,select,textarea).contrast:is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before{filter:brightness(0)}[type=checkbox],[type=radio],[type=range],progress{accent-color:var(--pico-primary)}*,::after,::before{box-sizing:border-box;background-repeat:no-repeat}::after,::before{text-decoration:inherit;vertical-align:inherit}:where(:host),:where(:root){-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:100%;-moz-text-size-adjust:100%;text-size-adjust:100%;background-color:var(--pico-background-color);color:var(--pico-color);font-weight:var(--pico-font-weight);font-size:var(--pico-font-size);line-height:var(--pico-line-height);font-family:var(--pico-font-family);text-underline-offset:var(--pico-text-underline-offset);text-rendering:optimizeLegibility;overflow-wrap:break-word;-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{width:100%;margin:0}main{display:block}body>footer,body>header,body>main{padding-block:var(--pico-block-spacing-vertical)}section{margin-bottom:var(--pico-block-spacing-vertical)}.container,.container-fluid{width:100%;margin-right:auto;margin-left:auto;padding-right:var(--pico-spacing);padding-left:var(--pico-spacing)}@media (min-width:576px){.container{max-width:510px;padding-right:0;padding-left:0}}@media (min-width:768px){.container{max-width:700px}}@media (min-width:1024px){.container{max-width:950px}}@media (min-width:1280px){.container{max-width:1200px}}@media (min-width:1536px){.container{max-width:1450px}}.grid{grid-column-gap:var(--pico-grid-column-gap);grid-row-gap:var(--pico-grid-row-gap);display:grid;grid-template-columns:1fr}@media (min-width:768px){.grid{grid-template-columns:repeat(auto-fit,minmax(0%,1fr))}}.grid>*{min-width:0}.overflow-auto{overflow:auto}b,strong{font-weight:bolder}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}address,blockquote,dl,ol,p,pre,table,ul{margin-top:0;margin-bottom:var(--pico-typography-spacing-vertical);color:var(--pico-color);font-style:normal;font-weight:var(--pico-font-weight)}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:var(--pico-typography-spacing-vertical);color:var(--pico-color);font-weight:var(--pico-font-weight);font-size:var(--pico-font-size);line-height:var(--pico-line-height);font-family:var(--pico-font-family)}h1{--pico-color:var(--pico-h1-color)}h2{--pico-color:var(--pico-h2-color)}h3{--pico-color:var(--pico-h3-color)}h4{--pico-color:var(--pico-h4-color)}h5{--pico-color:var(--pico-h5-color)}h6{--pico-color:var(--pico-h6-color)}:where(article,address,blockquote,dl,figure,form,ol,p,pre,table,ul)~:is(h1,h2,h3,h4,h5,h6){margin-top:var(--pico-typography-spacing-top)}p{margin-bottom:var(--pico-typography-spacing-vertical)}hgroup{margin-bottom:var(--pico-typography-spacing-vertical)}hgroup>*{margin-top:0;margin-bottom:0}hgroup>:not(:first-child):last-child{--pico-color:var(--pico-muted-color);--pico-font-weight:unset;font-size:1rem}:where(ol,ul) li{margin-bottom:calc(var(--pico-typography-spacing-vertical) * .25)}:where(dl,ol,ul) :where(dl,ol,ul){margin:0;margin-top:calc(var(--pico-typography-spacing-vertical) * .25)}ul li{list-style:square}mark{padding:.125rem .25rem;background-color:var(--pico-mark-background-color);color:var(--pico-mark-color);vertical-align:baseline}blockquote{display:block;margin:var(--pico-typography-spacing-vertical) 0;padding:var(--pico-spacing);border-right:none;border-left:.25rem solid var(--pico-blockquote-border-color);border-inline-start:0.25rem solid var(--pico-blockquote-border-color);border-inline-end:none}blockquote footer{margin-top:calc(var(--pico-typography-spacing-vertical) * .5);color:var(--pico-blockquote-footer-color)}abbr[title]{border-bottom:1px dotted;text-decoration:none;cursor:help}ins{color:var(--pico-ins-color);text-decoration:none}del{color:var(--pico-del-color)}::-moz-selection{background-color:var(--pico-text-selection-color)}::selection{background-color:var(--pico-text-selection-color)}:where(a:not([role=button])),[role=link]{--pico-color:var(--pico-primary);--pico-background-color:transparent;--pico-underline:var(--pico-primary-underline);outline:0;background-color:var(--pico-background-color);color:var(--pico-color);-webkit-text-decoration:var(--pico-text-decoration);text-decoration:var(--pico-text-decoration);text-decoration-color:var(--pico-underline);text-underline-offset:0.125em;transition:background-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition),-webkit-text-decoration var(--pico-transition);transition:background-color var(--pico-transition),color var(--pico-transition),text-decoration var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),color var(--pico-transition),text-decoration var(--pico-transition),box-shadow var(--pico-transition),-webkit-text-decoration var(--pico-transition)}:where(a:not([role=button])):is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[role=link]:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-primary-hover);--pico-underline:var(--pico-primary-hover-underline);--pico-text-decoration:underline}:where(a:not([role=button])):focus-visible,[role=link]:focus-visible{box-shadow:0 0 0 var(--pico-outline-width) var(--pico-primary-focus)}:where(a:not([role=button])).secondary,[role=link].secondary{--pico-color:var(--pico-secondary);--pico-underline:var(--pico-secondary-underline)}:where(a:not([role=button])).secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[role=link].secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-secondary-hover);--pico-underline:var(--pico-secondary-hover-underline)}:where(a:not([role=button])).contrast,[role=link].contrast{--pico-color:var(--pico-contrast);--pico-underline:var(--pico-contrast-underline)}:where(a:not([role=button])).contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[role=link].contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-contrast-hover);--pico-underline:var(--pico-contrast-hover-underline)}a[role=button]{display:inline-block}button{margin:0;overflow:visible;font-family:inherit;text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[role=button],[type=button],[type=file]::file-selector-button,[type=reset],[type=submit],button{--pico-background-color:var(--pico-primary-background);--pico-border-color:var(--pico-primary-border);--pico-color:var(--pico-primary-inverse);--pico-box-shadow:var(--pico-button-box-shadow, 0 0 0 rgba(0, 0, 0, 0));padding:var(--pico-form-element-spacing-vertical) var(--pico-form-element-spacing-horizontal);border:var(--pico-border-width) solid var(--pico-border-color);border-radius:var(--pico-border-radius);outline:0;background-color:var(--pico-background-color);box-shadow:var(--pico-box-shadow);color:var(--pico-color);font-weight:var(--pico-font-weight);font-size:1rem;line-height:var(--pico-line-height);text-align:center;text-decoration:none;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:background-color var(--pico-transition),border-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition)}[role=button]:is(:hover,:active,:focus),[role=button]:is([aria-current]:not([aria-current=false])),[type=button]:is(:hover,:active,:focus),[type=button]:is([aria-current]:not([aria-current=false])),[type=file]::file-selector-button:is(:hover,:active,:focus),[type=file]::file-selector-button:is([aria-current]:not([aria-current=false])),[type=reset]:is(:hover,:active,:focus),[type=reset]:is([aria-current]:not([aria-current=false])),[type=submit]:is(:hover,:active,:focus),[type=submit]:is([aria-current]:not([aria-current=false])),button:is(:hover,:active,:focus),button:is([aria-current]:not([aria-current=false])){--pico-background-color:var(--pico-primary-hover-background);--pico-border-color:var(--pico-primary-hover-border);--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0));--pico-color:var(--pico-primary-inverse)}[role=button]:focus,[role=button]:is([aria-current]:not([aria-current=false])):focus,[type=button]:focus,[type=button]:is([aria-current]:not([aria-current=false])):focus,[type=file]::file-selector-button:focus,[type=file]::file-selector-button:is([aria-current]:not([aria-current=false])):focus,[type=reset]:focus,[type=reset]:is([aria-current]:not([aria-current=false])):focus,[type=submit]:focus,[type=submit]:is([aria-current]:not([aria-current=false])):focus,button:focus,button:is([aria-current]:not([aria-current=false])):focus{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-primary-focus)}[type=button],[type=reset],[type=submit]{margin-bottom:var(--pico-spacing)}:is(button,[type=submit],[type=button],[role=button]).secondary,[type=file]::file-selector-button,[type=reset]{--pico-background-color:var(--pico-secondary-background);--pico-border-color:var(--pico-secondary-border);--pico-color:var(--pico-secondary-inverse);cursor:pointer}:is(button,[type=submit],[type=button],[role=button]).secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=file]::file-selector-button:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=reset]:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-background-color:var(--pico-secondary-hover-background);--pico-border-color:var(--pico-secondary-hover-border);--pico-color:var(--pico-secondary-inverse)}:is(button,[type=submit],[type=button],[role=button]).secondary:focus,:is(button,[type=submit],[type=button],[role=button]).secondary:is([aria-current]:not([aria-current=false])):focus,[type=file]::file-selector-button:focus,[type=file]::file-selector-button:is([aria-current]:not([aria-current=false])):focus,[type=reset]:focus,[type=reset]:is([aria-current]:not([aria-current=false])):focus{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-secondary-focus)}:is(button,[type=submit],[type=button],[role=button]).contrast{--pico-background-color:var(--pico-contrast-background);--pico-border-color:var(--pico-contrast-border);--pico-color:var(--pico-contrast-inverse)}:is(button,[type=submit],[type=button],[role=button]).contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-background-color:var(--pico-contrast-hover-background);--pico-border-color:var(--pico-contrast-hover-border);--pico-color:var(--pico-contrast-inverse)}:is(button,[type=submit],[type=button],[role=button]).contrast:focus,:is(button,[type=submit],[type=button],[role=button]).contrast:is([aria-current]:not([aria-current=false])):focus{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-contrast-focus)}:is(button,[type=submit],[type=button],[role=button]).outline,[type=reset].outline{--pico-background-color:transparent;--pico-color:var(--pico-primary);--pico-border-color:var(--pico-primary)}:is(button,[type=submit],[type=button],[role=button]).outline:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=reset].outline:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-background-color:transparent;--pico-color:var(--pico-primary-hover);--pico-border-color:var(--pico-primary-hover)}:is(button,[type=submit],[type=button],[role=button]).outline.secondary,[type=reset].outline{--pico-color:var(--pico-secondary);--pico-border-color:var(--pico-secondary)}:is(button,[type=submit],[type=button],[role=button]).outline.secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=reset].outline:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-secondary-hover);--pico-border-color:var(--pico-secondary-hover)}:is(button,[type=submit],[type=button],[role=button]).outline.contrast{--pico-color:var(--pico-contrast);--pico-border-color:var(--pico-contrast)}:is(button,[type=submit],[type=button],[role=button]).outline.contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-contrast-hover);--pico-border-color:var(--pico-contrast-hover)}:where(button,[type=submit],[type=reset],[type=button],[role=button])[disabled],:where(fieldset[disabled]) :is(button,[type=submit],[type=button],[type=reset],[role=button]){opacity:.5;pointer-events:none}:where(table){width:100%;border-collapse:collapse;border-spacing:0;text-indent:0}td,th{padding:calc(var(--pico-spacing)/ 2) var(--pico-spacing);border-bottom:var(--pico-border-width) solid var(--pico-table-border-color);background-color:var(--pico-background-color);color:var(--pico-color);font-weight:var(--pico-font-weight);text-align:left;text-align:start}tfoot td,tfoot th{border-top:var(--pico-border-width) solid var(--pico-table-border-color);border-bottom:0}table.striped tbody tr:nth-child(odd) td,table.striped tbody tr:nth-child(odd) th{background-color:var(--pico-table-row-stripped-background-color)}:where(audio,canvas,iframe,img,svg,video){vertical-align:middle}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}:where(iframe){border-style:none}img{max-width:100%;height:auto;border-style:none}:where(svg:not([fill])){fill:currentColor}svg:not(:host),svg:not(:root){overflow:hidden}code,kbd,pre,samp{font-size:.875em;font-family:var(--pico-font-family)}pre code,pre samp{font-size:inherit;font-family:inherit}pre{-ms-overflow-style:scrollbar;overflow:auto}code,kbd,pre,samp{border-radius:var(--pico-border-radius);background:var(--pico-code-background-color);color:var(--pico-code-color);font-weight:var(--pico-font-weight);line-height:initial}code,kbd,samp{display:inline-block;padding:.375rem}pre{display:block;margin-bottom:var(--pico-spacing);overflow-x:auto}pre>code,pre>samp{display:block;padding:var(--pico-spacing);background:0 0;line-height:var(--pico-line-height)}kbd{background-color:var(--pico-code-kbd-background-color);color:var(--pico-code-kbd-color);vertical-align:baseline}figure{display:block;margin:0;padding:0}figure figcaption{padding:calc(var(--pico-spacing) * .5) 0;color:var(--pico-muted-color)}hr{height:0;margin:var(--pico-typography-spacing-vertical) 0;border:0;border-top:1px solid var(--pico-muted-border-color);color:inherit}[hidden],template{display:none!important}canvas{display:inline-block}input,optgroup,select,textarea{margin:0;font-size:1rem;line-height:var(--pico-line-height);font-family:inherit;letter-spacing:inherit}input{overflow:visible}select{text-transform:none}legend{max-width:100%;padding:0;color:inherit;white-space:normal}textarea{overflow:auto}[type=checkbox],[type=radio]{padding:0}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}::-moz-focus-inner{padding:0;border-style:none}:-moz-focusring{outline:0}:-moz-ui-invalid{box-shadow:none}::-ms-expand{display:none}[type=file],[type=range]{padding:0;border-width:0}input:not([type=checkbox],[type=radio],[type=range]){height:calc(1rem * var(--pico-line-height) + var(--pico-form-element-spacing-vertical) * 2 + var(--pico-border-width) * 2)}fieldset{width:100%;margin:0;margin-bottom:var(--pico-spacing);padding:0;border:0}fieldset legend,label{display:block;margin-bottom:calc(var(--pico-spacing) * .375);color:var(--pico-color);font-weight:var(--pico-form-label-font-weight,var(--pico-font-weight))}fieldset legend{margin-bottom:calc(var(--pico-spacing) * .5)}button[type=submit],input:not([type=checkbox],[type=radio]),select,textarea{width:100%}input:not([type=checkbox],[type=radio],[type=range],[type=file]),select,textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:var(--pico-form-element-spacing-vertical) var(--pico-form-element-spacing-horizontal)}input,select,textarea{--pico-background-color:var(--pico-form-element-background-color);--pico-border-color:var(--pico-form-element-border-color);--pico-color:var(--pico-form-element-color);--pico-box-shadow:none;border:var(--pico-border-width) solid var(--pico-border-color);border-radius:var(--pico-border-radius);outline:0;background-color:var(--pico-background-color);box-shadow:var(--pico-box-shadow);color:var(--pico-color);font-weight:var(--pico-font-weight);transition:background-color var(--pico-transition),border-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition)}:where(select,textarea):not([readonly]):is(:active,:focus),input:not([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[readonly]):is(:active,:focus){--pico-background-color:var(--pico-form-element-active-background-color)}:where(select,textarea):not([readonly]):is(:active,:focus),input:not([type=submit],[type=button],[type=reset],[role=switch],[readonly]):is(:active,:focus){--pico-border-color:var(--pico-form-element-active-border-color)}:where(select,textarea):not([readonly]):focus,input:not([type=submit],[type=button],[type=reset],[type=range],[type=file],[readonly]):focus{--pico-box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-focus-color)}:where(fieldset[disabled]) :is(input:not([type=submit],[type=button],[type=reset]),select,textarea),input:not([type=submit],[type=button],[type=reset])[disabled],label[aria-disabled=true],select[disabled],textarea[disabled]{opacity:var(--pico-form-element-disabled-opacity);pointer-events:none}label[aria-disabled=true] input[disabled]{opacity:1}:where(input,select,textarea):not([type=checkbox],[type=radio],[type=date],[type=datetime-local],[type=month],[type=time],[type=week],[type=range])[aria-invalid]{padding-right:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem)!important;padding-left:var(--pico-form-element-spacing-horizontal);padding-inline-start:var(--pico-form-element-spacing-horizontal)!important;padding-inline-end:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem)!important;background-position:center right .75rem;background-size:1rem auto;background-repeat:no-repeat}:where(input,select,textarea):not([type=checkbox],[type=radio],[type=date],[type=datetime-local],[type=month],[type=time],[type=week],[type=range])[aria-invalid=false]:not(select){background-image:var(--pico-icon-valid)}:where(input,select,textarea):not([type=checkbox],[type=radio],[type=date],[type=datetime-local],[type=month],[type=time],[type=week],[type=range])[aria-invalid=true]:not(select){background-image:var(--pico-icon-invalid)}:where(input,select,textarea)[aria-invalid=false]{--pico-border-color:var(--pico-form-element-valid-border-color)}:where(input,select,textarea)[aria-invalid=false]:is(:active,:focus){--pico-border-color:var(--pico-form-element-valid-active-border-color)!important}:where(input,select,textarea)[aria-invalid=false]:is(:active,:focus):not([type=checkbox],[type=radio]){--pico-box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-valid-focus-color)!important}:where(input,select,textarea)[aria-invalid=true]{--pico-border-color:var(--pico-form-element-invalid-border-color)}:where(input,select,textarea)[aria-invalid=true]:is(:active,:focus){--pico-border-color:var(--pico-form-element-invalid-active-border-color)!important}:where(input,select,textarea)[aria-invalid=true]:is(:active,:focus):not([type=checkbox],[type=radio]){--pico-box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-invalid-focus-color)!important}[dir=rtl] :where(input,select,textarea):not([type=checkbox],[type=radio]):is([aria-invalid],[aria-invalid=true],[aria-invalid=false]){background-position:center left .75rem}input::-webkit-input-placeholder,input::placeholder,select:invalid,textarea::-webkit-input-placeholder,textarea::placeholder{color:var(--pico-form-element-placeholder-color);opacity:1}input:not([type=checkbox],[type=radio]),select,textarea{margin-bottom:var(--pico-spacing)}select::-ms-expand{border:0;background-color:transparent}select:not([multiple],[size]){padding-right:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem);padding-left:var(--pico-form-element-spacing-horizontal);padding-inline-start:var(--pico-form-element-spacing-horizontal);padding-inline-end:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem);background-image:var(--pico-icon-chevron);background-position:center right .75rem;background-size:1rem auto;background-repeat:no-repeat}select[multiple] option:checked{background:var(--pico-form-element-selected-background-color);color:var(--pico-form-element-color)}[dir=rtl] select:not([multiple],[size]){background-position:center left .75rem}textarea{display:block;resize:vertical}textarea[aria-invalid]{--pico-icon-height:calc(1rem * var(--pico-line-height) + var(--pico-form-element-spacing-vertical) * 2 + var(--pico-border-width) * 2);background-position:top right .75rem!important;background-size:1rem var(--pico-icon-height)!important}:where(input,select,textarea,fieldset,.grid)+small{display:block;width:100%;margin-top:calc(var(--pico-spacing) * -.75);margin-bottom:var(--pico-spacing);color:var(--pico-muted-color)}:where(input,select,textarea,fieldset,.grid)[aria-invalid=false]+small{color:var(--pico-ins-color)}:where(input,select,textarea,fieldset,.grid)[aria-invalid=true]+small{color:var(--pico-del-color)}label>:where(input,select,textarea){margin-top:calc(var(--pico-spacing) * .25)}label:has([type=checkbox],[type=radio]){width:-moz-fit-content;width:fit-content;cursor:pointer}[type=checkbox],[type=radio]{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:1.25em;height:1.25em;margin-top:-.125em;margin-inline-end:.5em;border-width:var(--pico-border-width);vertical-align:middle;cursor:pointer}[type=checkbox]::-ms-check,[type=radio]::-ms-check{display:none}[type=checkbox]:checked,[type=checkbox]:checked:active,[type=checkbox]:checked:focus,[type=radio]:checked,[type=radio]:checked:active,[type=radio]:checked:focus{--pico-background-color:var(--pico-primary-background);--pico-border-color:var(--pico-primary-border);background-image:var(--pico-icon-checkbox);background-position:center;background-size:.75em auto;background-repeat:no-repeat}[type=checkbox]~label,[type=radio]~label{display:inline-block;margin-bottom:0;cursor:pointer}[type=checkbox]~label:not(:last-of-type),[type=radio]~label:not(:last-of-type){margin-inline-end:1em}[type=checkbox]:indeterminate{--pico-background-color:var(--pico-primary-background);--pico-border-color:var(--pico-primary-border);background-image:var(--pico-icon-minus);background-position:center;background-size:.75em auto;background-repeat:no-repeat}[type=radio]{border-radius:50%}[type=radio]:checked,[type=radio]:checked:active,[type=radio]:checked:focus{--pico-background-color:var(--pico-primary-inverse);border-width:.35em;background-image:none}[type=checkbox][role=switch]{--pico-background-color:var(--pico-switch-background-color);--pico-color:var(--pico-switch-color);width:2.25em;height:1.25em;border:var(--pico-border-width) solid var(--pico-border-color);border-radius:1.25em;background-color:var(--pico-background-color);line-height:1.25em}[type=checkbox][role=switch]:not([aria-invalid]){--pico-border-color:var(--pico-switch-background-color)}[type=checkbox][role=switch]:before{display:block;aspect-ratio:1;height:100%;border-radius:50%;background-color:var(--pico-color);box-shadow:var(--pico-switch-thumb-box-shadow);content:"";transition:margin .1s ease-in-out}[type=checkbox][role=switch]:focus{--pico-background-color:var(--pico-switch-background-color);--pico-border-color:var(--pico-switch-background-color)}[type=checkbox][role=switch]:checked{--pico-background-color:var(--pico-switch-checked-background-color);--pico-border-color:var(--pico-switch-checked-background-color);background-image:none}[type=checkbox][role=switch]:checked::before{margin-inline-start:calc(2.25em - 1.25em)}[type=checkbox][role=switch][disabled]{--pico-background-color:var(--pico-border-color)}[type=checkbox][aria-invalid=false]:checked,[type=checkbox][aria-invalid=false]:checked:active,[type=checkbox][aria-invalid=false]:checked:focus,[type=checkbox][role=switch][aria-invalid=false]:checked,[type=checkbox][role=switch][aria-invalid=false]:checked:active,[type=checkbox][role=switch][aria-invalid=false]:checked:focus{--pico-background-color:var(--pico-form-element-valid-border-color)}[type=checkbox]:checked:active[aria-invalid=true],[type=checkbox]:checked:focus[aria-invalid=true],[type=checkbox]:checked[aria-invalid=true],[type=checkbox][role=switch]:checked:active[aria-invalid=true],[type=checkbox][role=switch]:checked:focus[aria-invalid=true],[type=checkbox][role=switch]:checked[aria-invalid=true]{--pico-background-color:var(--pico-form-element-invalid-border-color)}[type=checkbox][aria-invalid=false]:checked,[type=checkbox][aria-invalid=false]:checked:active,[type=checkbox][aria-invalid=false]:checked:focus,[type=checkbox][role=switch][aria-invalid=false]:checked,[type=checkbox][role=switch][aria-invalid=false]:checked:active,[type=checkbox][role=switch][aria-invalid=false]:checked:focus,[type=radio][aria-invalid=false]:checked,[type=radio][aria-invalid=false]:checked:active,[type=radio][aria-invalid=false]:checked:focus{--pico-border-color:var(--pico-form-element-valid-border-color)}[type=checkbox]:checked:active[aria-invalid=true],[type=checkbox]:checked:focus[aria-invalid=true],[type=checkbox]:checked[aria-invalid=true],[type=checkbox][role=switch]:checked:active[aria-invalid=true],[type=checkbox][role=switch]:checked:focus[aria-invalid=true],[type=checkbox][role=switch]:checked[aria-invalid=true],[type=radio]:checked:active[aria-invalid=true],[type=radio]:checked:focus[aria-invalid=true],[type=radio]:checked[aria-invalid=true]{--pico-border-color:var(--pico-form-element-invalid-border-color)}[type=color]::-webkit-color-swatch-wrapper{padding:0}[type=color]::-moz-focus-inner{padding:0}[type=color]::-webkit-color-swatch{border:0;border-radius:calc(var(--pico-border-radius) * .5)}[type=color]::-moz-color-swatch{border:0;border-radius:calc(var(--pico-border-radius) * .5)}input:not([type=checkbox],[type=radio],[type=range],[type=file]):is([type=date],[type=datetime-local],[type=month],[type=time],[type=week]){--pico-icon-position:0.75rem;--pico-icon-width:1rem;padding-right:calc(var(--pico-icon-width) + var(--pico-icon-position));background-image:var(--pico-icon-date);background-position:center right var(--pico-icon-position);background-size:var(--pico-icon-width) auto;background-repeat:no-repeat}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=time]{background-image:var(--pico-icon-time)}[type=date]::-webkit-calendar-picker-indicator,[type=datetime-local]::-webkit-calendar-picker-indicator,[type=month]::-webkit-calendar-picker-indicator,[type=time]::-webkit-calendar-picker-indicator,[type=week]::-webkit-calendar-picker-indicator{width:var(--pico-icon-width);margin-right:calc(var(--pico-icon-width) * -1);margin-left:var(--pico-icon-position);opacity:0}@-moz-document url-prefix(){[type=date],[type=datetime-local],[type=month],[type=time],[type=week]{padding-right:var(--pico-form-element-spacing-horizontal)!important;background-image:none!important}}[dir=rtl] :is([type=date],[type=datetime-local],[type=month],[type=time],[type=week]){text-align:right}[type=file]{--pico-color:var(--pico-muted-color);margin-left:calc(var(--pico-outline-width) * -1);padding:calc(var(--pico-form-element-spacing-vertical) * .5) 0;padding-left:var(--pico-outline-width);border:0;border-radius:0;background:0 0}[type=file]::file-selector-button{margin-right:calc(var(--pico-spacing)/ 2);padding:calc(var(--pico-form-element-spacing-vertical) * .5) var(--pico-form-element-spacing-horizontal)}[type=file]:is(:hover,:active,:focus)::file-selector-button{--pico-background-color:var(--pico-secondary-hover-background);--pico-border-color:var(--pico-secondary-hover-border)}[type=file]:focus::file-selector-button{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-secondary-focus)}[type=range]{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:1.25rem;background:0 0}[type=range]::-webkit-slider-runnable-track{width:100%;height:.375rem;border-radius:var(--pico-border-radius);background-color:var(--pico-range-border-color);-webkit-transition:background-color var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),box-shadow var(--pico-transition)}[type=range]::-moz-range-track{width:100%;height:.375rem;border-radius:var(--pico-border-radius);background-color:var(--pico-range-border-color);-moz-transition:background-color var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),box-shadow var(--pico-transition)}[type=range]::-ms-track{width:100%;height:.375rem;border-radius:var(--pico-border-radius);background-color:var(--pico-range-border-color);-ms-transition:background-color var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),box-shadow var(--pico-transition)}[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:1.25rem;height:1.25rem;margin-top:-.4375rem;border:2px solid var(--pico-range-thumb-border-color);border-radius:50%;background-color:var(--pico-range-thumb-color);cursor:pointer;-webkit-transition:background-color var(--pico-transition),transform var(--pico-transition);transition:background-color var(--pico-transition),transform var(--pico-transition)}[type=range]::-moz-range-thumb{-webkit-appearance:none;width:1.25rem;height:1.25rem;margin-top:-.4375rem;border:2px solid var(--pico-range-thumb-border-color);border-radius:50%;background-color:var(--pico-range-thumb-color);cursor:pointer;-moz-transition:background-color var(--pico-transition),transform var(--pico-transition);transition:background-color var(--pico-transition),transform var(--pico-transition)}[type=range]::-ms-thumb{-webkit-appearance:none;width:1.25rem;height:1.25rem;margin-top:-.4375rem;border:2px solid var(--pico-range-thumb-border-color);border-radius:50%;background-color:var(--pico-range-thumb-color);cursor:pointer;-ms-transition:background-color var(--pico-transition),transform var(--pico-transition);transition:background-color var(--pico-transition),transform var(--pico-transition)}[type=range]:active,[type=range]:focus-within{--pico-range-border-color:var(--pico-range-active-border-color);--pico-range-thumb-color:var(--pico-range-thumb-active-color)}[type=range]:active::-webkit-slider-thumb{transform:scale(1.25)}[type=range]:active::-moz-range-thumb{transform:scale(1.25)}[type=range]:active::-ms-thumb{transform:scale(1.25)}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search]{padding-inline-start:calc(var(--pico-form-element-spacing-horizontal) + 1.75rem);background-image:var(--pico-icon-search);background-position:center left calc(var(--pico-form-element-spacing-horizontal) + .125rem);background-size:1rem auto;background-repeat:no-repeat}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid]{padding-inline-start:calc(var(--pico-form-element-spacing-horizontal) + 1.75rem)!important;background-position:center left 1.125rem,center right .75rem}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid=false]{background-image:var(--pico-icon-search),var(--pico-icon-valid)}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid=true]{background-image:var(--pico-icon-search),var(--pico-icon-invalid)}[dir=rtl] :where(input):not([type=checkbox],[type=radio],[type=range],[type=file])[type=search]{background-position:center right 1.125rem}[dir=rtl] :where(input):not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid]{background-position:center right 1.125rem,center left .75rem}details{display:block;margin-bottom:var(--pico-spacing)}details summary{line-height:1rem;list-style-type:none;cursor:pointer;transition:color var(--pico-transition)}details summary:not([role]){color:var(--pico-accordion-close-summary-color)}details summary::-webkit-details-marker{display:none}details summary::marker{display:none}details summary::-moz-list-bullet{list-style-type:none}details summary::after{display:block;width:1rem;height:1rem;margin-inline-start:calc(var(--pico-spacing,1rem) * .5);float:right;transform:rotate(-90deg);background-image:var(--pico-icon-chevron);background-position:right center;background-size:1rem auto;background-repeat:no-repeat;content:"";transition:transform var(--pico-transition)}details summary:focus{outline:0}details summary:focus:not([role]){color:var(--pico-accordion-active-summary-color)}details summary:focus-visible:not([role]){outline:var(--pico-outline-width) solid var(--pico-primary-focus);outline-offset:calc(var(--pico-spacing,1rem) * 0.5);color:var(--pico-primary)}details summary[role=button]{width:100%;text-align:left}details summary[role=button]::after{height:calc(1rem * var(--pico-line-height,1.5))}details[open]>summary{margin-bottom:var(--pico-spacing)}details[open]>summary:not([role]):not(:focus){color:var(--pico-accordion-open-summary-color)}details[open]>summary::after{transform:rotate(0)}[dir=rtl] details summary{text-align:right}[dir=rtl] details summary::after{float:left;background-position:left center}article{margin-bottom:var(--pico-block-spacing-vertical);padding:var(--pico-block-spacing-vertical) var(--pico-block-spacing-horizontal);border-radius:var(--pico-border-radius);background:var(--pico-card-background-color);box-shadow:var(--pico-card-box-shadow)}article>footer,article>header{margin-right:calc(var(--pico-block-spacing-horizontal) * -1);margin-left:calc(var(--pico-block-spacing-horizontal) * -1);padding:calc(var(--pico-block-spacing-vertical) * .66) var(--pico-block-spacing-horizontal);background-color:var(--pico-card-sectioning-background-color)}article>header{margin-top:calc(var(--pico-block-spacing-vertical) * -1);margin-bottom:var(--pico-block-spacing-vertical);border-bottom:var(--pico-border-width) solid var(--pico-card-border-color);border-top-right-radius:var(--pico-border-radius);border-top-left-radius:var(--pico-border-radius)}article>footer{margin-top:var(--pico-block-spacing-vertical);margin-bottom:calc(var(--pico-block-spacing-vertical) * -1);border-top:var(--pico-border-width) solid var(--pico-card-border-color);border-bottom-right-radius:var(--pico-border-radius);border-bottom-left-radius:var(--pico-border-radius)}details.dropdown{position:relative;border-bottom:none}details.dropdown>a::after,details.dropdown>button::after,details.dropdown>summary::after{display:block;width:1rem;height:calc(1rem * var(--pico-line-height,1.5));margin-inline-start:.25rem;float:right;transform:rotate(0) translateX(.2rem);background-image:var(--pico-icon-chevron);background-position:right center;background-size:1rem auto;background-repeat:no-repeat;content:""}nav details.dropdown{margin-bottom:0}details.dropdown>summary:not([role]){height:calc(1rem * var(--pico-line-height) + var(--pico-form-element-spacing-vertical) * 2 + var(--pico-border-width) * 2);padding:var(--pico-form-element-spacing-vertical) var(--pico-form-element-spacing-horizontal);border:var(--pico-border-width) solid var(--pico-form-element-border-color);border-radius:var(--pico-border-radius);background-color:var(--pico-form-element-background-color);color:var(--pico-form-element-placeholder-color);line-height:inherit;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:background-color var(--pico-transition),border-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition)}details.dropdown>summary:not([role]):active,details.dropdown>summary:not([role]):focus{border-color:var(--pico-form-element-active-border-color);background-color:var(--pico-form-element-active-background-color)}details.dropdown>summary:not([role]):focus{box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-focus-color)}details.dropdown>summary:not([role]):focus-visible{outline:0}details.dropdown>summary:not([role])[aria-invalid=false]{--pico-form-element-border-color:var(--pico-form-element-valid-border-color);--pico-form-element-active-border-color:var(--pico-form-element-valid-focus-color);--pico-form-element-focus-color:var(--pico-form-element-valid-focus-color)}details.dropdown>summary:not([role])[aria-invalid=true]{--pico-form-element-border-color:var(--pico-form-element-invalid-border-color);--pico-form-element-active-border-color:var(--pico-form-element-invalid-focus-color);--pico-form-element-focus-color:var(--pico-form-element-invalid-focus-color)}nav details.dropdown{display:inline;margin:calc(var(--pico-nav-element-spacing-vertical) * -1) 0}nav details.dropdown>summary::after{transform:rotate(0) translateX(0)}nav details.dropdown>summary:not([role]){height:calc(1rem * var(--pico-line-height) + var(--pico-nav-link-spacing-vertical) * 2);padding:calc(var(--pico-nav-link-spacing-vertical) - var(--pico-border-width) * 2) var(--pico-nav-link-spacing-horizontal)}nav details.dropdown>summary:not([role]):focus-visible{box-shadow:0 0 0 var(--pico-outline-width) var(--pico-primary-focus)}details.dropdown>summary+ul{display:flex;z-index:99;position:absolute;left:0;flex-direction:column;width:100%;min-width:-moz-fit-content;min-width:fit-content;margin:0;margin-top:var(--pico-outline-width);padding:0;border:var(--pico-border-width) solid var(--pico-dropdown-border-color);border-radius:var(--pico-border-radius);background-color:var(--pico-dropdown-background-color);box-shadow:var(--pico-dropdown-box-shadow);color:var(--pico-dropdown-color);white-space:nowrap;opacity:0;transition:opacity var(--pico-transition),transform 0s ease-in-out 1s}details.dropdown>summary+ul[dir=rtl]{right:0;left:auto}details.dropdown>summary+ul li{width:100%;margin-bottom:0;padding:calc(var(--pico-form-element-spacing-vertical) * .5) var(--pico-form-element-spacing-horizontal);list-style:none}details.dropdown>summary+ul li:first-of-type{margin-top:calc(var(--pico-form-element-spacing-vertical) * .5)}details.dropdown>summary+ul li:last-of-type{margin-bottom:calc(var(--pico-form-element-spacing-vertical) * .5)}details.dropdown>summary+ul li a{display:block;margin:calc(var(--pico-form-element-spacing-vertical) * -.5) calc(var(--pico-form-element-spacing-horizontal) * -1);padding:calc(var(--pico-form-element-spacing-vertical) * .5) var(--pico-form-element-spacing-horizontal);overflow:hidden;border-radius:0;color:var(--pico-dropdown-color);text-decoration:none;text-overflow:ellipsis}details.dropdown>summary+ul li a:active,details.dropdown>summary+ul li a:focus,details.dropdown>summary+ul li a:focus-visible,details.dropdown>summary+ul li a:hover,details.dropdown>summary+ul li a[aria-current]:not([aria-current=false]){background-color:var(--pico-dropdown-hover-background-color)}details.dropdown>summary+ul li label{width:100%}details.dropdown>summary+ul li:has(label):hover{background-color:var(--pico-dropdown-hover-background-color)}details.dropdown[open]>summary{margin-bottom:0}details.dropdown[open]>summary+ul{transform:scaleY(1);opacity:1;transition:opacity var(--pico-transition),transform 0s ease-in-out 0s}details.dropdown[open]>summary::before{display:block;z-index:1;position:fixed;width:100vw;height:100vh;inset:0;background:0 0;content:"";cursor:default}label>details.dropdown{margin-top:calc(var(--pico-spacing) * .25)}[role=group],[role=search]{display:inline-flex;position:relative;width:100%;margin-bottom:var(--pico-spacing);border-radius:var(--pico-border-radius);box-shadow:var(--pico-group-box-shadow,0 0 0 transparent);vertical-align:middle;transition:box-shadow var(--pico-transition)}[role=group] input:not([type=checkbox],[type=radio]),[role=group] select,[role=group]>*,[role=search] input:not([type=checkbox],[type=radio]),[role=search] select,[role=search]>*{position:relative;flex:1 1 auto;margin-bottom:0}[role=group] input:not([type=checkbox],[type=radio]):not(:first-child),[role=group] select:not(:first-child),[role=group]>:not(:first-child),[role=search] input:not([type=checkbox],[type=radio]):not(:first-child),[role=search] select:not(:first-child),[role=search]>:not(:first-child){margin-left:0;border-top-left-radius:0;border-bottom-left-radius:0}[role=group] input:not([type=checkbox],[type=radio]):not(:last-child),[role=group] select:not(:last-child),[role=group]>:not(:last-child),[role=search] input:not([type=checkbox],[type=radio]):not(:last-child),[role=search] select:not(:last-child),[role=search]>:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}[role=group] input:not([type=checkbox],[type=radio]):focus,[role=group] select:focus,[role=group]>:focus,[role=search] input:not([type=checkbox],[type=radio]):focus,[role=search] select:focus,[role=search]>:focus{z-index:2}[role=group] [role=button]:not(:first-child),[role=group] [type=button]:not(:first-child),[role=group] [type=reset]:not(:first-child),[role=group] [type=submit]:not(:first-child),[role=group] button:not(:first-child),[role=group] input:not([type=checkbox],[type=radio]):not(:first-child),[role=group] select:not(:first-child),[role=search] [role=button]:not(:first-child),[role=search] [type=button]:not(:first-child),[role=search] [type=reset]:not(:first-child),[role=search] [type=submit]:not(:first-child),[role=search] button:not(:first-child),[role=search] input:not([type=checkbox],[type=radio]):not(:first-child),[role=search] select:not(:first-child){margin-left:calc(var(--pico-border-width) * -1)}[role=group] [role=button],[role=group] [type=button],[role=group] [type=reset],[role=group] [type=submit],[role=group] button,[role=search] [role=button],[role=search] [type=button],[role=search] [type=reset],[role=search] [type=submit],[role=search] button{width:auto}@supports selector(:has(*)){[role=group]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus),[role=search]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus){--pico-group-box-shadow:var(--pico-group-box-shadow-focus-with-button)}[role=group]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) input:not([type=checkbox],[type=radio]),[role=group]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) select,[role=search]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) input:not([type=checkbox],[type=radio]),[role=search]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) select{border-color:transparent}[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus),[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus){--pico-group-box-shadow:var(--pico-group-box-shadow-focus-with-input)}[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) [role=button],[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=button],[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=submit],[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) button,[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) [role=button],[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=button],[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=submit],[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) button{--pico-button-box-shadow:0 0 0 var(--pico-border-width) var(--pico-primary-border);--pico-button-hover-box-shadow:0 0 0 var(--pico-border-width) var(--pico-primary-hover-border)}[role=group] [role=button]:focus,[role=group] [type=button]:focus,[role=group] [type=reset]:focus,[role=group] [type=submit]:focus,[role=group] button:focus,[role=search] [role=button]:focus,[role=search] [type=button]:focus,[role=search] [type=reset]:focus,[role=search] [type=submit]:focus,[role=search] button:focus{box-shadow:none}}[role=search]>:first-child{border-top-left-radius:5rem;border-bottom-left-radius:5rem}[role=search]>:last-child{border-top-right-radius:5rem;border-bottom-right-radius:5rem}[aria-busy=true]:not(input,select,textarea,html,form){white-space:nowrap}[aria-busy=true]:not(input,select,textarea,html,form)::before{display:inline-block;width:1em;height:1em;background-image:var(--pico-icon-loading);background-size:1em auto;background-repeat:no-repeat;content:"";vertical-align:-.125em}[aria-busy=true]:not(input,select,textarea,html,form):not(:empty)::before{margin-inline-end:calc(var(--pico-spacing) * .5)}[aria-busy=true]:not(input,select,textarea,html,form):empty{text-align:center}[role=button][aria-busy=true],[type=button][aria-busy=true],[type=reset][aria-busy=true],[type=submit][aria-busy=true],a[aria-busy=true],button[aria-busy=true]{pointer-events:none}:host,:root{--pico-scrollbar-width:0px}dialog{display:flex;z-index:999;position:fixed;top:0;right:0;bottom:0;left:0;align-items:center;justify-content:center;width:inherit;min-width:100%;height:inherit;min-height:100%;padding:0;border:0;-webkit-backdrop-filter:var(--pico-modal-overlay-backdrop-filter);backdrop-filter:var(--pico-modal-overlay-backdrop-filter);background-color:var(--pico-modal-overlay-background-color);color:var(--pico-color)}dialog>article{width:100%;max-height:calc(100vh - var(--pico-spacing) * 2);margin:var(--pico-spacing);overflow:auto}@media (min-width:576px){dialog>article{max-width:510px}}@media (min-width:768px){dialog>article{max-width:700px}}dialog>article>header>*{margin-bottom:0}dialog>article>header .close,dialog>article>header :is(a,button)[rel=prev]{margin:0;margin-left:var(--pico-spacing);padding:0;float:right}dialog>article>footer{text-align:right}dialog>article>footer [role=button],dialog>article>footer button{margin-bottom:0}dialog>article>footer [role=button]:not(:first-of-type),dialog>article>footer button:not(:first-of-type){margin-left:calc(var(--pico-spacing) * .5)}dialog>article .close,dialog>article :is(a,button)[rel=prev]{display:block;width:1rem;height:1rem;margin-top:calc(var(--pico-spacing) * -1);margin-bottom:var(--pico-spacing);margin-left:auto;border:none;background-image:var(--pico-icon-close);background-position:center;background-size:auto 1rem;background-repeat:no-repeat;background-color:transparent;opacity:.5;transition:opacity var(--pico-transition)}dialog>article .close:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),dialog>article :is(a,button)[rel=prev]:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){opacity:1}dialog:not([open]),dialog[open=false]{display:none}.modal-is-open{padding-right:var(--pico-scrollbar-width,0);overflow:hidden;pointer-events:none;touch-action:none}.modal-is-open dialog{pointer-events:auto;touch-action:auto}:where(.modal-is-opening,.modal-is-closing) dialog,:where(.modal-is-opening,.modal-is-closing) dialog>article{animation-duration:.2s;animation-timing-function:ease-in-out;animation-fill-mode:both}:where(.modal-is-opening,.modal-is-closing) dialog{animation-duration:.8s;animation-name:modal-overlay}:where(.modal-is-opening,.modal-is-closing) dialog>article{animation-delay:.2s;animation-name:modal}.modal-is-closing dialog,.modal-is-closing dialog>article{animation-delay:0s;animation-direction:reverse}@keyframes modal-overlay{from{-webkit-backdrop-filter:none;backdrop-filter:none;background-color:transparent}}@keyframes modal{from{transform:translateY(-100%);opacity:0}}:where(nav li)::before{float:left;content:"​"}nav,nav ul{display:flex}nav{justify-content:space-between;overflow:visible}nav ol,nav ul{align-items:center;margin-bottom:0;padding:0;list-style:none}nav ol:first-of-type,nav ul:first-of-type{margin-left:calc(var(--pico-nav-element-spacing-horizontal) * -1)}nav ol:last-of-type,nav ul:last-of-type{margin-right:calc(var(--pico-nav-element-spacing-horizontal) * -1)}nav li{display:inline-block;margin:0;padding:var(--pico-nav-element-spacing-vertical) var(--pico-nav-element-spacing-horizontal)}nav li :where(a,[role=link]){display:inline-block;margin:calc(var(--pico-nav-link-spacing-vertical) * -1) calc(var(--pico-nav-link-spacing-horizontal) * -1);padding:var(--pico-nav-link-spacing-vertical) var(--pico-nav-link-spacing-horizontal);border-radius:var(--pico-border-radius)}nav li :where(a,[role=link]):not(:hover){text-decoration:none}nav li [role=button],nav li [type=button],nav li button,nav li input:not([type=checkbox],[type=radio],[type=range],[type=file]),nav li select{height:auto;margin-right:inherit;margin-bottom:0;margin-left:inherit;padding:calc(var(--pico-nav-link-spacing-vertical) - var(--pico-border-width) * 2) var(--pico-nav-link-spacing-horizontal)}nav[aria-label=breadcrumb]{align-items:center;justify-content:start}nav[aria-label=breadcrumb] ul li:not(:first-child){margin-inline-start:var(--pico-nav-link-spacing-horizontal)}nav[aria-label=breadcrumb] ul li a{margin:calc(var(--pico-nav-link-spacing-vertical) * -1) 0;margin-inline-start:calc(var(--pico-nav-link-spacing-horizontal) * -1)}nav[aria-label=breadcrumb] ul li:not(:last-child)::after{display:inline-block;position:absolute;width:calc(var(--pico-nav-link-spacing-horizontal) * 4);margin:0 calc(var(--pico-nav-link-spacing-horizontal) * -1);content:var(--pico-nav-breadcrumb-divider);color:var(--pico-muted-color);text-align:center;text-decoration:none;white-space:nowrap}nav[aria-label=breadcrumb] a[aria-current]:not([aria-current=false]){background-color:transparent;color:inherit;text-decoration:none;pointer-events:none}aside li,aside nav,aside ol,aside ul{display:block}aside li{padding:calc(var(--pico-nav-element-spacing-vertical) * .5) var(--pico-nav-element-spacing-horizontal)}aside li a{display:block}aside li [role=button]{margin:inherit}[dir=rtl] nav[aria-label=breadcrumb] ul li:not(:last-child) ::after{content:"\\"}progress{display:inline-block;vertical-align:baseline}progress{-webkit-appearance:none;-moz-appearance:none;display:inline-block;appearance:none;width:100%;height:.5rem;margin-bottom:calc(var(--pico-spacing) * .5);overflow:hidden;border:0;border-radius:var(--pico-border-radius);background-color:var(--pico-progress-background-color);color:var(--pico-progress-color)}progress::-webkit-progress-bar{border-radius:var(--pico-border-radius);background:0 0}progress[value]::-webkit-progress-value{background-color:var(--pico-progress-color);-webkit-transition:inline-size var(--pico-transition);transition:inline-size var(--pico-transition)}progress::-moz-progress-bar{background-color:var(--pico-progress-color)}@media (prefers-reduced-motion:no-preference){progress:indeterminate{background:var(--pico-progress-background-color) linear-gradient(to right,var(--pico-progress-color) 30%,var(--pico-progress-background-color) 30%) top left/150% 150% no-repeat;animation:progress-indeterminate 1s linear infinite}progress:indeterminate[value]::-webkit-progress-value{background-color:transparent}progress:indeterminate::-moz-progress-bar{background-color:transparent}}@media (prefers-reduced-motion:no-preference){[dir=rtl] progress:indeterminate{animation-direction:reverse}}@keyframes progress-indeterminate{0%{background-position:200% 0}100%{background-position:-200% 0}}[data-tooltip]{position:relative}[data-tooltip]:not(a,button,input,[role=button]){border-bottom:1px dotted;text-decoration:none;cursor:help}[data-tooltip]::after,[data-tooltip]::before,[data-tooltip][data-placement=top]::after,[data-tooltip][data-placement=top]::before{display:block;z-index:99;position:absolute;bottom:100%;left:50%;padding:.25rem .5rem;overflow:hidden;transform:translate(-50%,-.25rem);border-radius:var(--pico-border-radius);background:var(--pico-tooltip-background-color);content:attr(data-tooltip);color:var(--pico-tooltip-color);font-style:normal;font-weight:var(--pico-font-weight);font-size:.875rem;text-decoration:none;text-overflow:ellipsis;white-space:nowrap;opacity:0;pointer-events:none}[data-tooltip]::after,[data-tooltip][data-placement=top]::after{padding:0;transform:translate(-50%,0);border-top:.3rem solid;border-right:.3rem solid transparent;border-left:.3rem solid transparent;border-radius:0;background-color:transparent;content:"";color:var(--pico-tooltip-background-color)}[data-tooltip][data-placement=bottom]::after,[data-tooltip][data-placement=bottom]::before{top:100%;bottom:auto;transform:translate(-50%,.25rem)}[data-tooltip][data-placement=bottom]:after{transform:translate(-50%,-.3rem);border:.3rem solid transparent;border-bottom:.3rem solid}[data-tooltip][data-placement=left]::after,[data-tooltip][data-placement=left]::before{top:50%;right:100%;bottom:auto;left:auto;transform:translate(-.25rem,-50%)}[data-tooltip][data-placement=left]:after{transform:translate(.3rem,-50%);border:.3rem solid transparent;border-left:.3rem solid}[data-tooltip][data-placement=right]::after,[data-tooltip][data-placement=right]::before{top:50%;right:auto;bottom:auto;left:100%;transform:translate(.25rem,-50%)}[data-tooltip][data-placement=right]:after{transform:translate(-.3rem,-50%);border:.3rem solid transparent;border-right:.3rem solid}[data-tooltip]:focus::after,[data-tooltip]:focus::before,[data-tooltip]:hover::after,[data-tooltip]:hover::before{opacity:1}@media (hover:hover) and (pointer:fine){[data-tooltip]:focus::after,[data-tooltip]:focus::before,[data-tooltip]:hover::after,[data-tooltip]:hover::before{--pico-tooltip-slide-to:translate(-50%, -0.25rem);transform:translate(-50%,.75rem);animation-duration:.2s;animation-fill-mode:forwards;animation-name:tooltip-slide;opacity:0}[data-tooltip]:focus::after,[data-tooltip]:hover::after{--pico-tooltip-caret-slide-to:translate(-50%, 0rem);transform:translate(-50%,-.25rem);animation-name:tooltip-caret-slide}[data-tooltip][data-placement=bottom]:focus::after,[data-tooltip][data-placement=bottom]:focus::before,[data-tooltip][data-placement=bottom]:hover::after,[data-tooltip][data-placement=bottom]:hover::before{--pico-tooltip-slide-to:translate(-50%, 0.25rem);transform:translate(-50%,-.75rem);animation-name:tooltip-slide}[data-tooltip][data-placement=bottom]:focus::after,[data-tooltip][data-placement=bottom]:hover::after{--pico-tooltip-caret-slide-to:translate(-50%, -0.3rem);transform:translate(-50%,-.5rem);animation-name:tooltip-caret-slide}[data-tooltip][data-placement=left]:focus::after,[data-tooltip][data-placement=left]:focus::before,[data-tooltip][data-placement=left]:hover::after,[data-tooltip][data-placement=left]:hover::before{--pico-tooltip-slide-to:translate(-0.25rem, -50%);transform:translate(.75rem,-50%);animation-name:tooltip-slide}[data-tooltip][data-placement=left]:focus::after,[data-tooltip][data-placement=left]:hover::after{--pico-tooltip-caret-slide-to:translate(0.3rem, -50%);transform:translate(.05rem,-50%);animation-name:tooltip-caret-slide}[data-tooltip][data-placement=right]:focus::after,[data-tooltip][data-placement=right]:focus::before,[data-tooltip][data-placement=right]:hover::after,[data-tooltip][data-placement=right]:hover::before{--pico-tooltip-slide-to:translate(0.25rem, -50%);transform:translate(-.75rem,-50%);animation-name:tooltip-slide}[data-tooltip][data-placement=right]:focus::after,[data-tooltip][data-placement=right]:hover::after{--pico-tooltip-caret-slide-to:translate(-0.3rem, -50%);transform:translate(-.05rem,-50%);animation-name:tooltip-caret-slide}}@keyframes tooltip-slide{to{transform:var(--pico-tooltip-slide-to);opacity:1}}@keyframes tooltip-caret-slide{50%{opacity:0}to{transform:var(--pico-tooltip-caret-slide-to);opacity:1}}[aria-controls]{cursor:pointer}[aria-disabled=true],[disabled]{cursor:not-allowed}[aria-hidden=false][hidden]{display:initial}[aria-hidden=false][hidden]:not(:focus){clip:rect(0,0,0,0);position:absolute}[tabindex],a,area,button,input,label,select,summary,textarea{-ms-touch-action:manipulation}[dir=rtl]{direction:rtl}@media (prefers-reduced-motion:reduce){:not([aria-busy=true]),:not([aria-busy=true])::after,:not([aria-busy=true])::before{background-attachment:initial!important;animation-duration:1ms!important;animation-delay:-1ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important;transition-delay:0s!important;transition-duration:0s!important}} \ No newline at end of file diff --git a/web/templates/layouts/base.html b/web/templates/layouts/base.html new file mode 100644 index 0000000..ac4c0df --- /dev/null +++ b/web/templates/layouts/base.html @@ -0,0 +1,62 @@ +{{define "base.html"}} + + + + + {{if .Title}}{{.Title}} — {{end}}{{.SiteName}} + + + {{block "head" .}}{{end}} + + + + +
+ +
+ +
+ {{if .Flash}} + + {{end}} + {{block "content" .}}{{end}} +
+ + + + + + +{{end}} diff --git a/web/templates/pages/fave_detail.html b/web/templates/pages/fave_detail.html new file mode 100644 index 0000000..ea1d68b --- /dev/null +++ b/web/templates/pages/fave_detail.html @@ -0,0 +1,73 @@ +{{define "head"}} +{{with .Data}}{{with .Fave}} + {{if eq .Privacy "public"}} + + + + {{if $.ExternalURL}} + + {{if .ImagePath}} + + + {{else}} + + {{end}} + {{end}} + + {{range .Tags}} + + {{end}} + {{end}} +{{end}}{{end}} +{{end}} + +{{define "content"}} +{{with .Data}} +
+ {{with .Fave}} + {{if .ImagePath}} + Bilde for: {{.Description}} + {{end}} + +
+

{{.Description}}

+

+ Av {{.DisplayName}} + {{if eq .Privacy "private"}} + — Privat + {{end}} +

+
+ + {{if .URL}} +

{{.URL}}

+ {{end}} + + {{if .Tags}} +

+ {{range .Tags}} + {{.Name}} + {{end}} +

+ {{end}} + +
+ Lagt til {{.CreatedAt.Format "02.01.2006"}} + {{if $.IsOwner}} + + {{end}} +
+ {{end}} +
+{{end}} +{{end}} diff --git a/web/templates/pages/fave_form.html b/web/templates/pages/fave_form.html new file mode 100644 index 0000000..c86bf75 --- /dev/null +++ b/web/templates/pages/fave_form.html @@ -0,0 +1,92 @@ +{{define "content"}} +
+ {{with .Data}} + {{if .IsNew}} +

Ny favoritt

+ {{else}} +

Rediger favoritt

+ {{end}} + +
+ + + + + + + + {{if not .IsNew}} + {{if .Fave.ImagePath}} +
+ Nåværende bilde + +
+ {{end}} + {{end}} + + +
    + +
    + Synlighet + + +
    + + +
    + {{end}} +
    +{{end}} diff --git a/web/templates/pages/fave_list.html b/web/templates/pages/fave_list.html new file mode 100644 index 0000000..add8846 --- /dev/null +++ b/web/templates/pages/fave_list.html @@ -0,0 +1,56 @@ +{{define "content"}} +
    +
    +

    Mine favoritter

    +

    {{with .Data}}{{.Total}} favoritter totalt{{end}}

    +
    + + Ny favoritt +
    + +{{with .Data}} + {{if .Faves}} +
    + {{range .Faves}} +
    + {{if .ImagePath}} + Bilde for: {{.Description}} + {{end}} +
    + + {{.Description}} + + {{if eq .Privacy "private"}} + Privat + {{end}} +
    + {{if .Tags}} + + {{end}} +
    + {{end}} +
    + + {{if gt .TotalPages 1}} + + {{end}} + {{else}} +

    Du har ingen favoritter ennå. Legg til din første!

    + {{end}} +{{end}} +{{end}} diff --git a/web/templates/pages/home.html b/web/templates/pages/home.html new file mode 100644 index 0000000..e01b798 --- /dev/null +++ b/web/templates/pages/home.html @@ -0,0 +1,13 @@ +{{define "content"}} +
    +

    Velkommen til {{.SiteName}}

    +

    Del dine favoritter med verden — eller behold dem for deg selv.

    +
    + +{{if not .User}} + +{{end}} +{{end}} diff --git a/web/templates/pages/login.html b/web/templates/pages/login.html new file mode 100644 index 0000000..6dc052f --- /dev/null +++ b/web/templates/pages/login.html @@ -0,0 +1,24 @@ +{{define "head"}} + +{{end}} + +{{define "content"}} + +{{end}} diff --git a/web/templates/pages/reset_password.html b/web/templates/pages/reset_password.html new file mode 100644 index 0000000..d030e43 --- /dev/null +++ b/web/templates/pages/reset_password.html @@ -0,0 +1,24 @@ +{{define "head"}} + +{{end}} + +{{define "content"}} +
    +

    Endre passord

    +

    Du må velge et nytt passord før du kan fortsette.

    +
    + + + + +
    +
    +{{end}} diff --git a/web/templates/pages/signup.html b/web/templates/pages/signup.html new file mode 100644 index 0000000..3a2dc56 --- /dev/null +++ b/web/templates/pages/signup.html @@ -0,0 +1,62 @@ +{{define "head"}} + +{{end}} + +{{define "content"}} +
    + {{with .Data}} + {{if eq .Mode "closed"}} +

    Registrering stengt

    +

    Nye registreringer er for øyeblikket ikke tilgjengelig. Kontakt administrator for tilgang.

    + {{else if eq .Mode "requests"}} +

    Be om tilgang

    +

    Nye brukere må godkjennes av en administrator.

    +
    + + + + + +
    + {{else}} +

    Registrer deg

    +
    + + + + + +
    + {{end}} + {{end}} +

    Har du allerede konto? Logg inn

    +
    +{{end}} diff --git a/web/templates/pages/tag_browse.html b/web/templates/pages/tag_browse.html new file mode 100644 index 0000000..561edbd --- /dev/null +++ b/web/templates/pages/tag_browse.html @@ -0,0 +1,51 @@ +{{define "content"}} +{{with .Data}} +
    +

    Merkelapp: {{.TagName}}

    +

    {{.Total}} offentlige favoritter

    +
    + +{{if .Faves}} +
    + {{range .Faves}} + + {{end}} +
    + + {{if gt .TotalPages 1}} + + {{end}} +{{else}} +

    Ingen offentlige favoritter med denne merkelappen.

    +{{end}} +{{end}} +{{end}} diff --git a/web/templates/partials/tag_suggestions.html b/web/templates/partials/tag_suggestions.html new file mode 100644 index 0000000..8da9612 --- /dev/null +++ b/web/templates/partials/tag_suggestions.html @@ -0,0 +1,6 @@ +{{range .}}
  • {{.Name}}
  • +{{end}}