diff --git a/.gitignore b/.gitignore index a24413d..1a7f126 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,10 @@ xcuserdata/ # nötig ist, steht in Halo.xcworkspace/README.md. Halo.xcodeproj/ node_modules/ + +# .NET +server/**/bin/ +server/**/obj/ +server/data/ +server/cache/ +server/transcode/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9efa6fb --- /dev/null +++ b/LICENSE @@ -0,0 +1,338 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 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 licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Moe Ghoul, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/LICENSE-MPL-2.0 b/LICENSE-MPL-2.0 new file mode 100644 index 0000000..d0a1fa1 --- /dev/null +++ b/LICENSE-MPL-2.0 @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/LICENSES.md b/LICENSES.md new file mode 100644 index 0000000..caa6164 --- /dev/null +++ b/LICENSES.md @@ -0,0 +1,34 @@ +# Lizenzen + +Dieses Repo trägt **zwei** Lizenzen. Welche gilt, hängt vom Verzeichnis ab. + +| Was | Lizenz | Datei | +|---|---|---| +| `server/`, `web/`, `Tools/`, `docs/` | **GPL-2.0-only** | [`LICENSE`](LICENSE) | +| `Halo/`, `HaloTV/`, `HaloTopShelf/`, `HaloUITests/`, `DownloadWidget/`, `Packages/HaloKit/` | **MPL-2.0** | [`LICENSE-MPL-2.0`](LICENSE-MPL-2.0) | + +## Warum zweierlei + +**Der Server steht unter GPL-2.0-only**, derselben Lizenz wie Jellyfin. Damit +darf aus deren Quellcode übernommen werden — bei ffmpeg-Argumenten und +Empfänger-Ansteuerung spart das echte Wochen. + +**Die Apps stehen unter MPL-2.0, weil GPL und App Store sich nicht vertragen.** +Apple entfernte 2011 VLC aus dem Store, nachdem ein Rechteinhaber sich auf +Abschnitt 6 der GPL berufen hatte — „keine weiteren Einschränkungen" gegen +Apples Bedingungen zu Gerätezahl und Kopierschutz. MPL-2.0 ist Copyleft je +Datei, kennt keine Relink-Pflicht und ist App-Store-tauglich. + +## Was das für Beiträge bedeutet + +**Abhängigkeiten im Server müssen GPL-2.0-verträglich sein: MIT, BSD oder +GPL-2.0.** Apache-2.0 ist **ausgeschlossen** — dessen Patentklausel gilt unter +GPL-2.0 Abschnitt 6 als „weitere Einschränkung". Ein nennenswerter Teil des +.NET-Umfelds steht unter Apache-2.0, deshalb: vor jedem `PackageReference` die +Lizenz prüfen und sie im Commit nennen. + +Dasselbe gilt für Werkzeuge, die nur beim Entwickeln laufen. Das Testwerk ist +aus diesem Grund NUnit (MIT) und nicht xUnit (Apache-2.0). + +**ffmpeg** wird als eigener Prozess aufgerufen und nicht eingebunden. Das hält +die Lizenzen getrennt — und erlaubt nebenbei, die Argumente zu protokollieren. diff --git a/docs/superpowers/specs/2026-10-03-halo-server-design.md b/docs/superpowers/specs/2026-10-03-halo-server-design.md new file mode 100644 index 0000000..c94d1ad --- /dev/null +++ b/docs/superpowers/specs/2026-10-03-halo-server-design.md @@ -0,0 +1,253 @@ +# Halo-Server — Entwurf + +*3. Oktober 2026* + +## Warum es ihn gibt + +Ein Download brach die Sprachwahl. Jellyfins Transcode-Endpunkt bildet **eine +Tonspur je Sitzung** ab; was offline landet, ist einspurig, und welche Spur es +ist, entscheidet der Server. Einmal war es die Audiodeskription — drei Gigabyte +Mobilfunk für eine Datei, die niemand hören wollte. + +Am Server gemessen, nicht vermutet: + +- `static=true` liefert die Datei unverändert — alle Spuren, aber Matroska. Die + Magie am Dateianfang ist `1a45dfa3`, auch wenn im Pfad `.mp4` steht. +- `stream.mp4` bildet genau eine Tonspur ab. +- Die HLS-Liste führt **eine** Variante und **keine** `EXT-X-MEDIA`-Tonspuren. +- Beim Umpacken verliert Jellyfin die Sprachkennungen: alle Spuren kommen als + `und` an. + +Das liegt weder an MP4 — das trägt mehrere Tonspuren — noch an AVFoundation. +Es liegt am Transcoder. Ein Jellyfin-Plugin könnte es beheben; die Entscheidung +fiel für einen eigenen Server. + +**Was Halo werden soll:** ein Server, der *„eigentlich nichts mit Jellyfin zu +tun hat, aber grundsätzlich die gleichen Funktionen bietet"*. Funktionsgleich, +unabhängig, ohne Nachziehen bei fremden Veröffentlichungen. Open Source, für +jeden, nicht für einen Haushalt. + +--- + +## Entscheidungen + +| | | Preis, der bewusst gezahlt wird | +|---|---|---| +| **Sprache** | C# / .NET 10 | — | +| **Schnittstelle** | eigene, von Anfang an | Die App braucht ein eigenes Backend-Modul; bis es steht, gibt es keinen Zwischenstand zum Ausprobieren | +| **Datenbank** | SQLite | Schreibzugriffe laufen nacheinander. Bei 40 000 Titeln und laufendem Scan spürbar — Jellyfins bekanntester Schmerzpunkt | +| **Metadaten** | TMDB | Jeder Betreiber braucht einen eigenen Schlüssel; gepflegte Bestände werden unnötig neu nachgeschlagen | +| **Anmeldung** | Passwort, Geräte-Token, Code-Verfahren | Zwei Anmeldewege statt einem, jeder mit eigenen Sicherheitsüberlegungen | +| **Oberfläche** | Client **und** `/admin`, getrennte Bereiche, vom Server ausgeliefert | — | +| **Live TV** | HDHomeRun und IPTV (m3u + XMLTV) | Keine DVB-Karte. Wer eine hat, bekommt sie nicht unterstützt | +| **Übernahme** | keine | Jeder Umsteiger verliert Gesehen-Status und Fortschritt | +| **Laufzeit** | Docker, amd64 und arm64 | — | +| **Hardware** | VAAPI über `/dev/dri` | Keine NVENC-Unterstützung in der ersten Fassung | +| **Lizenz** | GPL-2.0-only | Siehe unten — die folgenreichste Zeile dieses Dokuments | + +### Die Lizenz ist eine Bauvorschrift + +GPL-2.0-only ist dieselbe Lizenz wie Jellyfin. Deren Quellcode darf also +gelesen **und übernommen** werden. + +**Der Preis trifft jede Abhängigkeit, die je hinzukommt:** GPL-2.0-only ist +**unverträglich mit Apache-2.0**. Die Patentklausel der Apache-Lizenz gilt +unter GPL-2.0 Abschnitt 6 als „weitere Einschränkung". Ein nennenswerter Teil +des .NET-Umfelds steht unter Apache-2.0. + +> **Regel für jede neue Abhängigkeit: MIT, BSD oder GPL-2.0-verträglich. +> Apache-2.0 ist ausgeschlossen.** Vor jedem `PackageReference` die Lizenz +> prüfen und im Commit nennen. + +Microsofts eigene Pakete — ASP.NET Core, EF Core — stehen unter MIT und sind +unbedenklich. + +ffmpeg wird als **eigener Prozess** aufgerufen, nicht über Bindings +eingebunden. Das hält die Lizenzen sauber getrennt und erlaubt nebenbei, die +Argumente zu protokollieren — ohne das ist „warum ruckelt das" nicht zu +beantworten. + +**Die App** steht unter **MPL-2.0**, nicht unter GPL: GPL und App Store +vertragen sich nicht. Apple entfernte 2011 VLC aus dem Store, nachdem ein +Rechteinhaber sich auf Abschnitt 6 berufen hatte — Apples Bedingungen +schreiben Gerätezahl und Kopierschutz vor. MPL-2.0 ist Copyleft je Datei, ohne +Relink-Pflicht, und App-Store-tauglich. + +*Umlizenzieren geht nur, solange ein einziger Rechteinhaber da ist. Sobald +Fremde beitragen, braucht jede Änderung deren Zustimmung.* + +--- + +## Grundsätze + +- **Nichts fest verdrahtet.** Jeder Pfad, jeder Port, jede Kennung aus + Konfiguration — Umgebungsvariablen und `appsettings`, beides überschreibbar. + Das Setup des Autors ist ein *Beispiel in der Dokumentation*, keine Annahme + im Code. +- **Kein Zustand im Image.** Datenbank, Konfiguration und Bilder-Cache liegen + in eingehängten Verzeichnissen. +- **Medien werden nur gelesen.** Schreibgeschützt eingehängt. +- **Mehrbenutzer von Anfang an.** Fortschritt und Gesehen-Status je Benutzer + nachträglich einzuziehen ist ein Umbau am Datenmodell, kein Zusatz. + +--- + +## Aufbau + +``` +server/ + Halo.sln + src/ + Halo.Api/ HTTP-Schnittstelle, Authentifizierung, Auslieferung der Oberfläche + Halo.Core/ Domäne: Benutzer, Bibliothek, Fortschritt. Kennt kein HTTP + Halo.Data/ EF Core, SQLite, Migrationen + tests/ + Halo.Core.Tests/ + Halo.Api.Tests/ + Dockerfile + docker-compose.example.yml +web/ Client (vorhanden) + /admin (neu) +``` + +Später, je Stufe: `Halo.Media` (ffmpeg), `Halo.Metadata` (TMDB), +`Halo.LiveTV` (HDHomeRun, m3u). + +**Der Node-Proxy unter `web/server` entfällt.** Er löste CORS und das +http/https-Problem, weil Jellyfin woanders lief. Liefert Halo die Seite selbst +aus, ist er die Adresse, an der alles hängt — beide Probleme verschwinden mit +ihm. + +--- + +## Stufen + +| | Inhalt | +|---|---| +| **1** | Gerüst: Benutzer, Anmeldung, Einrichtung, Oberflächen-Gerüst, Docker | +| **2** | Bibliothek und Metadaten: Scanner, Dateinamen-Erkennung, TMDB, Bilder | +| **3** | Ausliefern: direktes Abspielen, Umpacken, VAAPI, **Download mit allen Spuren** | +| **4** | Fortschritt, Gesehen-Status, Favoriten, Vorschläge | +| **5** | Live TV: HDHomeRun, m3u mit XMLTV | + +Gewählt in Kenntnis des Preises: Stufe 1 spielt noch keinen Film ab. Für ein +offenes Projekt, bei dem Fremde den Server in Betrieb nehmen müssen, ist es +trotzdem die ehrliche Reihenfolge — ein Server ohne Einrichtung ist für einen +Fremden kein Server. + +### Was Stufe 3 anders macht als Jellyfin + +``` +ffmpeg -i datei.mkv -map 0 -c copy -c:s mov_text out.mp4 +``` + +`-map 0` nimmt **alle** Ströme mit, `-c copy` fasst Bild und Ton nicht an. Das +kostet den Server fast nichts und liefert eine MP4 mit allen Ton- und +Textspuren — offline wählbar, wie bei jedem anderen Anbieter auch. +Sprachkennungen werden dabei ausdrücklich durchgereicht. + +### Was Stufe 4 anders macht als Jellyfin + +**Fortschritt ohne Schwelle.** Jellyfin merkt sich unterhalb eines +Mindestanteils und einer Mindestlaufzeit gar nichts; wer zehn Minuten eines +Films sieht und abbricht, findet beim nächsten Mal keinen Anknüpfungspunkt. +Halo speichert von der ersten Sekunde an, laufend, je Benutzer. + +*Die genauen Jellyfin-Werte stehen aus dem Gedächtnis hier nicht; sie werden +vor dem Bauen gegen die laufende Installation geprüft, damit die Begründung +belegt ist und nicht behauptet.* + +--- + +## Stufe 1 im Einzelnen + +### Daten + +| Tabelle | Felder | +|---|---| +| `User` | Id, UserName, PasswordHash, IsAdministrator, CreatedAt | +| `DeviceToken` | Id, UserId, TokenHash, DeviceName, DeviceId, CreatedAt, LastSeenAt, RevokedAt | +| `PendingAuthCode` | Id, Code, Handle, DeviceName, CreatedAt, ExpiresAt, ApprovedByUserId, ConsumedAt | +| `Library` | Id, Name, Kind, Path, CreatedAt | +| `ServerSetting` | Key, Value | + +**Token werden gehasht abgelegt, nie im Klartext.** Was der Client bekommt, +sieht der Server danach nie wieder — gestohlene Datenbank heißt dann gestohlene +Hashes, nicht gestohlene Zugänge. + +### Schnittstelle + +``` +GET /api/v1/system/info Fassung, ob eingerichtet werden muss +POST /api/v1/system/setup Erstes Administratorkonto — nur solange keines existiert + +POST /api/v1/auth/login Benutzername und Passwort → Token +POST /api/v1/auth/logout Widerruft das eigene Token +GET /api/v1/auth/me Wer bin ich + +POST /api/v1/auth/code Fernseher startet: → sechsstelliger Code + Abholschein +GET /api/v1/auth/code/{schein} Fernseher fragt nach → wartend | bestätigt + Token | abgelaufen +POST /api/v1/auth/code/{code} Telefon bestätigt (angemeldet) + +GET /api/v1/users Liste (Administrator) +POST /api/v1/users Anlegen (Administrator) +GET /api/v1/libraries Bibliotheken +POST /api/v1/libraries Anlegen (Administrator) + +GET /health Gesundheit, ohne Anmeldung +``` + +### Anmeldung mit Code + +Für die Fernbedienung: Passwörter dort einzutippen ist eine Zumutung, die man +selbst jedes Mal spürt. + +1. Der Fernseher fordert einen Code an und bekommt zusätzlich einen + **Abholschein**, den nur er kennt. +2. Auf dem Bildschirm steht der sechsstellige Code. +3. Am Telefon, angemeldet, wird er bestätigt. +4. Der Fernseher fragt mit seinem Abholschein nach und bekommt sein Token. + +**Der Code allein genügt nie**, um ein Token abzuholen — sonst könnte jemand +sechsstellige Zahlen durchprobieren. Dazu: Gültigkeit wenige Minuten, +Versuchsbegrenzung, einmalige Verwendung. + +### Einrichtung + +`POST /api/v1/system/setup` arbeitet **nur**, solange kein Benutzer existiert. +Danach antwortet es ablehnend, auch unangemeldet — sonst wäre ein frisch +gestarteter Server für den ersten Fremden im Netz offen. + +### Konfiguration + +| Variable | Bedeutung | Voreinstellung | +|---|---|---| +| `HALO_DATA` | Datenbank und Konfiguration | `/config` | +| `HALO_CACHE` | Bilder und Zwischenstände | `/cache` | +| `HALO_TRANSCODE` | Kratzplatz fürs Umrechnen | `/transcode` | +| `HALO_PORT` | Port | `8080` | +| `TZ` | Zeitzone | `UTC` | +| `HALO_RATELIMIT_SIGNIN` | Anmeldeversuche je Minute und Adresse | `10` | + +Die Benutzerkennung steht **nicht** in der Umgebung: das Image läuft als +`1000:1000`, und wer andere Kennungen hat, setzt Dockers eigenes +`user: ":"`. Ein eigenes Startskript mit `PUID`/`PGID` — wie es im +selbstgehosteten Umfeld üblich ist — bräuchte root im Container, und dafür gibt +es hier keinen Grund. + +Medienpfade stehen **nicht** hier: sie werden in der Oberfläche als +Bibliotheken angelegt und liegen in der Datenbank. Wer sie in die Compose-Datei +schriebe, müsste den Container neu starten, um eine Bibliothek hinzuzufügen. + +--- + +## Nachweis + +- `dotnet test` für Domäne und Schnittstelle. +- Der Einrichtungsassistent wird gegen eine **leere** Datenbank gefahren: ein + frisch gestarteter Container führt durch die Einrichtung und legt einen + Administrator an. +- `POST /api/v1/system/setup` ein zweites Mal muss **abgelehnt** werden. +- Ein Code wird am Telefon bestätigt und am Fernseher abgeholt, ohne dass ein + Passwort getippt wurde. +- Ein Abholschein, der nicht zum Code gehört, bekommt **kein** Token. +- Das Image baut für `linux/amd64` und `linux/arm64`. diff --git a/server/.dockerignore b/server/.dockerignore new file mode 100644 index 0000000..2e264a2 --- /dev/null +++ b/server/.dockerignore @@ -0,0 +1,6 @@ +**/bin/ +**/obj/ +**/*.user +data/ +cache/ +transcode/ diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..d27bb1e --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,49 @@ +# syntax=docker/dockerfile:1 + +# Gebaut wird auf der Architektur des Bauwirts, übersetzt wird für die des +# Ziels — `dotnet publish -a` kann das. Ohne diese Trennung liefe der Bau für +# arm64 unter Emulation und dauerte ein Vielfaches. +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build +ARG TARGETARCH +WORKDIR /src + +# Erst die Projektdateien, dann wiederherstellen: so bleibt die +# Paket-Wiederherstellung in der Ebenenzwischenablage, solange sich keine +# Abhängigkeit ändert. Ohne diesen Schritt lädt jeder Bau alles neu. +COPY src/Halo.Api/Halo.Api.csproj src/Halo.Api/ +COPY src/Halo.Core/Halo.Core.csproj src/Halo.Core/ +COPY src/Halo.Data/Halo.Data.csproj src/Halo.Data/ +RUN dotnet restore src/Halo.Api/Halo.Api.csproj -a $TARGETARCH + +COPY . . +RUN dotnet publish src/Halo.Api/Halo.Api.csproj -a $TARGETARCH -c Release -o /app --no-restore + + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime + +# **Die Verzeichnisse müssen hier angelegt werden, nicht erst beim Start.** +# Docker legt den Einhängepunkt eines frischen benannten Volumes sonst als +# `root` an und übernimmt für ein leeres Volume die Rechte aus dem Image — +# gibt es das Verzeichnis im Image nicht, erbt es `root:root`, und der erste +# Start scheitert für jeden, der kein Bind Mount benutzt. +RUN mkdir -p /config /cache /transcode && chown -R 1000:1000 /config /cache /transcode + +# **Kein root.** Die Kennung 1000 ist die des ersten Benutzers auf fast jedem +# Linux und auf den üblichen NAS-Geräten — wessen Dateien anders gehören, setzt +# in der Compose-Datei `user: ":"`. Das ist Docker-Bordmittel und +# braucht weder ein Startskript noch root im Container. +USER 1000:1000 + +ENV HALO_DATA=/config \ + HALO_CACHE=/cache \ + HALO_TRANSCODE=/transcode \ + ASPNETCORE_URLS=http://+:8080 \ + DOTNET_gcServer=0 + +WORKDIR /app +COPY --from=build /app . + +EXPOSE 8080 +VOLUME ["/config", "/cache", "/transcode"] + +ENTRYPOINT ["dotnet", "Halo.Api.dll"] diff --git a/server/Halo.slnx b/server/Halo.slnx new file mode 100644 index 0000000..021941a --- /dev/null +++ b/server/Halo.slnx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..6c27156 --- /dev/null +++ b/server/README.md @@ -0,0 +1,128 @@ +# Halo-Server + +Ein Medienserver, der dieselben Dinge kann wie Jellyfin — und zwei, die dort +nicht gehen. + +**Stand: Stufe 1 von 5.** Es gibt Benutzer, Anmeldung, Einrichtung und das +Gerüst. Einen Film spielt er noch nicht ab. Der Entwurf samt Begründungen steht +in [`docs/superpowers/specs/2026-10-03-halo-server-design.md`](../docs/superpowers/specs/2026-10-03-halo-server-design.md). + +## Warum + +**Download mit allen Tonspuren.** Jellyfins Transcode-Endpunkt bildet eine +Tonspur je Sitzung ab; was offline landet, ist einspurig, und welche Spur es +ist, entscheidet der Server. Einmal war es die Audiodeskription — drei Gigabyte +Mobilfunk für eine Datei, die niemand hören wollte. + +**Fortschritt ohne Schwelle.** Jellyfin merkt sich unterhalb eines +Mindestanteils gar nichts. Wer zehn Minuten sieht und abbricht, findet beim +nächsten Mal keinen Anknüpfungspunkt. + +## Betreiben + +```bash +cp docker-compose.example.yml docker-compose.yml +# Pfade anpassen — jeder darin ist ein Beispiel, keiner stimmt bei dir. +docker compose up -d +``` + +Dann `http://localhost:8080` öffnen; der Einrichtungsassistent legt das erste +Administratorkonto an. Danach verschliesst sich dieser Weg von selbst. + +### Einstellungen + +| Variable | Bedeutung | Voreinstellung im Image | +|---|---|---| +| `HALO_DATA` | Datenbank und Einstellungen. **Das Einzige, was gesichert werden muss.** | `/config` | +| `HALO_CACHE` | Bilder und Zwischenstände. Darf verlorengehen. | `/cache` | +| `HALO_TRANSCODE` | Kratzplatz fürs Umrechnen. Am besten auf eine SSD. | `/transcode` | +| `ASPNETCORE_URLS` | Worauf gelauscht wird | `http://+:8080` | +| `TZ` | Zeitzone | `UTC` | +| `HALO_RATELIMIT_SIGNIN` | Anmeldeversuche je Minute und Adresse | `10` | +| `HALO_RATELIMIT_POLLING` | Nachfragen je Minute und Adresse | `120` | + +**Medienpfade stehen hier nicht.** Sie werden in der Oberfläche als +Bibliotheken angelegt und liegen in der Datenbank — sonst müsste der Container +neu starten, um eine Bibliothek hinzuzufügen. + +### Rechte + +Das Image läuft als `1000:1000`, **nicht als root**. Gehören die eingehängten +Verzeichnisse jemand anderem, trage in der Compose-Datei +`user: ":"` ein (`id -u` und `id -g` auf dem Wirt sagen, welche) +oder übereigne sie mit `chown`. + +Stimmt etwas nicht, bricht der Server **beim Start** ab und nennt Variable, +Pfad, seine eigene Kennung und den nächsten Schritt. Das ist Absicht: ohne +diese Meldung stünde dort nur „unable to open database file". + +### Hardware fürs Umrechnen + +`/dev/dri` durchreichen — VAAPI deckt Intel wie AMD ab. Fehlt es, rechnet Halo +in Software; das ist langsamer, aber es läuft. **Zum blossen Umpacken wird gar +keine Hardware gebraucht**, und das ist der Weg, der den meisten Beständen +hilft. + +## Entwickeln + +```bash +dotnet test # 55 Tests +dotnet run --project src/Halo.Api # auf http://localhost:5000 +``` + +Ohne gesetzte Variablen legt der Server `data/`, `cache/` und `transcode/` +neben dem Programm an. + +```bash +# Image bauen, beide Architekturen +docker buildx build --platform linux/amd64,linux/arm64 -t halo:dev . + +# Eine Migration nach einer Modelländerung +dotnet ef migrations add --project src/Halo.Data --startup-project src/Halo.Api --output-dir Migrations +``` + +Migrationen wandern **beim Start** des Servers, nicht über ein eigenes +Kommando. + +### Aufbau + +| Projekt | Aufgabe | +|---|---| +| `Halo.Core` | Domäne: Benutzer, Anmeldung, Bibliotheken. Kennt kein HTTP und keine Datenbank | +| `Halo.Data` | EF Core, SQLite, Migrationen | +| `Halo.Api` | Endpunkte, Authentifizierung, Auslieferung der Oberfläche | + +Was sicherheitsrelevant ist, liegt in `Halo.Core` — dort ist es ohne Server +prüfbar, und die Tests dazu sind die, die am meisten wert sind. + +### Zwei Entscheidungen, die beim Lesen Fragen aufwerfen + +**Zeitpunkte liegen als Unix-Millisekunden in der Datenbank, nicht als Text.** +SQLite hat keinen Zeittyp; ein `DateTimeOffset` landet sonst als Text mitsamt +Zonenversatz, und dann steht `…T12:00+02:00` neben `…T11:00Z` — derselbe +Augenblick, als Text aber falsch herum sortiert. EF weigert sich deshalb, +`ExpiresAt > jetzt` überhaupt zu übersetzen. + +**Token sind keine JWT.** Der Server schlägt sie nach, statt sie zu prüfen. +Ein nachgeschlagenes Token lässt sich **sofort** widerrufen; ein signiertes +gilt bis zum Ablauf weiter, und für ein verlorenes Telefon ist das der falsche +Satz. In der Datenbank steht nur der Fingerabdruck. + +## Anmeldung am Fernseher + +Ein Passwort auf der Apple-TV-Fernbedienung zu tippen ist eine Zumutung. +Stattdessen: + +1. Der Fernseher fordert an und bekommt einen **sechsstelligen Code** für den + Bildschirm und einen **Abholschein**, den nur er kennt. +2. Am Telefon, angemeldet, wird der Code bestätigt — dort steht, welches Gerät. +3. Der Fernseher holt mit seinem Abholschein das Token ab. + +**Der Code allein holt nie ein Token ab.** Ohne den Abholschein wären +sechsstellige Codes ein Türschloss mit einer Million Schlüsseln. + +## Lizenz + +**GPL-2.0-only.** Abhängigkeiten müssen dazu passen: MIT, BSD oder GPL-2.0. +**Apache-2.0 ist ausgeschlossen** — Einzelheiten und der Grund stehen in +[`LICENSES.md`](../LICENSES.md). diff --git a/server/docker-compose.example.yml b/server/docker-compose.example.yml new file mode 100644 index 0000000..8ead38f --- /dev/null +++ b/server/docker-compose.example.yml @@ -0,0 +1,50 @@ +# Beispiel, kein fertiger Betrieb. Jeder Pfad hier gehört angepasst. +# +# Übernommen aus einem laufenden Plex-Container auf einem UGREEN-NAS — die +# Form ist bewährt, die Werte sind es nur dort. + +services: + halo: + image: ghcr.io/scarriffle/halo:latest + container_name: halo + restart: unless-stopped + + ports: + - "8080:8080" + + environment: + - TZ=Europe/Zurich + + # Wem die Dateien auf dem Wirt gehören. 1000:1000 ist die Voreinstellung + # im Image; wer andere Kennungen hat, trägt sie hier ein — `id -u` und + # `id -g` auf dem Wirt sagen, welche. + user: "1000:1000" + + volumes: + # Datenbank und Einstellungen. **Das Einzige, was gesichert werden muss.** + - /volume4/CRITICAL/Docker/Halo/config:/config + + # Bilder und Zwischenstände. Darf verlorengehen, baut sich neu auf. + - /volume4/CRITICAL/Docker/Halo/cache:/cache + + # Kratzplatz fürs Umrechnen. Am besten auf eine SSD und nicht dorthin, + # wo die Medien liegen — hier wird viel und kurzlebig geschrieben. + - /volume1/Transcode:/transcode + + # Die Medien. **Schreibgeschützt**, und das ist Absicht: Halo liest nur. + # Was hier eingehängt wird, ist der Pfad, den du später in der Oberfläche + # als Bibliothek anlegst — also `/media`, nicht `/volume4/MYFLIX`. + - /volume4/MYFLIX:/media:ro + + # Hardware fürs Umrechnen. Intel wie AMD laufen über VAAPI an derselben + # Stelle. Fehlt die Zeile, rechnet Halo in Software — langsamer, aber es + # läuft. Zum blossen Umpacken wird sie ohnehin nicht gebraucht. + devices: + - /dev/dri:/dev/dri + + healthcheck: + test: ["CMD", "dotnet", "--info"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 20s diff --git a/server/dotnet-tools.json b/server/dotnet-tools.json new file mode 100644 index 0000000..5c1165b --- /dev/null +++ b/server/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "10.0.12", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/server/src/Halo.Api/Auth/TokenAuthentication.cs b/server/src/Halo.Api/Auth/TokenAuthentication.cs new file mode 100644 index 0000000..8df59d7 --- /dev/null +++ b/server/src/Halo.Api/Auth/TokenAuthentication.cs @@ -0,0 +1,79 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Halo.Core.Auth; +using Halo.Data; +using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace Halo.Api.Auth; + +/// Weist Anfragen über ein Geräte-Token aus. +/// +/// +/// +/// Authorization: Bearer <token>. Der Server hasht das Vorgezeigte +/// und sucht den Fingerabdruck — das Token selbst steht nirgends in der +/// Datenbank und ist aus ihr auch nicht zu gewinnen. +/// +/// +/// Keine JWT. Ein Token, das der Server nachschlägt, lässt sich sofort +/// widerrufen; ein signiertes gilt bis zum Ablauf weiter, und für ein +/// verlorenes Telefon ist das der falsche Satz. +/// +/// +public sealed class TokenAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + HaloContext db, + TimeProvider clock) : AuthenticationHandler(options, logger, encoder) +{ + public const string SchemeName = "HaloToken"; + public const string DeviceTokenIdClaim = "halo:device"; + + protected override async Task HandleAuthenticateAsync() + { + if (!Request.Headers.TryGetValue("Authorization", out var kopfzeile)) return AuthenticateResult.NoResult(); + + var roh = kopfzeile.ToString(); + const string vorsatz = "Bearer "; + if (!roh.StartsWith(vorsatz, StringComparison.OrdinalIgnoreCase)) return AuthenticateResult.NoResult(); + + var token = roh[vorsatz.Length..].Trim(); + if (token.Length == 0) return AuthenticateResult.NoResult(); + + var fingerabdruck = Secrets.Fingerprint(token); + var eintrag = await db.DeviceTokens.FirstOrDefaultAsync(t => t.TokenFingerprint == fingerabdruck); + + var jetzt = clock.GetUtcNow(); + if (eintrag is null || !eintrag.IsValid(jetzt)) return AuthenticateResult.Fail("Token gilt nicht."); + + var benutzer = await db.Users.FindAsync(eintrag.UserId); + if (benutzer is null) return AuthenticateResult.Fail("Token gilt nicht."); + + // Für die Geräteliste: „zuletzt gesehen". Höchstens einmal je Stunde + // geschrieben — bei jeder Anfrage zu schreiben hiesse, jede Anfrage in + // einen Schreibzugriff zu verwandeln, und SQLite serialisiert die. + if (jetzt - eintrag.LastSeenAt > TimeSpan.FromHours(1)) + { + eintrag.LastSeenAt = jetzt; + await db.SaveChangesAsync(); + } + + var ausweis = new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, benutzer.Id.ToString()), + new Claim(ClaimTypes.Name, benutzer.UserName), + new Claim(DeviceTokenIdClaim, eintrag.Id.ToString()), + .. benutzer.IsAdministrator ? new[] { new Claim(ClaimTypes.Role, HaloRoles.Administrator) } : [], + ], SchemeName); + + return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(ausweis), SchemeName)); + } +} + +public static class HaloRoles +{ + public const string Administrator = "administrator"; +} diff --git a/server/src/Halo.Api/Endpoints/AuthEndpoints.cs b/server/src/Halo.Api/Endpoints/AuthEndpoints.cs new file mode 100644 index 0000000..8c79be6 --- /dev/null +++ b/server/src/Halo.Api/Endpoints/AuthEndpoints.cs @@ -0,0 +1,190 @@ +using System.Security.Claims; +using Halo.Api.Auth; +using Halo.Core.Auth; +using Halo.Core.Users; +using Halo.Data; +using Microsoft.EntityFrameworkCore; + +namespace Halo.Api.Endpoints; + +public static class AuthEndpoints +{ + /// Ein Hash, gegen den geprüft wird, wenn es den Benutzer gar nicht gibt. + /// + /// + /// Gegen das Abfragen von Benutzernamen über die Uhr. Ohne ihn + /// antwortet der Server bei einem unbekannten Namen sofort und bei einem + /// bekannten erst nach dem Argon2-Lauf — vierzig Millisekunden Unterschied, + /// und damit lässt sich eine Liste gültiger Konten zusammentragen. + /// + private static readonly Lazy Strohmann = + new(() => PasswordHasher.Hash(Secrets.Create()), LazyThreadSafetyMode.ExecutionAndPublication); + + public static void MapAuth(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/auth/login", async ( + LoginRequest anfrage, HaloContext db, TimeProvider clock) => + { + var name = anfrage.UserName.Trim(); + var benutzer = await db.Users.FirstOrDefaultAsync(u => u.UserName == name); + + if (benutzer is null) + { + // Dieselbe Arbeit wie bei einem echten Konto, dann ablehnen. + PasswordHasher.Verify(anfrage.Password, Strohmann.Value); + return Abgelehnt(); + } + + if (!PasswordHasher.Verify(anfrage.Password, benutzer.PasswordHash)) return Abgelehnt(); + + // Gelegenheit genutzt: hier liegt das Passwort im Klartext vor, und + // nur hier lässt sich ein nach alten Kennwerten gebildeter Hash + // überhaupt erneuern. + if (PasswordHasher.NeedsRehash(benutzer.PasswordHash)) + benutzer.PasswordHash = PasswordHasher.Hash(anfrage.Password); + + var antwort = await TokenAusstellen(db, clock, benutzer, anfrage.DeviceName, anfrage.DeviceId); + await db.SaveChangesAsync(); + return Results.Ok(antwort); + }).AllowAnonymous().RequireRateLimiting(HaloRateLimits.SignIn); + + app.MapPost("/api/v1/auth/logout", async (ClaimsPrincipal wer, HaloContext db, TimeProvider clock) => + { + if (!Guid.TryParse(wer.FindFirstValue(TokenAuthenticationHandler.DeviceTokenIdClaim), out var id)) + return Results.Unauthorized(); + + var eintrag = await db.DeviceTokens.FindAsync(id); + if (eintrag is not null) + { + eintrag.RevokedAt = clock.GetUtcNow(); + await db.SaveChangesAsync(); + } + return Results.NoContent(); + }).RequireAuthorization(); + + app.MapGet("/api/v1/auth/me", (ClaimsPrincipal wer) => + Guid.TryParse(wer.FindFirstValue(ClaimTypes.NameIdentifier), out var id) + ? Results.Ok(new AuthenticatedUser( + id, + wer.FindFirstValue(ClaimTypes.Name) ?? "", + wer.IsInRole(HaloRoles.Administrator))) + : Results.Unauthorized()) + .RequireAuthorization(); + + MapCodeFlow(app); + } + + /// Anmelden mit einem Code auf dem Bildschirm. + private static void MapCodeFlow(IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/auth/code", async (CodeRequest anfrage, HaloContext db, TimeProvider clock) => + { + var jetzt = clock.GetUtcNow(); + + // Beiläufig aufräumen. Ein eigener Hintergrunddienst für ein paar + // Zeilen je Tag wäre Aufwand ohne Gegenwert. + await db.AuthCodes.Where(c => c.ExpiresAt < jetzt).ExecuteDeleteAsync(); + + var abholschein = Secrets.Create(); + var code = new AuthCode + { + Code = AuthCode.NewCode(), + HandleFingerprint = Secrets.Fingerprint(abholschein), + DeviceName = Kürzen(anfrage.DeviceName, 128), + DeviceId = Kürzen(anfrage.DeviceId, 128), + CreatedAt = jetzt, + ExpiresAt = jetzt + AuthCode.Lifetime, + }; + db.AuthCodes.Add(code); + await db.SaveChangesAsync(); + + return Results.Ok(new CodeResponse(code.Code, abholschein, code.ExpiresAt)); + }).AllowAnonymous().RequireRateLimiting(HaloRateLimits.SignIn); + + app.MapGet("/api/v1/auth/code/{handle}", async ( + string handle, HaloContext db, TimeProvider clock) => + { + var jetzt = clock.GetUtcNow(); + var fingerabdruck = Secrets.Fingerprint(handle); + var code = await db.AuthCodes.FirstOrDefaultAsync(c => c.HandleFingerprint == fingerabdruck); + + if (code is null || code.IsExpired(jetzt) || code.ConsumedAt is not null) + return Results.Ok(new CodeState("expired", null)); + + if (code.ApprovedByUserId is not { } benutzerId) + return Results.Ok(new CodeState("pending", null)); + + var benutzer = await db.Users.FindAsync(benutzerId); + if (benutzer is null) return Results.Ok(new CodeState("expired", null)); + + // Einmal abgeholt ist abgeholt — vor dem Ausstellen gesetzt, damit + // zwei gleichzeitige Abholungen nicht zwei Token ergeben. + code.ConsumedAt = jetzt; + var antwort = await TokenAusstellen(db, clock, benutzer, code.DeviceName, code.DeviceId); + await db.SaveChangesAsync(); + + return Results.Ok(new CodeState("approved", antwort)); + }).AllowAnonymous().RequireRateLimiting(HaloRateLimits.Polling); + + app.MapPost("/api/v1/auth/code/{code}", async ( + string code, ClaimsPrincipal wer, HaloContext db, TimeProvider clock) => + { + if (!Guid.TryParse(wer.FindFirstValue(ClaimTypes.NameIdentifier), out var benutzerId)) + return Results.Unauthorized(); + + var jetzt = clock.GetUtcNow(); + var offen = await db.AuthCodes.FirstOrDefaultAsync(c => + c.Code == code && c.ApprovedByUserId == null && c.ExpiresAt > jetzt); + + if (offen is null) + return Results.Problem("Dieser Code gilt nicht mehr.", statusCode: StatusCodes.Status404NotFound); + + offen.ApprovedByUserId = benutzerId; + await db.SaveChangesAsync(); + + // Damit am Telefon steht, was man da gerade hereinlässt. + return Results.Ok(new { device = offen.DeviceName }); + }).RequireAuthorization().RequireRateLimiting(HaloRateLimits.SignIn); + } + + /// Stellt ein Geräte-Token aus und löst ein älteres desselben Geräts ab. + /// + /// + /// Ohne das Ablösen füllt sich die Geräteliste mit Karteileichen: jede + /// erneute Anmeldung derselben App hinterliesse einen weiteren Eintrag, + /// und nach einem Jahr weiss niemand mehr, welches Telefon welches ist. + /// + private static async Task TokenAusstellen( + HaloContext db, TimeProvider clock, User benutzer, string geräteName, string geräteKennung) + { + var jetzt = clock.GetUtcNow(); + var kennung = Kürzen(geräteKennung, 128); + + await db.DeviceTokens + .Where(t => t.UserId == benutzer.Id && t.DeviceId == kennung && t.RevokedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(t => t.RevokedAt, jetzt)); + + var token = Secrets.Create(); + db.DeviceTokens.Add(new DeviceToken + { + UserId = benutzer.Id, + TokenFingerprint = Secrets.Fingerprint(token), + DeviceName = Kürzen(geräteName, 128), + DeviceId = kennung, + CreatedAt = jetzt, + LastSeenAt = jetzt, + }); + + return new LoginResponse(token, new AuthenticatedUser(benutzer.Id, benutzer.UserName, benutzer.IsAdministrator)); + } + + /// Eine Antwort, die nicht verrät, welche Hälfte falsch war. + private static IResult Abgelehnt() => + Results.Problem("Benutzername oder Passwort stimmt nicht.", statusCode: StatusCodes.Status401Unauthorized); + + private static string Kürzen(string? wert, int höchstens) + { + var sauber = (wert ?? "").Trim(); + return sauber.Length <= höchstens ? sauber : sauber[..höchstens]; + } +} diff --git a/server/src/Halo.Api/Endpoints/Contracts.cs b/server/src/Halo.Api/Endpoints/Contracts.cs new file mode 100644 index 0000000..533ae68 --- /dev/null +++ b/server/src/Halo.Api/Endpoints/Contracts.cs @@ -0,0 +1,33 @@ +namespace Halo.Api.Endpoints; + +// Was über die Leitung geht. Bewusst eigene Typen und nicht die der Domäne: +// sonst wandert jede Umbenennung im Datenmodell ungefragt in die Schnittstelle +// und bricht Clients, die niemand mehr aktualisiert. + +public sealed record SystemInfo(string Version, bool NeedsSetup); + +public sealed record SetupRequest(string UserName, string Password); + +public sealed record LoginRequest(string UserName, string Password, string DeviceName, string DeviceId); + +public sealed record AuthenticatedUser(Guid Id, string UserName, bool IsAdministrator); + +public sealed record LoginResponse(string Token, AuthenticatedUser User); + +public sealed record CodeRequest(string DeviceName, string DeviceId); + +/// Was der Fernseher nach dem Anfordern bekommt. +/// +/// +/// Der Handle ist das Geheimnis und wird nicht angezeigt — der +/// Code ist das, was auf dem Bildschirm steht. +/// +public sealed record CodeResponse(string Code, string Handle, DateTimeOffset ExpiresAt); + +public sealed record CodeState(string State, LoginResponse? Login); + +public sealed record CreateUserRequest(string UserName, string Password, bool IsAdministrator); + +public sealed record LibraryResponse(Guid Id, string Name, string Kind, string Path); + +public sealed record CreateLibraryRequest(string Name, string Kind, string Path); diff --git a/server/src/Halo.Api/Endpoints/ManagementEndpoints.cs b/server/src/Halo.Api/Endpoints/ManagementEndpoints.cs new file mode 100644 index 0000000..e7db424 --- /dev/null +++ b/server/src/Halo.Api/Endpoints/ManagementEndpoints.cs @@ -0,0 +1,94 @@ +using Halo.Api.Auth; +using Halo.Core.Libraries; +using Halo.Core.Users; +using Halo.Data; +using Microsoft.EntityFrameworkCore; + +namespace Halo.Api.Endpoints; + +public static class ManagementEndpoints +{ + public static void MapManagement(this IEndpointRouteBuilder app) + { + var benutzer = app.MapGroup("/api/v1/users").RequireAuthorization(HaloPolicies.Administrator); + + benutzer.MapGet("/", async (HaloContext db) => + Results.Ok(await db.Users + .OrderBy(u => u.UserName) + .Select(u => new AuthenticatedUser(u.Id, u.UserName, u.IsAdministrator)) + .ToListAsync())); + + benutzer.MapPost("/", async (CreateUserRequest anfrage, HaloContext db) => + { + var name = anfrage.UserName.Trim(); + if (name.Length == 0 || anfrage.Password.Length < 8) + return Results.ValidationProblem(new Dictionary + { + ["password"] = ["Benutzername darf nicht leer sein, das Passwort braucht mindestens 8 Zeichen."], + }); + + if (await db.Users.AnyAsync(u => u.UserName == name)) + return Results.Problem($"„{name}“ gibt es schon.", statusCode: StatusCodes.Status409Conflict); + + var neu = new User + { + UserName = name, + PasswordHash = PasswordHasher.Hash(anfrage.Password), + IsAdministrator = anfrage.IsAdministrator, + }; + db.Users.Add(neu); + await db.SaveChangesAsync(); + return Results.Created($"/api/v1/users/{neu.Id}", + new AuthenticatedUser(neu.Id, neu.UserName, neu.IsAdministrator)); + }); + + var bibliotheken = app.MapGroup("/api/v1/libraries"); + + // Lesen darf jeder Angemeldete — ohne die Liste zeigt die App nichts an. + bibliotheken.MapGet("/", async (HaloContext db) => + Results.Ok(await db.Libraries + .OrderBy(l => l.Name) + .Select(l => new LibraryResponse(l.Id, l.Name, l.Kind.ToString(), l.Path)) + .ToListAsync())) + .RequireAuthorization(); + + bibliotheken.MapPost("/", async (CreateLibraryRequest anfrage, HaloContext db) => + { + if (!Enum.TryParse(anfrage.Kind, ignoreCase: true, out var art)) + return Results.ValidationProblem(new Dictionary + { + ["kind"] = [$"Unbekannte Art „{anfrage.Kind}“. Möglich: Movies, Shows."], + }); + + // **Jetzt prüfen, nicht beim ersten Scan.** Ein Tippfehler im Pfad + // führte sonst zu einer Bibliothek, die dauerhaft leer bleibt, und + // die Ursache stünde allenfalls im Protokoll. + if (!Directory.Exists(anfrage.Path)) + return Results.ValidationProblem(new Dictionary + { + ["path"] = [$"„{anfrage.Path}“ gibt es im Container nicht. " + + "Ist das Verzeichnis eingehängt? Gemeint ist der Pfad im Container, nicht der auf dem Wirt."], + }); + + var neu = new Library { Name = anfrage.Name.Trim(), Kind = art, Path = anfrage.Path }; + db.Libraries.Add(neu); + await db.SaveChangesAsync(); + return Results.Created($"/api/v1/libraries/{neu.Id}", + new LibraryResponse(neu.Id, neu.Name, neu.Kind.ToString(), neu.Path)); + }).RequireAuthorization(HaloPolicies.Administrator); + } +} + +public static class HaloPolicies +{ + public const string Administrator = "administrator-only"; +} + +public static class HaloRateLimits +{ + /// Für alles, was ein Geheimnis prüft. + public const string SignIn = "sign-in"; + + /// Für das Nachfragen des Fernsehers — darf häufig sein. + public const string Polling = "polling"; +} diff --git a/server/src/Halo.Api/Endpoints/SystemEndpoints.cs b/server/src/Halo.Api/Endpoints/SystemEndpoints.cs new file mode 100644 index 0000000..9ebdb36 --- /dev/null +++ b/server/src/Halo.Api/Endpoints/SystemEndpoints.cs @@ -0,0 +1,61 @@ +using Halo.Core.Users; +using Halo.Data; +using Microsoft.EntityFrameworkCore; + +namespace Halo.Api.Endpoints; + +public static class SystemEndpoints +{ + /// Verhindert, dass zwei gleichzeitige Anfragen zwei Administratoren anlegen. + /// + /// + /// Ein Prozess, ein Container — ein Semaphor reicht. Ohne ihn liegt + /// zwischen „kein Benutzer vorhanden" und dem Anlegen ein Fenster, und + /// genau in dieses Fenster passt eine zweite Anfrage. + /// + private static readonly SemaphoreSlim EinrichtungsSchloss = new(1, 1); + + public static void MapSystem(this IEndpointRouteBuilder app) + { + app.MapGet("/api/v1/system/info", async (HaloContext db) => + Results.Ok(new SystemInfo( + Version: typeof(SystemEndpoints).Assembly.GetName().Version?.ToString(3) ?? "0.0.0", + NeedsSetup: !await db.Users.AnyAsync()))) + .AllowAnonymous(); + + app.MapPost("/api/v1/system/setup", async (SetupRequest anfrage, HaloContext db) => + { + if (string.IsNullOrWhiteSpace(anfrage.UserName) || anfrage.Password.Length < 8) + return Results.ValidationProblem(new Dictionary + { + ["password"] = ["Benutzername darf nicht leer sein, das Passwort braucht mindestens 8 Zeichen."], + }); + + await EinrichtungsSchloss.WaitAsync(); + try + { + // Noch einmal prüfen, innerhalb des Schlosses. Draussen wäre die + // Antwort schon veraltet, wenn sie ankommt. + if (await db.Users.AnyAsync()) + return Results.Problem( + "Dieser Server ist bereits eingerichtet.", statusCode: StatusCodes.Status409Conflict); + + var administrator = new User + { + UserName = anfrage.UserName.Trim(), + PasswordHash = PasswordHasher.Hash(anfrage.Password), + IsAdministrator = true, + }; + db.Users.Add(administrator); + await db.SaveChangesAsync(); + + return Results.Ok(new AuthenticatedUser(administrator.Id, administrator.UserName, true)); + } + finally { EinrichtungsSchloss.Release(); } + }).AllowAnonymous(); + + // Ohne Anmeldung, damit Docker und Reverse Proxies danach fragen können. + // Verrät nichts ausser der Tatsache, dass etwas antwortet. + app.MapGet("/health", () => Results.Ok(new { status = "ok" })).AllowAnonymous(); + } +} diff --git a/server/src/Halo.Api/Halo.Api.csproj b/server/src/Halo.Api/Halo.Api.csproj new file mode 100644 index 0000000..9d046d3 --- /dev/null +++ b/server/src/Halo.Api/Halo.Api.csproj @@ -0,0 +1,21 @@ + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + net10.0 + enable + enable + + + diff --git a/server/src/Halo.Api/HaloPaths.cs b/server/src/Halo.Api/HaloPaths.cs new file mode 100644 index 0000000..33810a2 --- /dev/null +++ b/server/src/Halo.Api/HaloPaths.cs @@ -0,0 +1,110 @@ +namespace Halo.Api; + +/// Wo der Server seine Sachen ablegt. +/// +/// +/// +/// Alles aus der Umgebung, nichts im Code. Dies ist kein Server für +/// einen Haushalt: wer ihn startet, hat ein anderes NAS, andere Platten und +/// andere Gewohnheiten. Ein fester Pfad hier wäre eine Annahme über ein +/// fremdes System. +/// +/// +/// Die Voreinstellungen sind die für Entwicklung auf einem Arbeitsrechner — +/// ein Unterverzeichnis neben dem Programm. Im Container setzt das Dockerfile +/// /config, /cache und /transcode; das sind die Pfade, +/// die in der Compose-Datei eingehängt werden. +/// +/// +/// Medienpfade stehen hier nicht. Sie werden in der Oberfläche als +/// Bibliotheken angelegt und liegen in der Datenbank — sonst müsste der +/// Container neu starten, um eine Bibliothek hinzuzufügen. +/// +/// +public sealed class HaloPaths +{ + public required string Data { get; init; } + public required string Cache { get; init; } + public required string Transcode { get; init; } + + public string DatabaseFile => Path.Combine(Data, "halo.db"); + + public static HaloPaths FromEnvironment(string contentRoot) + { + string lies(string name, string voreinstellung) => + Environment.GetEnvironmentVariable(name) is { Length: > 0 } wert + ? wert + : Path.Combine(contentRoot, voreinstellung); + + return new HaloPaths + { + Data = lies("HALO_DATA", "data"), + Cache = lies("HALO_CACHE", "cache"), + Transcode = lies("HALO_TRANSCODE", "transcode"), + }; + } + + /// Legt an, was fehlt — und prüft, ob sich dort wirklich schreiben lässt. + /// + /// + /// + /// Anlegen allein genügt nicht. Ein vorhandenes Verzeichnis, in das + /// der Benutzer nicht schreiben darf, lässt CreateDirectory ohne + /// Murren durchgehen — und der Server stirbt zehn Zeilen später an + /// „unable to open database file". Diese Meldung sagt niemandem, dass es + /// um Dateirechte geht, geschweige denn um welches Verzeichnis. + /// + /// + /// Es ist der häufigste Stolperstein beim ersten Start eines Containers, + /// und deshalb wird hier tatsächlich eine Datei angelegt und wieder + /// gelöscht, statt es anzunehmen. + /// + /// + public void EnsureExists() + { + foreach (var (name, pfad) in new[] { ("HALO_DATA", Data), ("HALO_CACHE", Cache), ("HALO_TRANSCODE", Transcode) }) + { + try + { + Directory.CreateDirectory(pfad); + + var probe = Path.Combine(pfad, $".halo-schreibprobe-{Environment.ProcessId}"); + File.WriteAllBytes(probe, []); + File.Delete(probe); + } + catch (Exception fehler) + { + throw new InvalidOperationException( + $""" + {name} zeigt auf „{pfad}“, und dort lässt sich nicht schreiben. + + Halo läuft als Benutzer {Kennung()}. Dieses Verzeichnis muss + ihm gehören oder für ihn beschreibbar sein. + + Im Container ist das fast immer die Einhängung: entweder gehört + das Verzeichnis auf dem Wirt jemand anderem — dann hilft + `chown -R : ` —, oder in der + Compose-Datei steht ein `user:`, der nicht dazu passt. + + Ursprüngliche Meldung: {fehler.Message} + """, fehler); + } + } + } + + /// Unter welcher Kennung der Prozess läuft — die eine Angabe, die beim Suchen hilft. + private static string Kennung() + { + if (OperatingSystem.IsWindows()) return Environment.UserName; + return $"uid={LibC.getuid()}, gid={LibC.getgid()}"; + } + + private static partial class LibC + { + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "getuid")] + public static extern uint getuid(); + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "getgid")] + public static extern uint getgid(); + } +} diff --git a/server/src/Halo.Api/Program.cs b/server/src/Halo.Api/Program.cs new file mode 100644 index 0000000..1b005c8 --- /dev/null +++ b/server/src/Halo.Api/Program.cs @@ -0,0 +1,84 @@ +using System.Threading.RateLimiting; +using Halo.Api; +using Halo.Api.Auth; +using Halo.Api.Endpoints; +using Halo.Data; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; + +var builder = WebApplication.CreateBuilder(args); + +var pfade = HaloPaths.FromEnvironment(builder.Environment.ContentRootPath); +pfade.EnsureExists(); +builder.Services.AddSingleton(pfade); +builder.Services.AddSingleton(TimeProvider.System); + +builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={pfade.DatabaseFile}")); + +builder.Services + .AddAuthentication(TokenAuthenticationHandler.SchemeName) + .AddScheme( + TokenAuthenticationHandler.SchemeName, _ => { }); + +builder.Services.AddAuthorizationBuilder() + // Jeder Endpunkt verlangt Anmeldung, sofern er sie nicht ausdrücklich + // abbestellt. Andersherum — jeden einzeln absichern — ist der Entwurf, bei + // dem irgendwann einer vergessen wird. + .SetFallbackPolicy(new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder() + .RequireAuthenticatedUser().Build()) + .AddPolicy(HaloPolicies.Administrator, p => p.RequireRole(HaloRoles.Administrator)); + +// Einstellbar, weil die richtige Zahl vom Aufbau abhängt: steht Halo hinter +// einem Reverse Proxy, erscheinen **alle** Benutzer unter derselben Adresse +// und teilen sich einen Eimer. Wer das nicht weiss, hält die eigene App für +// kaputt, während in Wahrheit der Nachbar im selben Haus gerade angemeldet hat. +// +// NOCH OFFEN: `X-Forwarded-For` auswerten, damit die Aufteilung auch hinter +// einem Proxy je Benutzer greift. Blind zu vertrauen wäre falsch — es braucht +// eine Liste vertrauenswürdiger Gegenstellen. +int grenze(string name, int voreinstellung) => + int.TryParse(Environment.GetEnvironmentVariable(name), out var wert) && wert > 0 ? wert : voreinstellung; + +builder.Services.AddRateLimiter(o => +{ + o.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + var beimAnmelden = grenze("HALO_RATELIMIT_SIGNIN", 10); + var beimNachfragen = grenze("HALO_RATELIMIT_POLLING", 120); + + // Je Absender, nicht global: sonst sperrt ein einzelner Angreifer den + // ganzen Haushalt aus, und die Abwehr wäre selbst der Ausfall. + o.AddPolicy(HaloRateLimits.SignIn, anfrage => RateLimitPartition.GetFixedWindowLimiter( + anfrage.Connection.RemoteIpAddress?.ToString() ?? "unbekannt", + _ => new FixedWindowRateLimiterOptions { PermitLimit = beimAnmelden, Window = TimeSpan.FromMinutes(1) })); + + o.AddPolicy(HaloRateLimits.Polling, anfrage => RateLimitPartition.GetFixedWindowLimiter( + anfrage.Connection.RemoteIpAddress?.ToString() ?? "unbekannt", + _ => new FixedWindowRateLimiterOptions { PermitLimit = beimNachfragen, Window = TimeSpan.FromMinutes(1) })); +}); + +builder.Services.AddProblemDetails(); + +var app = builder.Build(); + +// Beim Start wandern, nicht über ein eigenes Kommando: wer den Container +// hochfährt, soll nicht erst eine Migration von Hand anstossen müssen. +using (var bereich = app.Services.CreateScope()) +{ + await bereich.ServiceProvider.GetRequiredService().Database.MigrateAsync(); +} + +app.UseExceptionHandler(); +app.UseStatusCodePages(); +app.UseRateLimiter(); +app.UseAuthentication(); +app.UseAuthorization(); + +app.MapSystem(); +app.MapAuth(); +app.MapManagement(); + +app.Run(); + +/// Damit die Tests den Server hochfahren können. +public partial class Program; diff --git a/server/src/Halo.Api/Properties/launchSettings.json b/server/src/Halo.Api/Properties/launchSettings.json new file mode 100644 index 0000000..bb1b952 --- /dev/null +++ b/server/src/Halo.Api/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7190;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/server/src/Halo.Api/appsettings.Development.json b/server/src/Halo.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/server/src/Halo.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/server/src/Halo.Api/appsettings.json b/server/src/Halo.Api/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/server/src/Halo.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/server/src/Halo.Core/Auth/AuthCode.cs b/server/src/Halo.Core/Auth/AuthCode.cs new file mode 100644 index 0000000..7ca70ed --- /dev/null +++ b/server/src/Halo.Core/Auth/AuthCode.cs @@ -0,0 +1,58 @@ +using System.Security.Cryptography; + +namespace Halo.Core.Auth; + +/// Eine laufende Anmeldung per Code — für den Fernseher. +/// +/// +/// +/// Ein Passwort auf der Apple-TV-Fernbedienung einzutippen ist eine Zumutung, +/// die man selbst jedes Mal spürt. Stattdessen: sechsstelliger Code auf dem +/// Bildschirm, Bestätigung am Telefon. +/// +/// +/// Der Code allein holt nie ein Token ab. Dafür gibt es den Abholschein, +/// den nur das anfragende Gerät kennt und der hier nur als Fingerabdruck +/// liegt. Ohne ihn könnte jemand sechsstellige Zahlen durchprobieren — eine +/// Million Versuche sind nichts, und am Ende stünde ein fremdes Gerät in der +/// Mediathek. +/// +/// +public sealed class AuthCode +{ + /// Kurz genug zum Vorlesen, lang genug zum Nichterraten. + public const int CodeLength = 6; + + /// So lange, wie jemand braucht, um zum Telefon zu greifen. + public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5); + + public Guid Id { get; init; } = Guid.CreateVersion7(); + public required string Code { get; init; } + public required string HandleFingerprint { get; init; } + public required string DeviceName { get; init; } + public required string DeviceId { get; init; } + public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow; + public required DateTimeOffset ExpiresAt { get; init; } + + /// Wer bestätigt hat — null, solange niemand. + public Guid? ApprovedByUserId { get; set; } + + /// Wann das Token abgeholt wurde. Danach ist der Code verbraucht. + public DateTimeOffset? ConsumedAt { get; set; } + + public bool IsExpired(DateTimeOffset now) => now >= ExpiresAt; + + /// Ob jetzt ein Token herausgegeben werden darf. + public bool CanBeRedeemed(DateTimeOffset now) => + ApprovedByUserId is not null && ConsumedAt is null && !IsExpired(now); + + /// Sechs Ziffern, gleichverteilt gezogen. + /// + /// + /// und nicht : der + /// Code ist ein Zugang. Die obere Grenze ist ausschliesslich, führende + /// Nullen bleiben erhalten. + /// + public static string NewCode() => + RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D" + CodeLength); +} diff --git a/server/src/Halo.Core/Auth/DeviceToken.cs b/server/src/Halo.Core/Auth/DeviceToken.cs new file mode 100644 index 0000000..7a079c4 --- /dev/null +++ b/server/src/Halo.Core/Auth/DeviceToken.cs @@ -0,0 +1,33 @@ +namespace Halo.Core.Auth; + +/// Ein angemeldetes Gerät. +/// +/// +/// Ein Eintrag je Gerät, nicht je Benutzer: so lässt sich ein verlorenes +/// Telefon einzeln aussperren, ohne alle anderen abzumelden. +/// +public sealed class DeviceToken +{ + public Guid Id { get; init; } = Guid.CreateVersion7(); + public required Guid UserId { get; init; } + + /// Siehe — nie das Token selbst. + public required string TokenFingerprint { get; init; } + + /// Wie das Gerät sich nennt, für die Geräteliste. + public required string DeviceName { get; init; } + + /// Die vom Client vergebene Gerätekennung. + /// + /// + /// Damit dieselbe App nach einer erneuten Anmeldung denselben Eintrag + /// ablöst, statt die Liste mit Karteileichen zu füllen. + /// + public required string DeviceId { get; init; } + + public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow; + public DateTimeOffset LastSeenAt { get; set; } = DateTimeOffset.UtcNow; + public DateTimeOffset? RevokedAt { get; set; } + + public bool IsValid(DateTimeOffset now) => RevokedAt is null || RevokedAt > now; +} diff --git a/server/src/Halo.Core/Auth/Secrets.cs b/server/src/Halo.Core/Auth/Secrets.cs new file mode 100644 index 0000000..2142cfb --- /dev/null +++ b/server/src/Halo.Core/Auth/Secrets.cs @@ -0,0 +1,32 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Halo.Core.Auth; + +/// Erzeugt und verfingert Geheimnisse, die Clients vorzeigen. +/// +/// +/// Abgelegt wird nur der Fingerabdruck, nie das Geheimnis. Wer die +/// Datenbank erbeutet, hat damit Hashes und keine Zugänge. Dass das überhaupt +/// erwähnt werden muss: bei Medienservern liegen Token regelmässig im +/// Klartext, und ein einziges Datenbankleck gibt dann jedem alles. +/// +/// SHA-256 ohne Salz und ohne Streckung genügt hier — anders als bei +/// Passwörtern. Diese Geheimnisse sind 256 Bit Zufall; sie zu erraten ist +/// aussichtslos, ganz gleich wie schnell jemand hashen kann. +/// +public static class Secrets +{ + private const int Bytes = 32; + + /// Ein neues Geheimnis, in URL-sicherem Base64. + public static string Create() => + Base64UrlEncode(RandomNumberGenerator.GetBytes(Bytes)); + + /// Der Fingerabdruck, wie er in der Datenbank steht. + public static string Fingerprint(string secret) => + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(secret))); + + private static string Base64UrlEncode(byte[] roh) => + Convert.ToBase64String(roh).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} diff --git a/server/src/Halo.Core/Halo.Core.csproj b/server/src/Halo.Core/Halo.Core.csproj new file mode 100644 index 0000000..640f98d --- /dev/null +++ b/server/src/Halo.Core/Halo.Core.csproj @@ -0,0 +1,13 @@ + + + + net10.0 + enable + enable + + + + + + + diff --git a/server/src/Halo.Core/Libraries/Library.cs b/server/src/Halo.Core/Libraries/Library.cs new file mode 100644 index 0000000..5e26baf --- /dev/null +++ b/server/src/Halo.Core/Libraries/Library.cs @@ -0,0 +1,20 @@ +namespace Halo.Core.Libraries; + +public enum LibraryKind { Movies, Shows } + +/// Ein Verzeichnis mit Medien, wie der Betreiber es eingerichtet hat. +/// +/// +/// In der Datenbank und nicht in der Umgebung. Stünden Medienpfade in +/// der Compose-Datei, müsste der Container neu starten, um eine Bibliothek +/// hinzuzufügen — und ein Fremder, der Halo zum ersten Mal startet, hätte +/// keine Datei, in der schon das Richtige steht. +/// +public sealed class Library +{ + public Guid Id { get; init; } = Guid.CreateVersion7(); + public required string Name { get; set; } + public required LibraryKind Kind { get; set; } + public required string Path { get; set; } + public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow; +} diff --git a/server/src/Halo.Core/Settings.cs b/server/src/Halo.Core/Settings.cs new file mode 100644 index 0000000..8468190 --- /dev/null +++ b/server/src/Halo.Core/Settings.cs @@ -0,0 +1,15 @@ +namespace Halo.Core; + +/// Eine Einstellung des Servers, als Zeile in der Datenbank. +/// +/// +/// Für alles, was der Betreiber in der Oberfläche setzt und was einen +/// Neustart überleben muss — den TMDB-Schlüssel zum Beispiel. Was dagegen +/// den Betrieb des Containers betrifft (Pfade, Port, Zeitzone), kommt aus der +/// Umgebung und steht nicht hier. +/// +public sealed class ServerSetting +{ + public required string Key { get; init; } + public required string Value { get; set; } +} diff --git a/server/src/Halo.Core/Users/PasswordHasher.cs b/server/src/Halo.Core/Users/PasswordHasher.cs new file mode 100644 index 0000000..c98eac8 --- /dev/null +++ b/server/src/Halo.Core/Users/PasswordHasher.cs @@ -0,0 +1,116 @@ +using System.Security.Cryptography; +using System.Text; +using Konscious.Security.Cryptography; + +namespace Halo.Core.Users; + +/// Passwörter als Argon2id, im PHC-Format abgelegt. +/// +/// +/// +/// Argon2id ist speicherhart: ein Angreifer mit Grafikkarten gewinnt dadurch +/// viel weniger, als er es bei PBKDF2 täte. Die Kennwerte folgen der +/// OWASP-Empfehlung — 19 MiB, zwei Durchgänge, eine Spur. +/// +/// +/// Die Kennwerte stehen im Hash selbst, nicht nur hier als Konstante. +/// Werden sie später angehoben, lassen sich alte Passwörter weiterhin prüfen, +/// statt alle Konten auf einen Schlag auszusperren. Genau daran scheitern +/// solche Umstellungen sonst. +/// +/// +public static class PasswordHasher +{ + private const int MemoryKiB = 19 * 1024; + private const int Iterations = 2; + private const int Parallelism = 1; + private const int SaltBytes = 16; + private const int HashBytes = 32; + + public static string Hash(string password) + { + ArgumentException.ThrowIfNullOrEmpty(password); + + var salt = RandomNumberGenerator.GetBytes(SaltBytes); + var hash = Derive(password, salt, MemoryKiB, Iterations, Parallelism, HashBytes); + + return $"$argon2id$v=19$m={MemoryKiB},t={Iterations},p={Parallelism}$" + + $"{Convert.ToBase64String(salt).TrimEnd('=')}$" + + $"{Convert.ToBase64String(hash).TrimEnd('=')}"; + } + + /// Prüft ein Passwort gegen einen abgelegten Hash. + /// + /// + /// Gibt bei unlesbarem Hash false zurück statt zu werfen: eine + /// beschädigte Zeile in der Datenbank soll die Anmeldung ablehnen, nicht + /// den Server umwerfen. + /// + public static bool Verify(string password, string stored) + { + if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(stored)) return false; + + var teile = stored.Split('$', StringSplitOptions.RemoveEmptyEntries); + if (teile.Length != 5 || teile[0] != "argon2id") return false; + + var kennwerte = teile[2].Split(','); + if (kennwerte.Length != 3) return false; + if (!TryLesen(kennwerte[0], "m=", out var speicher) || + !TryLesen(kennwerte[1], "t=", out var durchgänge) || + !TryLesen(kennwerte[2], "p=", out var spuren)) return false; + + byte[] salt, erwartet; + try + { + salt = Convert.FromBase64String(Auffüllen(teile[3])); + erwartet = Convert.FromBase64String(Auffüllen(teile[4])); + } + catch (FormatException) { return false; } + + if (erwartet.Length == 0) return false; + + var gerechnet = Derive(password, salt, speicher, durchgänge, spuren, erwartet.Length); + return CryptographicOperations.FixedTimeEquals(gerechnet, erwartet); + } + + /// Ob dieser Hash mit schwächeren Kennwerten entstand. + /// + /// + /// Damit lässt sich beim nächsten erfolgreichen Anmelden still neu hashen. + /// Ohne diese Frage bliebe ein Konto von 2026 für immer bei den Kennwerten + /// von 2026, auch wenn die längst zu schwach wären. + /// + public static bool NeedsRehash(string stored) + { + var teile = stored.Split('$', StringSplitOptions.RemoveEmptyEntries); + if (teile.Length != 5 || teile[0] != "argon2id") return true; + + var kennwerte = teile[2].Split(','); + if (kennwerte.Length != 3) return true; + return !TryLesen(kennwerte[0], "m=", out var speicher) || speicher < MemoryKiB + || !TryLesen(kennwerte[1], "t=", out var durchgänge) || durchgänge < Iterations; + } + + private static byte[] Derive(string password, byte[] salt, int speicher, int durchgänge, int spuren, int länge) + { + using var argon = new Argon2id(Encoding.UTF8.GetBytes(password)) + { + Salt = salt, + MemorySize = speicher, + Iterations = durchgänge, + DegreeOfParallelism = spuren, + }; + return argon.GetBytes(länge); + } + + private static bool TryLesen(string stück, string vorsatz, out int wert) + { + wert = 0; + return stück.StartsWith(vorsatz, StringComparison.Ordinal) + && int.TryParse(stück.AsSpan(vorsatz.Length), out wert) + && wert > 0; + } + + /// PHC lässt die Base64-Auffüllung weg; .NET besteht darauf. + private static string Auffüllen(string roh) => roh.PadRight((roh.Length + 3) / 4 * 4, '='); +} diff --git a/server/src/Halo.Core/Users/User.cs b/server/src/Halo.Core/Users/User.cs new file mode 100644 index 0000000..e99a897 --- /dev/null +++ b/server/src/Halo.Core/Users/User.cs @@ -0,0 +1,23 @@ +namespace Halo.Core.Users; + +/// Ein Benutzerkonto. +/// +/// +/// Mehrbenutzer von Anfang an — auch wenn der erste Server nur einen hat. +/// Fortschritt und Gesehen-Status je Benutzer nachträglich einzuziehen wäre +/// ein Umbau am Datenmodell und an jeder Abfrage darauf, kein Zusatz. +/// +public sealed class User +{ + /// Zeitlich geordnet, damit der Index nicht zerfasert. + public Guid Id { get; init; } = Guid.CreateVersion7(); + + public required string UserName { get; set; } + + /// Im PHC-Format, siehe . + public required string PasswordHash { get; set; } + + public bool IsAdministrator { get; set; } + + public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow; +} diff --git a/server/src/Halo.Data/Converters.cs b/server/src/Halo.Data/Converters.cs new file mode 100644 index 0000000..dbda9c5 --- /dev/null +++ b/server/src/Halo.Data/Converters.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Halo.Data; + +/// Zeitpunkte als Unix-Millisekunden statt als Text. +/// +/// +/// +/// Weil SQLite keinen Zeittyp hat. EF Core legt einen +/// DateTimeOffset sonst als Text ab — mitsamt Zeitzonenversatz. Dann +/// steht …T12:00+02:00 neben …T11:00Z, und das ist derselbe +/// Augenblick, sortiert sich als Text aber falsch herum. EF weiss das und +/// weigert sich deshalb, einen Vergleich wie ExpiresAt > jetzt +/// überhaupt zu übersetzen. +/// +/// +/// Millisekunden seit 1970 sind ein absoluter Wert: ihre Ordnung stimmt immer, +/// unabhängig davon, in welcher Zeitzone jemand sitzt. Der Preis ist, dass in +/// der Datenbank Zahlen stehen statt lesbarer Zeiten — für Ablaufprüfungen, +/// die hier zählen, ist das der richtige Tausch. +/// +/// +public sealed class DateTimeOffsetToUnixMilliseconds() : ValueConverter( + zeitpunkt => zeitpunkt.ToUnixTimeMilliseconds(), + zahl => DateTimeOffset.FromUnixTimeMilliseconds(zahl)); + +/// +public sealed class NullableDateTimeOffsetToUnixMilliseconds() : ValueConverter( + zeitpunkt => zeitpunkt == null ? null : zeitpunkt.Value.ToUnixTimeMilliseconds(), + zahl => zahl == null ? null : DateTimeOffset.FromUnixTimeMilliseconds(zahl.Value)); diff --git a/server/src/Halo.Data/Halo.Data.csproj b/server/src/Halo.Data/Halo.Data.csproj new file mode 100644 index 0000000..e8abc84 --- /dev/null +++ b/server/src/Halo.Data/Halo.Data.csproj @@ -0,0 +1,21 @@ + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + net10.0 + enable + enable + + + diff --git a/server/src/Halo.Data/HaloContext.cs b/server/src/Halo.Data/HaloContext.cs new file mode 100644 index 0000000..382042c --- /dev/null +++ b/server/src/Halo.Data/HaloContext.cs @@ -0,0 +1,94 @@ +using Halo.Core; +using Halo.Core.Auth; +using Halo.Core.Libraries; +using Halo.Core.Users; +using Microsoft.EntityFrameworkCore; + +namespace Halo.Data; + +/// Die Datenbank des Servers. +/// +/// +/// SQLite, eine Datei neben der Konfiguration. Kein zweiter Container, +/// kein Passwort, Sicherung ist Kopieren — bei selbstgehosteter Software ist +/// jede zusätzliche Einrichtungshürde eine messbare Abbruchquote. +/// +/// Der Preis steht im Entwurfsdokument: Schreibzugriffe laufen nacheinander. +/// Bei einem Haushalt ist das belanglos, bei 40 000 Titeln und laufendem Scan +/// nicht — dann ist der Umstieg auf PostgreSQL fällig, und deshalb steht hier +/// nirgends SQLite-eigenes SQL. +/// +public sealed class HaloContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Users => Set(); + public DbSet DeviceTokens => Set(); + public DbSet AuthCodes => Set(); + public DbSet Libraries => Set(); + public DbSet Settings => Set(); + + /// Gilt für jede Zeitangabe im Modell, ohne sie einzeln zu nennen. + /// + /// + /// Hier und nicht je Eigenschaft: eine vergessene Eigenschaft wäre eine, + /// deren Vergleich zur Laufzeit scheitert — und zwar erst dann, wenn sie + /// zum ersten Mal in einer Abfrage auftaucht. + /// + protected override void ConfigureConventions(ModelConfigurationBuilder builder) + { + builder.Properties().HaveConversion(); + builder.Properties().HaveConversion(); + } + + protected override void OnModelCreating(ModelBuilder b) + { + b.Entity(e => + { + e.HasKey(x => x.Id); + // Zwei Konten „Guido" und „guido" wären eine Falle, keine Funktion. + e.HasIndex(x => x.UserName).IsUnique(); + e.Property(x => x.UserName).HasMaxLength(64).UseCollation("NOCASE"); + e.Property(x => x.PasswordHash).HasMaxLength(256); + }); + + b.Entity(e => + { + e.HasKey(x => x.Id); + // Der Weg, den jede einzelne Anfrage geht — ohne Index wäre er ein + // vollständiger Tabellendurchlauf je Aufruf. + e.HasIndex(x => x.TokenFingerprint).IsUnique(); + e.HasIndex(x => x.UserId); + e.Property(x => x.TokenFingerprint).HasMaxLength(64); + e.Property(x => x.DeviceName).HasMaxLength(128); + e.Property(x => x.DeviceId).HasMaxLength(128); + e.HasOne().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade); + }); + + b.Entity(e => + { + e.HasKey(x => x.Id); + e.HasIndex(x => x.Code); + e.HasIndex(x => x.HandleFingerprint).IsUnique(); + e.Property(x => x.Code).HasMaxLength(16); + e.Property(x => x.HandleFingerprint).HasMaxLength(64); + e.Property(x => x.DeviceName).HasMaxLength(128); + e.Property(x => x.DeviceId).HasMaxLength(128); + }); + + b.Entity(e => + { + e.HasKey(x => x.Id); + e.Property(x => x.Name).HasMaxLength(128); + e.Property(x => x.Path).HasMaxLength(1024); + // Als Text und nicht als Zahl: wer in die Datenbank sieht, soll + // „Movies" lesen und nicht „0" deuten müssen. + e.Property(x => x.Kind).HasConversion().HasMaxLength(32); + }); + + b.Entity(e => + { + e.HasKey(x => x.Key); + e.Property(x => x.Key).HasMaxLength(128); + e.Property(x => x.Value).HasMaxLength(4096); + }); + } +} diff --git a/server/src/Halo.Data/Migrations/20261003095500_Initial.Designer.cs b/server/src/Halo.Data/Migrations/20261003095500_Initial.Designer.cs new file mode 100644 index 0000000..c5e3f98 --- /dev/null +++ b/server/src/Halo.Data/Migrations/20261003095500_Initial.Designer.cs @@ -0,0 +1,201 @@ +// +using System; +using Halo.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Halo.Data.Migrations +{ + [DbContext(typeof(HaloContext))] + [Migration("20261003095500_Initial")] + partial class Initial + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.12"); + + modelBuilder.Entity("Halo.Core.Auth.AuthCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ApprovedByUserId") + .HasColumnType("TEXT"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ConsumedAt") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("DeviceName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("HandleFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code"); + + b.HasIndex("HandleFingerprint") + .IsUnique(); + + b.ToTable("AuthCodes"); + }); + + modelBuilder.Entity("Halo.Core.Auth.DeviceToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("DeviceName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("LastSeenAt") + .HasColumnType("INTEGER"); + + b.Property("RevokedAt") + .HasColumnType("INTEGER"); + + b.Property("TokenFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenFingerprint") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("DeviceTokens"); + }); + + modelBuilder.Entity("Halo.Core.Libraries.Library", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Libraries"); + }); + + modelBuilder.Entity("Halo.Core.ServerSetting", b => + { + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4096) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("Settings"); + }); + + modelBuilder.Entity("Halo.Core.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .UseCollation("NOCASE"); + + b.HasKey("Id"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Halo.Core.Auth.DeviceToken", b => + { + b.HasOne("Halo.Core.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/server/src/Halo.Data/Migrations/20261003095500_Initial.cs b/server/src/Halo.Data/Migrations/20261003095500_Initial.cs new file mode 100644 index 0000000..ec712be --- /dev/null +++ b/server/src/Halo.Data/Migrations/20261003095500_Initial.cs @@ -0,0 +1,147 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Halo.Data.Migrations +{ + /// + public partial class Initial : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuthCodes", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Code = table.Column(type: "TEXT", maxLength: 16, nullable: false), + HandleFingerprint = table.Column(type: "TEXT", maxLength: 64, nullable: false), + DeviceName = table.Column(type: "TEXT", maxLength: 128, nullable: false), + DeviceId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + ExpiresAt = table.Column(type: "INTEGER", nullable: false), + ApprovedByUserId = table.Column(type: "TEXT", nullable: true), + ConsumedAt = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AuthCodes", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Libraries", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Kind = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Path = table.Column(type: "TEXT", maxLength: 1024, nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Libraries", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Settings", + columns: table => new + { + Key = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Value = table.Column(type: "TEXT", maxLength: 4096, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Settings", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserName = table.Column(type: "TEXT", maxLength: 64, nullable: false, collation: "NOCASE"), + PasswordHash = table.Column(type: "TEXT", maxLength: 256, nullable: false), + IsAdministrator = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceTokens", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + TokenFingerprint = table.Column(type: "TEXT", maxLength: 64, nullable: false), + DeviceName = table.Column(type: "TEXT", maxLength: 128, nullable: false), + DeviceId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + LastSeenAt = table.Column(type: "INTEGER", nullable: false), + RevokedAt = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceTokens", x => x.Id); + table.ForeignKey( + name: "FK_DeviceTokens_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AuthCodes_Code", + table: "AuthCodes", + column: "Code"); + + migrationBuilder.CreateIndex( + name: "IX_AuthCodes_HandleFingerprint", + table: "AuthCodes", + column: "HandleFingerprint", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_DeviceTokens_TokenFingerprint", + table: "DeviceTokens", + column: "TokenFingerprint", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_DeviceTokens_UserId", + table: "DeviceTokens", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Users_UserName", + table: "Users", + column: "UserName", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuthCodes"); + + migrationBuilder.DropTable( + name: "DeviceTokens"); + + migrationBuilder.DropTable( + name: "Libraries"); + + migrationBuilder.DropTable( + name: "Settings"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/server/src/Halo.Data/Migrations/HaloContextModelSnapshot.cs b/server/src/Halo.Data/Migrations/HaloContextModelSnapshot.cs new file mode 100644 index 0000000..9ac5ddc --- /dev/null +++ b/server/src/Halo.Data/Migrations/HaloContextModelSnapshot.cs @@ -0,0 +1,198 @@ +// +using System; +using Halo.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Halo.Data.Migrations +{ + [DbContext(typeof(HaloContext))] + partial class HaloContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.12"); + + modelBuilder.Entity("Halo.Core.Auth.AuthCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ApprovedByUserId") + .HasColumnType("TEXT"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ConsumedAt") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("DeviceName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("HandleFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code"); + + b.HasIndex("HandleFingerprint") + .IsUnique(); + + b.ToTable("AuthCodes"); + }); + + modelBuilder.Entity("Halo.Core.Auth.DeviceToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("DeviceName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("LastSeenAt") + .HasColumnType("INTEGER"); + + b.Property("RevokedAt") + .HasColumnType("INTEGER"); + + b.Property("TokenFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenFingerprint") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("DeviceTokens"); + }); + + modelBuilder.Entity("Halo.Core.Libraries.Library", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Libraries"); + }); + + modelBuilder.Entity("Halo.Core.ServerSetting", b => + { + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4096) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("Settings"); + }); + + modelBuilder.Entity("Halo.Core.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .UseCollation("NOCASE"); + + b.HasKey("Id"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Halo.Core.Auth.DeviceToken", b => + { + b.HasOne("Halo.Core.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/server/tests/Halo.Api.Tests/CodeSignInTests.cs b/server/tests/Halo.Api.Tests/CodeSignInTests.cs new file mode 100644 index 0000000..97fb1b4 --- /dev/null +++ b/server/tests/Halo.Api.Tests/CodeSignInTests.cs @@ -0,0 +1,137 @@ +using System.Net; +using System.Net.Http.Json; +using Halo.Api.Endpoints; + +namespace Halo.Api.Tests; + +/// Anmelden am Fernseher, ohne ein Passwort zu tippen. +public class CodeSignInTests +{ + private static Task CodeAnfordern(HaloServer server) => + server.Client.PostAsJsonAsync("/api/v1/auth/code", new CodeRequest("Wohnzimmer", "tv-1")); + + [Test] + public async Task Der_ganze_Weg_vom_Bildschirm_zum_Token() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + + // 1. Der Fernseher fordert an und zeigt den Code. + var angefordert = await (await CodeAnfordern(server)).Content.ReadFromJsonAsync(); + Assert.That(angefordert!.Code, Does.Match("^[0-9]{6}$")); + + // 2. Noch hat niemand bestätigt. + var wartend = await server.Client.GetFromJsonAsync($"/api/v1/auth/code/{angefordert.Handle}"); + Assert.That(wartend!.State, Is.EqualTo("pending")); + Assert.That(wartend.Login, Is.Null); + + // 3. Am Telefon bestätigen. + var bestätigt = await server.AlsAngemeldeter(telefon.Token) + .PostAsync($"/api/v1/auth/code/{angefordert.Code}", null); + bestätigt.EnsureSuccessStatusCode(); + + // 4. Der Fernseher holt sein Token ab. + var fertig = await server.Client.GetFromJsonAsync($"/api/v1/auth/code/{angefordert.Handle}"); + Assert.That(fertig!.State, Is.EqualTo("approved")); + Assert.That(fertig.Login!.Token, Is.Not.Empty); + + // Und es gilt auch wirklich. + var ich = await server.AlsAngemeldeter(fertig.Login.Token) + .GetFromJsonAsync("/api/v1/auth/me"); + Assert.That(ich!.UserName, Is.EqualTo("guido")); + } + + /// Der Code allein darf niemals ein Token herausgeben. + /// + /// + /// Die wichtigste Prüfung dieser Datei. Gäbe der Server auf einen + /// erratenen Abholschein hin Token heraus, wären sechsstellige Codes ein + /// Türschloss mit einer Million Schlüsseln — in Minuten durchprobiert, und + /// am Ende stünde ein fremdes Gerät in der Mediathek. + /// + [Test] + public async Task Ein_fremder_Abholschein_bekommt_nichts() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + + var echt = await (await CodeAnfordern(server)).Content.ReadFromJsonAsync(); + await server.AlsAngemeldeter(telefon.Token).PostAsync($"/api/v1/auth/code/{echt!.Code}", null); + + // Der Code ist bestätigt — aber der Abholschein stimmt nicht. + var erraten = await server.Client.GetFromJsonAsync("/api/v1/auth/code/ausgedacht"); + + Assert.That(erraten!.State, Is.EqualTo("expired")); + Assert.That(erraten.Login, Is.Null); + } + + /// Auch der Code selbst taugt nicht als Abholschein. + [Test] + public async Task Der_Code_ist_kein_Abholschein() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + + var echt = await (await CodeAnfordern(server)).Content.ReadFromJsonAsync(); + await server.AlsAngemeldeter(telefon.Token).PostAsync($"/api/v1/auth/code/{echt!.Code}", null); + + var mitCode = await server.Client.GetFromJsonAsync($"/api/v1/auth/code/{echt.Code}"); + Assert.That(mitCode!.Login, Is.Null); + } + + [Test] + public async Task Ein_abgeholtes_Token_gibt_es_kein_zweites_Mal() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + + var angefordert = await (await CodeAnfordern(server)).Content.ReadFromJsonAsync(); + await server.AlsAngemeldeter(telefon.Token).PostAsync($"/api/v1/auth/code/{angefordert!.Code}", null); + + var erstesMal = await server.Client.GetFromJsonAsync($"/api/v1/auth/code/{angefordert.Handle}"); + var zweitesMal = await server.Client.GetFromJsonAsync($"/api/v1/auth/code/{angefordert.Handle}"); + + Assert.That(erstesMal!.State, Is.EqualTo("approved")); + Assert.That(zweitesMal!.State, Is.EqualTo("expired")); + Assert.That(zweitesMal.Login, Is.Null); + } + + /// Bestätigen darf nur, wer angemeldet ist. + [Test] + public async Task Ein_Unangemeldeter_kann_nichts_bestaetigen() + { + using var server = new HaloServer(); + await server.SetUpAndSignIn(); + var angefordert = await (await CodeAnfordern(server)).Content.ReadFromJsonAsync(); + + var versuch = await server.Client.PostAsync($"/api/v1/auth/code/{angefordert!.Code}", null); + Assert.That(versuch.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + + var danach = await server.Client.GetFromJsonAsync($"/api/v1/auth/code/{angefordert.Handle}"); + Assert.That(danach!.State, Is.EqualTo("pending")); + } + + [Test] + public async Task Ein_erfundener_Code_laesst_sich_nicht_bestaetigen() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + + var versuch = await server.AlsAngemeldeter(telefon.Token).PostAsync("/api/v1/auth/code/000000", null); + Assert.That(versuch.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); + } + + /// Am Telefon soll stehen, was man da hereinlässt. + [Test] + public async Task Die_Bestaetigung_nennt_das_Geraet() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + var angefordert = await (await CodeAnfordern(server)).Content.ReadFromJsonAsync(); + + var antwort = await server.AlsAngemeldeter(telefon.Token) + .PostAsync($"/api/v1/auth/code/{angefordert!.Code}", null); + + Assert.That(await antwort.Content.ReadAsStringAsync(), Does.Contain("Wohnzimmer")); + } +} diff --git a/server/tests/Halo.Api.Tests/Halo.Api.Tests.csproj b/server/tests/Halo.Api.Tests/Halo.Api.Tests.csproj new file mode 100644 index 0000000..691dc86 --- /dev/null +++ b/server/tests/Halo.Api.Tests/Halo.Api.Tests.csproj @@ -0,0 +1,30 @@ + + + + net10.0 + latest + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/tests/Halo.Api.Tests/HaloPathsTests.cs b/server/tests/Halo.Api.Tests/HaloPathsTests.cs new file mode 100644 index 0000000..d543127 --- /dev/null +++ b/server/tests/Halo.Api.Tests/HaloPathsTests.cs @@ -0,0 +1,96 @@ +namespace Halo.Api.Tests; + +/// Was beim allerersten Start passiert, bevor irgendetwas anderes greift. +public class HaloPathsTests +{ + private string _wurzel = ""; + + [SetUp] + public void Anlegen() => + _wurzel = Directory.CreateDirectory( + Path.Combine(Path.GetTempPath(), "halo-pfade-" + Guid.CreateVersion7().ToString("N"))).FullName; + + [TearDown] + public void Aufraeumen() + { + // Zurücksetzen, sonst lässt sich das gesperrte Verzeichnis nicht löschen. + foreach (var d in Directory.EnumerateDirectories(_wurzel, "*", SearchOption.AllDirectories)) + File.SetUnixFileMode(d, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + try { Directory.Delete(_wurzel, recursive: true); } catch (IOException) { } + } + + private HaloPaths Pfade(string? daten = null) => new() + { + Data = daten ?? Path.Combine(_wurzel, "config"), + Cache = Path.Combine(_wurzel, "cache"), + Transcode = Path.Combine(_wurzel, "transcode"), + }; + + [Test] + public void Fehlende_Verzeichnisse_werden_angelegt() + { + var pfade = Pfade(); + pfade.EnsureExists(); + + Assert.That(Directory.Exists(pfade.Data), Is.True); + Assert.That(Directory.Exists(pfade.Cache), Is.True); + Assert.That(Directory.Exists(pfade.Transcode), Is.True); + } + + [Test] + public void Ein_zweiter_Start_stoert_sich_nicht_am_ersten() + { + var pfade = Pfade(); + pfade.EnsureExists(); + Assert.DoesNotThrow(() => pfade.EnsureExists()); + } + + /// Der häufigste Stolperstein beim ersten Containerstart. + /// + /// + /// Hier wird die Diagnose geprüft, nicht die Funktion. Ein + /// vorhandenes, aber gesperrtes Verzeichnis lässt + /// Directory.CreateDirectory durchgehen; ohne eigene Schreibprobe + /// stirbt der Server erst später an „unable to open database file" — einer + /// Meldung, die weder das Verzeichnis nennt noch verrät, dass es um + /// Dateirechte geht. + /// + [Test] + public void Ein_gesperrtes_Verzeichnis_faellt_beim_Start_auf_und_nennt_den_Grund() + { + if (OperatingSystem.IsWindows()) Assert.Ignore("Dateirechte verhalten sich dort anders."); + + var gesperrt = Directory.CreateDirectory(Path.Combine(_wurzel, "gesperrt")).FullName; + File.SetUnixFileMode(gesperrt, UnixFileMode.UserRead | UnixFileMode.UserExecute); + + var fehler = Assert.Throws(() => Pfade(daten: gesperrt).EnsureExists()); + + Assert.That(fehler!.Message, Does.Contain("HALO_DATA"), "Welche Einstellung gemeint ist"); + Assert.That(fehler.Message, Does.Contain(gesperrt), "Welches Verzeichnis"); + Assert.That(fehler.Message, Does.Contain("uid="), "Als wer der Server läuft"); + Assert.That(fehler.Message, Does.Contain("chown"), "Was zu tun ist"); + } + + [Test] + public void Ohne_Umgebungsvariablen_liegt_alles_neben_dem_Programm() + { + foreach (var name in new[] { "HALO_DATA", "HALO_CACHE", "HALO_TRANSCODE" }) + Environment.SetEnvironmentVariable(name, null); + + var pfade = HaloPaths.FromEnvironment(_wurzel); + + Assert.That(pfade.Data, Is.EqualTo(Path.Combine(_wurzel, "data"))); + Assert.That(pfade.DatabaseFile, Does.EndWith("halo.db")); + } + + [Test] + public void Die_Umgebung_sticht_die_Voreinstellung() + { + Environment.SetEnvironmentVariable("HALO_DATA", "/woanders"); + try + { + Assert.That(HaloPaths.FromEnvironment(_wurzel).Data, Is.EqualTo("/woanders")); + } + finally { Environment.SetEnvironmentVariable("HALO_DATA", null); } + } +} diff --git a/server/tests/Halo.Api.Tests/HaloServer.cs b/server/tests/Halo.Api.Tests/HaloServer.cs new file mode 100644 index 0000000..defbd17 --- /dev/null +++ b/server/tests/Halo.Api.Tests/HaloServer.cs @@ -0,0 +1,67 @@ +using System.Net.Http.Headers; +using System.Net.Http.Json; +using Halo.Api.Endpoints; +using Microsoft.AspNetCore.Mvc.Testing; + +namespace Halo.Api.Tests; + +/// Ein frisch gestarteter Server mit leerer Datenbank. +/// +/// +/// Eine echte SQLite-Datei, kein Ersatz im Arbeitsspeicher. Damit läuft +/// auch das durch, worauf es beim ersten Start ankommt: Verzeichnisse anlegen, +/// Migration wandern lassen, Einrichtung anbieten. Genau diese Kette sieht ein +/// Fremder als Erstes — und genau sie würde ein Ersatzspeicher überspringen. +/// +public sealed class HaloServer : IDisposable +{ + private readonly WebApplicationFactory _fabrik; + private readonly string _verzeichnis; + + public HttpClient Client { get; } + + public HaloServer() + { + _verzeichnis = Path.Combine(Path.GetTempPath(), "halo-test-" + Guid.CreateVersion7().ToString("N")); + Environment.SetEnvironmentVariable("HALO_DATA", Path.Combine(_verzeichnis, "config")); + Environment.SetEnvironmentVariable("HALO_CACHE", Path.Combine(_verzeichnis, "cache")); + Environment.SetEnvironmentVariable("HALO_TRANSCODE", Path.Combine(_verzeichnis, "transcode")); + // Die Zugriffsgrenze zählt je Adresse, und im Test kommt alles von + // derselben. Ohne das Hochsetzen prüfte man hier die Grenze statt der + // Anmeldung. + Environment.SetEnvironmentVariable("HALO_RATELIMIT_SIGNIN", "10000"); + + _fabrik = new WebApplicationFactory(); + Client = _fabrik.CreateClient(); + } + + /// Richtet ein und meldet den Administrator an. + public async Task SetUpAndSignIn(string name = "guido", string passwort = "ein-langes-passwort") + { + var einrichten = await Client.PostAsJsonAsync("/api/v1/system/setup", new SetupRequest(name, passwort)); + einrichten.EnsureSuccessStatusCode(); + return await SignIn(name, passwort); + } + + public async Task SignIn(string name, string passwort, string gerät = "iPhone", string kennung = "geraet-1") + { + var antwort = await Client.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest(name, passwort, gerät, kennung)); + antwort.EnsureSuccessStatusCode(); + return (await antwort.Content.ReadFromJsonAsync())!; + } + + /// Ein eigener Client, der ein Token vorzeigt. + public HttpClient AlsAngemeldeter(string token) + { + var client = _fabrik.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + return client; + } + + public void Dispose() + { + _fabrik.Dispose(); + try { Directory.Delete(_verzeichnis, recursive: true); } catch (IOException) { /* Aufräumen ist Kür */ } + } +} diff --git a/server/tests/Halo.Api.Tests/ManagementTests.cs b/server/tests/Halo.Api.Tests/ManagementTests.cs new file mode 100644 index 0000000..c1bc600 --- /dev/null +++ b/server/tests/Halo.Api.Tests/ManagementTests.cs @@ -0,0 +1,100 @@ +using System.Net; +using System.Net.Http.Json; +using Halo.Api.Endpoints; + +namespace Halo.Api.Tests; + +public class ManagementTests +{ + [Test] + public async Task Ein_Administrator_legt_Benutzer_an() + { + using var server = new HaloServer(); + var admin = await server.SetUpAndSignIn(); + var client = server.AlsAngemeldeter(admin.Token); + + var angelegt = await client.PostAsJsonAsync("/api/v1/users", + new CreateUserRequest("mitbewohner", "auch-ein-langes-passwort", false)); + Assert.That(angelegt.StatusCode, Is.EqualTo(HttpStatusCode.Created)); + + var alle = await client.GetFromJsonAsync>("/api/v1/users"); + Assert.That(alle!.Select(u => u.UserName), Is.EquivalentTo(new[] { "guido", "mitbewohner" })); + } + + /// Wer kein Administrator ist, verwaltet auch nichts. + [Test] + public async Task Ein_gewoehnlicher_Benutzer_darf_keine_Benutzer_anlegen() + { + using var server = new HaloServer(); + var admin = await server.SetUpAndSignIn(); + await server.AlsAngemeldeter(admin.Token).PostAsJsonAsync("/api/v1/users", + new CreateUserRequest("mitbewohner", "auch-ein-langes-passwort", false)); + + var gast = await server.SignIn("mitbewohner", "auch-ein-langes-passwort", "iPad", "geraet-9"); + var versuch = await server.AlsAngemeldeter(gast.Token).PostAsJsonAsync("/api/v1/users", + new CreateUserRequest("noch-einer", "noch-ein-langes-passwort", true)); + + Assert.That(versuch.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden)); + } + + [Test] + public async Task Derselbe_Benutzername_zweimal_wird_abgelehnt() + { + using var server = new HaloServer(); + var admin = await server.SetUpAndSignIn(); + var client = server.AlsAngemeldeter(admin.Token); + + var nochmal = await client.PostAsJsonAsync("/api/v1/users", + new CreateUserRequest("guido", "wieder-ein-langes-passwort", false)); + + Assert.That(nochmal.StatusCode, Is.EqualTo(HttpStatusCode.Conflict)); + } + + /// Ein Tippfehler im Pfad fällt sofort auf, nicht erst beim Scan. + /// + /// + /// Die häufigste Verwechslung beim Einrichten im Container: der Pfad auf + /// dem Wirt statt der im Container. Ohne diese Prüfung bliebe die + /// Bibliothek dauerhaft leer, und der Grund stünde allenfalls im Protokoll. + /// + [Test] + public async Task Eine_Bibliothek_auf_einem_Pfad_den_es_nicht_gibt_wird_abgelehnt() + { + using var server = new HaloServer(); + var admin = await server.SetUpAndSignIn(); + + var versuch = await server.AlsAngemeldeter(admin.Token).PostAsJsonAsync("/api/v1/libraries", + new CreateLibraryRequest("Filme", "Movies", "/gibt/es/nicht")); + + Assert.That(versuch.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + Assert.That(await versuch.Content.ReadAsStringAsync(), Does.Contain("eingeh")); + } + + [Test] + public async Task Eine_Bibliothek_auf_einem_vorhandenen_Pfad_wird_angelegt() + { + using var server = new HaloServer(); + var admin = await server.SetUpAndSignIn(); + var client = server.AlsAngemeldeter(admin.Token); + var pfad = Path.GetTempPath(); + + var angelegt = await client.PostAsJsonAsync("/api/v1/libraries", + new CreateLibraryRequest("Filme", "movies", pfad)); + Assert.That(angelegt.StatusCode, Is.EqualTo(HttpStatusCode.Created)); + + var alle = await client.GetFromJsonAsync>("/api/v1/libraries"); + Assert.That(alle!.Single().Kind, Is.EqualTo("Movies")); + } + + [Test] + public async Task Eine_unbekannte_Art_wird_abgelehnt() + { + using var server = new HaloServer(); + var admin = await server.SetUpAndSignIn(); + + var versuch = await server.AlsAngemeldeter(admin.Token).PostAsJsonAsync("/api/v1/libraries", + new CreateLibraryRequest("Musik", "Music", Path.GetTempPath())); + + Assert.That(versuch.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + } +} diff --git a/server/tests/Halo.Api.Tests/SetupTests.cs b/server/tests/Halo.Api.Tests/SetupTests.cs new file mode 100644 index 0000000..ba8b961 --- /dev/null +++ b/server/tests/Halo.Api.Tests/SetupTests.cs @@ -0,0 +1,71 @@ +using System.Net; +using System.Net.Http.Json; +using Halo.Api.Endpoints; + +namespace Halo.Api.Tests; + +public class SetupTests +{ + [Test] + public async Task Ein_frischer_Server_verlangt_Einrichtung() + { + using var server = new HaloServer(); + var info = await server.Client.GetFromJsonAsync("/api/v1/system/info"); + Assert.That(info!.NeedsSetup, Is.True); + } + + [Test] + public async Task Die_Einrichtung_legt_einen_Administrator_an() + { + using var server = new HaloServer(); + var antwort = await server.Client.PostAsJsonAsync("/api/v1/system/setup", + new SetupRequest("guido", "ein-langes-passwort")); + + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + var benutzer = await antwort.Content.ReadFromJsonAsync(); + Assert.That(benutzer!.UserName, Is.EqualTo("guido")); + Assert.That(benutzer.IsAdministrator, Is.True); + + var info = await server.Client.GetFromJsonAsync("/api/v1/system/info"); + Assert.That(info!.NeedsSetup, Is.False); + } + + /// Sonst stünde ein laufender Server dem ersten Fremden offen. + /// + /// + /// Der Endpunkt muss ohne Anmeldung erreichbar sein — beim ersten Start + /// gibt es ja noch niemanden, der sich anmelden könnte. Genau deshalb muss + /// er sich danach selbst verschliessen. + /// + [Test] + public async Task Ein_zweites_Mal_Einrichten_wird_abgelehnt() + { + using var server = new HaloServer(); + await server.SetUpAndSignIn(); + + var zweiterVersuch = await server.Client.PostAsJsonAsync("/api/v1/system/setup", + new SetupRequest("eindringling", "auch-ein-langes-passwort")); + + Assert.That(zweiterVersuch.StatusCode, Is.EqualTo(HttpStatusCode.Conflict)); + } + + [Test] + public async Task Ein_zu_kurzes_Passwort_wird_abgelehnt() + { + using var server = new HaloServer(); + var antwort = await server.Client.PostAsJsonAsync("/api/v1/system/setup", + new SetupRequest("guido", "kurz")); + + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + var info = await server.Client.GetFromJsonAsync("/api/v1/system/info"); + Assert.That(info!.NeedsSetup, Is.True, "Ein abgelehnter Versuch darf nichts angelegt haben"); + } + + [Test] + public async Task Die_Gesundheitsfrage_braucht_keine_Anmeldung() + { + using var server = new HaloServer(); + var antwort = await server.Client.GetAsync("/health"); + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + } +} diff --git a/server/tests/Halo.Api.Tests/SignInTests.cs b/server/tests/Halo.Api.Tests/SignInTests.cs new file mode 100644 index 0000000..dc681ea --- /dev/null +++ b/server/tests/Halo.Api.Tests/SignInTests.cs @@ -0,0 +1,137 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using Halo.Api.Endpoints; + +namespace Halo.Api.Tests; + +public class SignInTests +{ + [Test] + public async Task Mit_richtigem_Passwort_gibt_es_ein_Token() + { + using var server = new HaloServer(); + var anmeldung = await server.SetUpAndSignIn(); + + Assert.That(anmeldung.Token, Is.Not.Empty); + Assert.That(anmeldung.User.UserName, Is.EqualTo("guido")); + } + + [Test] + public async Task Mit_falschem_Passwort_gibt_es_keines() + { + using var server = new HaloServer(); + await server.SetUpAndSignIn(); + + var antwort = await server.Client.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest("guido", "falsch-aber-lang", "iPhone", "geraet-1")); + + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + /// Unbekannter Name und falsches Passwort sind nicht zu unterscheiden. + [Test] + public async Task Ein_unbekannter_Name_antwortet_wie_ein_falsches_Passwort() + { + using var server = new HaloServer(); + await server.SetUpAndSignIn(); + + var unbekannt = await server.Client.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest("gibtesnicht", "irgendein-passwort", "iPhone", "geraet-1")); + var falsch = await server.Client.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest("guido", "irgendein-passwort", "iPhone", "geraet-1")); + + Assert.That(unbekannt.StatusCode, Is.EqualTo(falsch.StatusCode)); + + // Nur die Begründung vergleichen, nicht den ganzen Körper: darin steht + // je Anfrage eine neue Ablaufkennung, die nichts über das Konto sagt. + static async Task Begründung(HttpResponseMessage antwort) => + (await antwort.Content.ReadFromJsonAsync())! + .RootElement.GetProperty("detail").GetString(); + + Assert.That(await Begründung(unbekannt), Is.EqualTo(await Begründung(falsch))); + } + + [Test] + public async Task Mit_Token_beantwortet_der_Server_wer_man_ist() + { + using var server = new HaloServer(); + var anmeldung = await server.SetUpAndSignIn(); + + var ich = await server.AlsAngemeldeter(anmeldung.Token) + .GetFromJsonAsync("/api/v1/auth/me"); + + Assert.That(ich!.Id, Is.EqualTo(anmeldung.User.Id)); + Assert.That(ich.IsAdministrator, Is.True); + } + + [Test] + public async Task Ohne_Token_antwortet_er_nicht() + { + using var server = new HaloServer(); + await server.SetUpAndSignIn(); + + var antwort = await server.Client.GetAsync("/api/v1/auth/me"); + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + [Test] + public async Task Ein_erfundenes_Token_gilt_nicht() + { + using var server = new HaloServer(); + await server.SetUpAndSignIn(); + + var antwort = await server.AlsAngemeldeter("ausgedacht-aber-lang-genug").GetAsync("/api/v1/auth/me"); + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + /// Nach dem Abmelden gilt das Token sofort nicht mehr. + /// + /// + /// Der Grund, warum hier keine JWT stehen: ein signiertes Token gälte bis + /// zum Ablauf weiter, und für ein verlorenes Telefon ist das der falsche + /// Satz. + /// + [Test] + public async Task Abmelden_entwertet_das_Token_augenblicklich() + { + using var server = new HaloServer(); + var anmeldung = await server.SetUpAndSignIn(); + var client = server.AlsAngemeldeter(anmeldung.Token); + + (await client.PostAsync("/api/v1/auth/logout", null)).EnsureSuccessStatusCode(); + + var danach = await client.GetAsync("/api/v1/auth/me"); + Assert.That(danach.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + /// Dasselbe Gerät ersetzt seinen Eintrag, statt einen zweiten anzulegen. + [Test] + public async Task Eine_erneute_Anmeldung_desselben_Geraets_entwertet_das_alte_Token() + { + using var server = new HaloServer(); + var erste = await server.SetUpAndSignIn(); + var zweite = await server.SignIn("guido", "ein-langes-passwort", "iPhone", "geraet-1"); + + Assert.That(zweite.Token, Is.Not.EqualTo(erste.Token)); + var mitAltem = await server.AlsAngemeldeter(erste.Token).GetAsync("/api/v1/auth/me"); + Assert.That(mitAltem.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + var mitNeuem = await server.AlsAngemeldeter(zweite.Token).GetAsync("/api/v1/auth/me"); + Assert.That(mitNeuem.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + } + + /// Ein zweites Gerät meldet das erste nicht ab. + [Test] + public async Task Ein_anderes_Geraet_laesst_das_erste_in_Ruhe() + { + using var server = new HaloServer(); + var telefon = await server.SetUpAndSignIn(); + var fernseher = await server.SignIn("guido", "ein-langes-passwort", "Apple TV", "geraet-2"); + + foreach (var token in new[] { telefon.Token, fernseher.Token }) + { + var antwort = await server.AlsAngemeldeter(token).GetAsync("/api/v1/auth/me"); + Assert.That(antwort.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + } + } +} diff --git a/server/tests/Halo.Core.Tests/AuthCodeTests.cs b/server/tests/Halo.Core.Tests/AuthCodeTests.cs new file mode 100644 index 0000000..1d81805 --- /dev/null +++ b/server/tests/Halo.Core.Tests/AuthCodeTests.cs @@ -0,0 +1,118 @@ +using Halo.Core.Auth; + +namespace Halo.Core.Tests; + +public class SecretsTests +{ + [Test] + public void Zwei_Geheimnisse_sind_nie_gleich() + { + var gesehen = new HashSet(); + for (var i = 0; i < 200; i++) Assert.That(gesehen.Add(Secrets.Create()), Is.True); + } + + [Test] + public void Das_Geheimnis_ist_URL_sicher() + { + for (var i = 0; i < 50; i++) + { + var s = Secrets.Create(); + Assert.That(s, Does.Not.Contain("+").And.Not.Contain("/").And.Not.Contain("=")); + } + } + + [Test] + public void Der_Fingerabdruck_ist_gleichbleibend_und_unterscheidet() + { + var a = Secrets.Create(); + var b = Secrets.Create(); + // Zweimal gerechnet, nicht zweimal derselbe Ausdruck: geprüft wird, + // dass die Funktion bei gleicher Eingabe gleich antwortet. + var ersterLauf = Secrets.Fingerprint(a); + var zweiterLauf = Secrets.Fingerprint(a); + Assert.That(zweiterLauf, Is.EqualTo(ersterLauf)); + Assert.That(Secrets.Fingerprint(b), Is.Not.EqualTo(ersterLauf)); + Assert.That(ersterLauf, Has.Length.EqualTo(64)); + } + + /// Der Fingerabdruck darf das Geheimnis nicht enthalten. + [Test] + public void Der_Fingerabdruck_verraet_das_Geheimnis_nicht() + { + var s = Secrets.Create(); + Assert.That(Secrets.Fingerprint(s), Does.Not.Contain(s)); + } +} + +public class AuthCodeTests +{ + private static readonly DateTimeOffset Jetzt = new(2026, 10, 3, 12, 0, 0, TimeSpan.Zero); + + private static AuthCode Angelegt(DateTimeOffset? läuftAb = null) => new() + { + Code = AuthCode.NewCode(), + HandleFingerprint = Secrets.Fingerprint(Secrets.Create()), + DeviceName = "Wohnzimmer", + DeviceId = "tv-1", + CreatedAt = Jetzt, + ExpiresAt = läuftAb ?? Jetzt + AuthCode.Lifetime, + }; + + [Test] + public void Der_Code_hat_immer_sechs_Ziffern() + { + for (var i = 0; i < 500; i++) + { + var code = AuthCode.NewCode(); + Assert.That(code, Has.Length.EqualTo(6)); + Assert.That(code, Does.Match("^[0-9]{6}$")); + } + } + + /// Führende Nullen dürfen nicht wegfallen — „000123" ist ein gültiger Code. + [Test] + public void Fuehrende_Nullen_bleiben_erhalten() + { + var mitNull = Enumerable.Range(0, 20_000).Select(_ => AuthCode.NewCode()).Any(c => c[0] == '0'); + Assert.That(mitNull, Is.True, "In 20 000 Ziehungen kam kein Code mit führender Null vor"); + } + + [Test] + public void Ohne_Bestaetigung_gibt_es_kein_Token() + { + Assert.That(Angelegt().CanBeRedeemed(Jetzt), Is.False); + } + + [Test] + public void Nach_Bestaetigung_gibt_es_ein_Token() + { + var code = Angelegt(); + code.ApprovedByUserId = Guid.CreateVersion7(); + Assert.That(code.CanBeRedeemed(Jetzt), Is.True); + } + + /// Einmal abgeholt ist abgeholt. + [Test] + public void Ein_verbrauchter_Code_gibt_kein_zweites_Token() + { + var code = Angelegt(); + code.ApprovedByUserId = Guid.CreateVersion7(); + code.ConsumedAt = Jetzt; + Assert.That(code.CanBeRedeemed(Jetzt), Is.False); + } + + [Test] + public void Ein_abgelaufener_Code_gibt_kein_Token_auch_wenn_bestaetigt() + { + var code = Angelegt(läuftAb: Jetzt); + code.ApprovedByUserId = Guid.CreateVersion7(); + Assert.That(code.IsExpired(Jetzt), Is.True); + Assert.That(code.CanBeRedeemed(Jetzt), Is.False); + } + + [Test] + public void Die_Gueltigkeit_ist_kurz() + { + Assert.That(AuthCode.Lifetime, Is.LessThanOrEqualTo(TimeSpan.FromMinutes(10))); + } +} diff --git a/server/tests/Halo.Core.Tests/Halo.Core.Tests.csproj b/server/tests/Halo.Core.Tests/Halo.Core.Tests.csproj new file mode 100644 index 0000000..7aa314b --- /dev/null +++ b/server/tests/Halo.Core.Tests/Halo.Core.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + latest + enable + enable + false + + + + + + + + + + + + + + + + + + + diff --git a/server/tests/Halo.Core.Tests/PasswordHasherTests.cs b/server/tests/Halo.Core.Tests/PasswordHasherTests.cs new file mode 100644 index 0000000..16a6fbe --- /dev/null +++ b/server/tests/Halo.Core.Tests/PasswordHasherTests.cs @@ -0,0 +1,72 @@ +using Halo.Core.Users; + +namespace Halo.Core.Tests; + +public class PasswordHasherTests +{ + [Test] + public void Richtiges_Passwort_wird_angenommen() + { + var hash = PasswordHasher.Hash("geheim-und-lang"); + Assert.That(PasswordHasher.Verify("geheim-und-lang", hash), Is.True); + } + + [Test] + public void Falsches_Passwort_wird_abgelehnt() + { + var hash = PasswordHasher.Hash("geheim-und-lang"); + Assert.That(PasswordHasher.Verify("geheim-und-kurz", hash), Is.False); + } + + /// Gleiches Passwort, zwei Hashes — sonst wäre das Salz wirkungslos. + /// + /// + /// Ohne diese Eigenschaft verrät die Datenbank, welche Konten dasselbe + /// Passwort benutzen, und eine einmal gebaute Tabelle knackt alle auf + /// einen Schlag. + /// + [Test] + public void Zweimal_dasselbe_Passwort_ergibt_zwei_verschiedene_Hashes() + { + var a = PasswordHasher.Hash("dasselbe"); + var b = PasswordHasher.Hash("dasselbe"); + Assert.That(a, Is.Not.EqualTo(b)); + Assert.That(PasswordHasher.Verify("dasselbe", a), Is.True); + Assert.That(PasswordHasher.Verify("dasselbe", b), Is.True); + } + + [Test] + public void Der_Hash_nennt_seine_Kennwerte() + { + var hash = PasswordHasher.Hash("egal"); + Assert.That(hash, Does.StartWith("$argon2id$v=19$m=19456,t=2,p=1$")); + } + + /// Eine beschädigte Zeile lehnt ab, statt den Server umzuwerfen. + [TestCase("")] + [TestCase("kein-hash")] + [TestCase("$argon2id$v=19$m=19456,t=2,p=1$nur-vier-teile")] + [TestCase("$bcrypt$v=19$m=19456,t=2,p=1$c2FsenNhbHo$aGFzaA")] + [TestCase("$argon2id$v=19$m=x,t=2,p=1$c2FsenNhbHo$aGFzaA")] + [TestCase("$argon2id$v=19$m=19456,t=2,p=1$!!!kein-base64!!!$aGFzaA")] + public void Unlesbarer_Hash_wirft_nicht_sondern_lehnt_ab(string kaputt) + { + Assert.That(PasswordHasher.Verify("egal", kaputt), Is.False); + } + + [Test] + public void Leeres_Passwort_wird_abgelehnt_statt_gehasht() + { + Assert.Throws(() => PasswordHasher.Hash("")); + Assert.That(PasswordHasher.Verify("", PasswordHasher.Hash("echt")), Is.False); + } + + /// Alte, schwächere Hashes sollen beim nächsten Anmelden auffallen. + [Test] + public void Schwaechere_Kennwerte_verlangen_ein_Neuhashen() + { + Assert.That(PasswordHasher.NeedsRehash("$argon2id$v=19$m=4096,t=1,p=1$c2FsenNhbHo$aGFzaA"), Is.True); + Assert.That(PasswordHasher.NeedsRehash("$2a$10$irgendwas"), Is.True); + Assert.That(PasswordHasher.NeedsRehash(PasswordHasher.Hash("aktuell")), Is.False); + } +}