From 587146d322a2938ecf49ca62d5e0c3f7cc7d4ef1 Mon Sep 17 00:00:00 2001 From: azures04 Date: Mon, 5 Jan 2026 04:42:39 +0100 Subject: [PATCH] Initial project structure and core files Add base project files including environment example, license, README, .gitignore, error classes, ESLint config, database modules, texture assets, repositories, routes, schemas, services, and server entry point. This establishes the foundational structure for a Yggdrasil-compatible REST API with modular error handling, database setup, and route organization. --- .env.example | 24 + .gitignore | 136 + LICENSE | 235 ++ README.md | 1 + data/textures/alex.png | Bin 0 -> 3420 bytes data/textures/steve.png | Bin 0 -> 1094 bytes errors/DefaultError.js | 24 + errors/ServiceError.js | 43 + errors/SessionError.js | 24 + errors/ValidationError.js | 119 + errors/YggdrasilError.js | 26 + errors/errors.js | 13 + eslint.config.js | 28 + modules/certificatesManager.js | 64 + modules/database.js | 16 + modules/databaseGlobals.js | 390 +++ modules/loader.js | 52 + modules/logger.js | 89 + modules/utils.js | 63 + package-lock.json | 2703 +++++++++++++++++ package.json | 47 + repositories/adminRepository.js | 131 + repositories/authRepository.js | 208 ++ repositories/sessionsRepository.js | 174 ++ repositories/userRepository.js | 774 +++++ routes/admin/ban/index.js | 32 + routes/admin/cosmetics/capes.js | 20 + routes/admin/index.js | 4 + routes/admin/players/password.js | 12 + routes/admin/players/textures.js | 23 + routes/admin/players/username.js | 12 + .../minecraft/profile/lookup/bulk/byname.js | 10 + routes/api/profile/lookup/name/[username].js | 28 + routes/api/profiles/minecraft.js | 10 + routes/api/user/profiles/[uuid]/names.js | 15 + .../users/profiles/minecraft/[username].js | 27 + routes/authserver/authenticate.js | 41 + routes/authserver/invalidate.js | 20 + routes/authserver/refresh.js | 28 + routes/authserver/signout.js | 29 + routes/authserver/validate.js | 20 + routes/index.js | 17 + routes/legacy/MinecraftCloaks/[username].js | 10 + routes/legacy/MinecraftSkins/[username].js | 10 + routes/legacy/checkserver.js | 24 + routes/legacy/cloaks/[username].js | 10 + routes/legacy/joinserver.js | 26 + routes/legacy/login.js | 36 + routes/legacy/skins/[username].js | 10 + .../minecraft/profile/capes/active.js | 26 + .../minecraft/profile/index.js | 18 + .../minecraft/profile/lookup/bulk/byname.js | 10 + .../profile/lookup/name/[username].js | 27 + .../minecraft/profile/name/[name].js | 44 + .../minecraft/profile/namechange.js | 12 + .../minecraft/profile/skins/active.js | 12 + .../minecraft/profile/skins/index.js | 77 + routes/minecraftservices/player/attributes.js | 34 + .../minecraftservices/player/certificates.js | 12 + routes/minecraftservices/privacy/blocklist.js | 39 + routes/minecraftservices/privileges.js | 34 + routes/minecraftservices/productvoucher.js | 14 + routes/minecraftservices/publickeys.js | 18 + routes/register.js | 44 + routes/sessionserver/blockedservers.js | 18 + .../session/minecraft/hasJoined.js | 24 + .../sessionserver/session/minecraft/join.js | 66 + .../session/minecraft/profile/[uuid].js | 29 + routes/textures/texture/[hash].js | 22 + schemas/admin/admin/cosmetics/capes/[hash].js | 9 + schemas/admin/ban/[uuid]/actions.js | 9 + schemas/admin/ban/[uuid]/history.js | 9 + schemas/admin/ban/[uuid]/index.js | 26 + schemas/admin/players/password/[uuid].js | 12 + .../players/textures/cape/[uuid]/[hash].js | 16 + .../minecraft/profile/lookup/bulk/byname.js | 18 + schemas/api/profile/lookup/name/[username].js | 13 + schemas/api/profiles/minecraft.js | 18 + schemas/api/user/profiles/[uuid]/names.js | 18 + .../users/profiles/minecraft/[username].js | 13 + schemas/authserver/authenticate.js | 31 + schemas/authserver/invalidate.js | 23 + schemas/authserver/refresh.js | 23 + schemas/authserver/signout.js | 25 + schemas/authserver/validate.js | 23 + schemas/legacy/joinserver.js | 11 + schemas/legacy/legacy/checkserver.js | 10 + schemas/legacy/login.js | 16 + .../minecraftservices/minecraft/profile.js | 13 + .../minecraft/profile/capes/active.js | 28 + .../minecraft/profile/lookup/bulk/byname.js | 18 + .../profile/lookup/name/[username].js | 13 + .../minecraft/profile/name/[name].js | 22 + .../profile/name/[name]/available.js | 21 + .../minecraft/profile/namechange.js | 13 + .../minecraft/profile/skins.js | 24 + .../minecraft/profile/skins/active.js | 13 + .../minecraftservices/player/attributes.js | 29 + .../minecraftservices/player/certificates.js | 13 + .../minecraftservices/privacy/blocklist.js | 13 + .../privacy/blocklist/[uuid].js | 28 + schemas/minecraftservices/privileges.js | 29 + schemas/register.js | 25 + .../session/minecraft/hasJoined.js | 19 + .../sessionsserver/session/minecraft/join.js | 22 + .../session/minecraft/profile/[uuid].js | 16 + server.js | 167 + services/adminService.js | 145 + services/authService.js | 289 ++ services/serverService.js | 39 + services/sessionsService.js | 212 ++ services/userService.js | 568 ++++ 112 files changed, 8540 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 data/textures/alex.png create mode 100644 data/textures/steve.png create mode 100644 errors/DefaultError.js create mode 100644 errors/ServiceError.js create mode 100644 errors/SessionError.js create mode 100644 errors/ValidationError.js create mode 100644 errors/YggdrasilError.js create mode 100644 errors/errors.js create mode 100644 eslint.config.js create mode 100644 modules/certificatesManager.js create mode 100644 modules/database.js create mode 100644 modules/databaseGlobals.js create mode 100644 modules/loader.js create mode 100644 modules/logger.js create mode 100644 modules/utils.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 repositories/adminRepository.js create mode 100644 repositories/authRepository.js create mode 100644 repositories/sessionsRepository.js create mode 100644 repositories/userRepository.js create mode 100644 routes/admin/ban/index.js create mode 100644 routes/admin/cosmetics/capes.js create mode 100644 routes/admin/index.js create mode 100644 routes/admin/players/password.js create mode 100644 routes/admin/players/textures.js create mode 100644 routes/admin/players/username.js create mode 100644 routes/api/minecraft/profile/lookup/bulk/byname.js create mode 100644 routes/api/profile/lookup/name/[username].js create mode 100644 routes/api/profiles/minecraft.js create mode 100644 routes/api/user/profiles/[uuid]/names.js create mode 100644 routes/api/users/profiles/minecraft/[username].js create mode 100644 routes/authserver/authenticate.js create mode 100644 routes/authserver/invalidate.js create mode 100644 routes/authserver/refresh.js create mode 100644 routes/authserver/signout.js create mode 100644 routes/authserver/validate.js create mode 100644 routes/index.js create mode 100644 routes/legacy/MinecraftCloaks/[username].js create mode 100644 routes/legacy/MinecraftSkins/[username].js create mode 100644 routes/legacy/checkserver.js create mode 100644 routes/legacy/cloaks/[username].js create mode 100644 routes/legacy/joinserver.js create mode 100644 routes/legacy/login.js create mode 100644 routes/legacy/skins/[username].js create mode 100644 routes/minecraftservices/minecraft/profile/capes/active.js create mode 100644 routes/minecraftservices/minecraft/profile/index.js create mode 100644 routes/minecraftservices/minecraft/profile/lookup/bulk/byname.js create mode 100644 routes/minecraftservices/minecraft/profile/lookup/name/[username].js create mode 100644 routes/minecraftservices/minecraft/profile/name/[name].js create mode 100644 routes/minecraftservices/minecraft/profile/namechange.js create mode 100644 routes/minecraftservices/minecraft/profile/skins/active.js create mode 100644 routes/minecraftservices/minecraft/profile/skins/index.js create mode 100644 routes/minecraftservices/player/attributes.js create mode 100644 routes/minecraftservices/player/certificates.js create mode 100644 routes/minecraftservices/privacy/blocklist.js create mode 100644 routes/minecraftservices/privileges.js create mode 100644 routes/minecraftservices/productvoucher.js create mode 100644 routes/minecraftservices/publickeys.js create mode 100644 routes/register.js create mode 100644 routes/sessionserver/blockedservers.js create mode 100644 routes/sessionserver/session/minecraft/hasJoined.js create mode 100644 routes/sessionserver/session/minecraft/join.js create mode 100644 routes/sessionserver/session/minecraft/profile/[uuid].js create mode 100644 routes/textures/texture/[hash].js create mode 100644 schemas/admin/admin/cosmetics/capes/[hash].js create mode 100644 schemas/admin/ban/[uuid]/actions.js create mode 100644 schemas/admin/ban/[uuid]/history.js create mode 100644 schemas/admin/ban/[uuid]/index.js create mode 100644 schemas/admin/players/password/[uuid].js create mode 100644 schemas/admin/players/textures/cape/[uuid]/[hash].js create mode 100644 schemas/api/minecraft/profile/lookup/bulk/byname.js create mode 100644 schemas/api/profile/lookup/name/[username].js create mode 100644 schemas/api/profiles/minecraft.js create mode 100644 schemas/api/user/profiles/[uuid]/names.js create mode 100644 schemas/api/users/profiles/minecraft/[username].js create mode 100644 schemas/authserver/authenticate.js create mode 100644 schemas/authserver/invalidate.js create mode 100644 schemas/authserver/refresh.js create mode 100644 schemas/authserver/signout.js create mode 100644 schemas/authserver/validate.js create mode 100644 schemas/legacy/joinserver.js create mode 100644 schemas/legacy/legacy/checkserver.js create mode 100644 schemas/legacy/login.js create mode 100644 schemas/minecraftservices/minecraft/profile.js create mode 100644 schemas/minecraftservices/minecraft/profile/capes/active.js create mode 100644 schemas/minecraftservices/minecraft/profile/lookup/bulk/byname.js create mode 100644 schemas/minecraftservices/minecraft/profile/lookup/name/[username].js create mode 100644 schemas/minecraftservices/minecraft/profile/name/[name].js create mode 100644 schemas/minecraftservices/minecraft/profile/name/[name]/available.js create mode 100644 schemas/minecraftservices/minecraft/profile/namechange.js create mode 100644 schemas/minecraftservices/minecraft/profile/skins.js create mode 100644 schemas/minecraftservices/minecraft/profile/skins/active.js create mode 100644 schemas/minecraftservices/player/attributes.js create mode 100644 schemas/minecraftservices/player/certificates.js create mode 100644 schemas/minecraftservices/privacy/blocklist.js create mode 100644 schemas/minecraftservices/privacy/blocklist/[uuid].js create mode 100644 schemas/minecraftservices/privileges.js create mode 100644 schemas/register.js create mode 100644 schemas/sessionsserver/session/minecraft/hasJoined.js create mode 100644 schemas/sessionsserver/session/minecraft/join.js create mode 100644 schemas/sessionsserver/session/minecraft/profile/[uuid].js create mode 100644 server.js create mode 100644 services/adminService.js create mode 100644 services/authService.js create mode 100644 services/serverService.js create mode 100644 services/sessionsService.js create mode 100644 services/userService.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..2d1829e --- /dev/null +++ b/.env.example @@ -0,0 +1,24 @@ +#Config +WEB_PORT=3000 +IS_PROD=FALSE + +#MariaDB +DATABASE_HOST="host" +DATABASE_USER="username" +DATABASE_PASSWORD="Password" +DATABASE_NAME="database" + +#Mojang API +SUPPORT_UUID_TO_NAME_HISTORY=TRUE + +#Authlib-Injector +SUPPORT_AUTHLIB_INJECTOR=TRUE +SUPPORT_LEGACY_SKIN_API=TRUE #[legacy_skin_api] +SUPPORT_MOJANG_FALLBACK=FALSE #[no_mojang_namespace] +SUPPORT_MOJANG_TELEMETRY_BLOCKER=TRUE #[enable_mojang_anti_features] +SUPPORT_PROFILE_KEY=TRUE #[enable_profile_key] +SUPPORT_ONLY_DEFAULT_USERNAME=true #[username_check] +SUPPORT_REGISTER=TRUE +REGISTER_ENDPOINT="/register" +HOMEPAGE_URL= +SERVER_NAME="Yggdrasil" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b20441f --- /dev/null +++ b/.gitignore @@ -0,0 +1,136 @@ +# ---> Node +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +#Modun Globals +logs +tests +data/keys \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2a76b9f --- /dev/null +++ b/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + Base-REST-API + Copyright (C) 2025 azures04 + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..325827a --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# Yggdrasil \ No newline at end of file diff --git a/data/textures/alex.png b/data/textures/alex.png new file mode 100644 index 0000000000000000000000000000000000000000..b643fe2d083f64677a630087ba4c4004eac1ca06 GIT binary patch literal 3420 zcmV-i4WsgjP)Px#24YJ`L;#EcxB!Yvbt8HJ000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2i^!2 z4I~Ks0H!ej000(gR9JLFZ*6U5ZgcGub@&yq{VgycsJMh@o?as}kck@S2_ss0>J$Ekx>8h=s znV#wH@B2Nv``5h!hDe7u&MyN1`uc%r7=i1)e&qA{LBF5&)Q1AKtqxrIB(y91{Gq;Yk#kP ze&C&N6!#6Q`p}SXM8hzw0tL$madYC>9DFX93;Zex8Fh-OFw6o4%Ls9E;#eGfE}ISf zDhU}q0SvH@5KW0tNmvDpd18QlglMYUzFB|!q2auwSz?v+nMSDBK0M|eXqHqZeWnr7 zYwsIl0$lrN>TXyC{w%5|$6f6~xP+who?ieEPb9{MfT*4XQEaOAk{kfvSIj^JF!PFe1AILXcH)sK8W>_26b^5kUuHH<9Gin=K-qZDb7mF;%nMk~ z>Z?_TXc(d-gJklsqA`KlG;u5rk^yDoJgD&0T(?84vm}PvK;4|0gc=0HOd+Lk(pb*QSiSt-Etje~ z7nuc|6?*)(v;?GQeEfsqKw%_*Xn}KO?+p_KazGrtQR8>WC>NUZ4{NJpdM@da7T&w)fvXbl& z>o^xwF@waMb|mJs!>|en&%Pg%@7jU+A9X`jRX_~ms^?dr<)VcsUvfJosIT9v!&QI3 z{d2Qm(szA_n2b^IY9!FXp52}3+1-h@W!v${brWIRHfFAvg_arDBRTaN%v>=Gwr%5) z>n5UY*>)UQJI`A)xa#k>e{L2``mXN~Q!xmi{o?YnW{F(#i8<|1^#nkuA8;H8f+#~2 z%77TA&jk^V<3JJxn5K#B+drWM_#C6(Gy)E>!c4NJC1{q!y?XPUN1^I*fKWf+mv-i} zT>voy&w6%uqWA5!ltiCn^qWS&Ay$})aQL~a%6^+yF1wFQn(9kG2Tl$dw1UZWHei}2 zR6PN+n586GVogu)pHy+*;`#-vtO$Oa*Dt->ZQu3q#H8261o_f!f1l3+F~?LQX)VB1IkZtP5O zwCNA(h5UM<`AOCAS65O1SdFP_%m@I0Tdw*J0N~X>150qE;q^1=H&2+135m$bMZnS< z7E)&hU`f*v&nGk@S&i$b@Wi(EG8C`k6CJN3m5f1^Mf7I!ux&zzJV}D%IGDC_F&)18 zG8B|Z0v&5gG{bs-Ux0w(uJu(b$f|XRf879J^TgTEWew>^hPI^TuX_y-dM{e z%YZXL3@}R(ErPOBs&;z5l!zwjJFIP2LzwhO>;oLf8|qBcM)&ayQpp%h(;Tr)9nT)e z_{4bN;v`;rqmw#AcLKCw{0u-O0jV*-tn&;&u0Mx(I1Xjc7f{u(+qZt$@-b+d4#Oxy zvCTl4;ychNH5G&4~zr_kX7Z zpR;%UDIB3hFo1?Z{gS3fASqN30z`<4Cv~GQJMxK8E|(h+>|kXtta=e4RYb`o2&p1w z&ixjyxbn&>A^>35&Yk%Cjt{5=YrJojtiU(BcJ9QjH_hPSX>M}~6Qc-GQK14LmI+a# zglN&>YkAH?kCI&S}1O99E0mDv<7X#6#cYoGdfICXz^Us6tPMb#a?r!hd>eZ*X2K4plhjA3EiH0GpJh(+#Qaq&I=( zM?S#0XP-f5ihK89N@+T9fR_Dd|EF{Ur7OU}e_~weC;;Hg;~qK7Pdg0&_&h(MD@f=H zvPJ9kHG#Zg4@$!Sl@CbhbkQ*`UOo1YRtruU0tN%fh&e5tU`(sMpExca!B?5uB%}+* zX*>*8Xhl5^@RV8$FbVHDcm%14hIGL|U#^H~SVqyJj$J-wdFJ1uPo{rT+#tTk56CjR_2f9BUeFd$pz@kNb)i~5@@uV~X zlF0*2!TtXc2R&L_hZQe4`J7;1KQ>I8U0=Ll>(*gwK;1szu6Y-g{pSZXO+|Au2Gb@; zy9Xlt<&lVn_?`230Q5w*mj_DOR{1O6{H{Bk1s6PQ|NoYcI&tXdi=!1K{;I_FuN-Rn;JyYyY6;b4}Q^KnkUk_w`@q#T| z==GCN(s;pw1=JaiA5Wh@{WLAB5ie-C570FQ=}aDHj!&X!l&gs1%X*sxK>}ER=5(aw z6yHy%B%$X1f30`{05mmu0h6(Ig8uUb0FX+?0$b>VrGfVUHKPb?H2eQ7UXV%whYtO3 zCqj6w6Z8f*5x1ps&) zK*zzIHRAbk8L+DGx^jHa@el@g^{u^97ZA`*eb?K#L|o2m!H7?`(iu z=1)Jne|AEvXx(0d=1*08lR5AeIN-zyHq&@*jbzOdU(+ y^6NbZk6_(hHv<5Ux$%OP-shV8w)Zc5G^1OFCYyo9t|iQ z3oITEGb9m0DiS{`6($%9D;^Fg8w(^D3bu)Cy^eCmmVmvBa=ngptae&7B@!qa4J{oG zFCr1DeP*diE^B2OePu(BNqvWSUQ|zMLH-H|Ns9|J&Cn@XDl8Ogii2#3p09#uCnVA5do&c|}0BC53RXdh%TR%TPYinz~Gp6qV0004WQchC< zK<3zH0008TNkl=4CIQG8L_ z7<3T2_%~7tDt2nx1Cw0>Fr;ZttOBLHi*p3v#>~SQ^LTx3mxp0D=mOrwNrBrBI1mhB z_W1Pt^7afQpeL)cEhEE&BotKVd>IAfchCf8DqWCs?}nsMP`jYk7XcW5g-w8* z5h>u&A>b&V0") + } + + if (this.errorType && this.errorType.trim() !== "") { + response.error = this.errorType + response.errorType = this.errorType + } + + if (this.details) { + response.details = this.details + } + + if (this.errorMessage && this.errorMessage.trim() !== "") { + response.errorMessage = this.errorMessage + } + + if (this.developerMessage && this.developerMessage.trim() !== "") { + response.developerMessage = this.developerMessage + } + + return response + } +} + +module.exports = ServiceError \ No newline at end of file diff --git a/errors/SessionError.js b/errors/SessionError.js new file mode 100644 index 0000000..364dfb4 --- /dev/null +++ b/errors/SessionError.js @@ -0,0 +1,24 @@ +class SessionError extends Error { + constructor(statusCode, error, errorMessage, path) { + super(errorMessage) + this.path = path + this.error = error + this.statusCode = statusCode + this.errorMessage = errorMessage + this.isOperational = true + Error.captureStackTrace(this, this.constructor) + } + + serialize() { + const response = { + path: this.path, + errorMessage: this.errorMessage + } + if (this.error != undefined) { + response.error = this.error + } + return response + } +} + +module.exports = SessionError \ No newline at end of file diff --git a/errors/ValidationError.js b/errors/ValidationError.js new file mode 100644 index 0000000..7743b54 --- /dev/null +++ b/errors/ValidationError.js @@ -0,0 +1,119 @@ +const DefaultError = require("./DefaultError") +const YggdrasilError = require("./YggdrasilError") +const SessionError = require("./SessionError") +const ServiceError = require("./ServiceError") +const logger = require("../modules/logger") + +class ValidationError extends DefaultError { + constructor(result, config = {}, context = {}) { + let formattedErrors = [] + if (result && result.error && Array.isArray(result.error.issues)) { + formattedErrors = result.error.issues.flatMap(issue => { + if (issue.code === "unrecognized_keys") { + return issue.keys.map(key => ({ + field: [...issue.path, key].join("."), + message: "Field not allowed" + })) + } + + if (issue.code === "invalid_union") { + return { + field: issue.path.join("."), + message: "Invalid input format (union mismatch)" + } + } + + return { + field: issue.path.join("."), + message: issue.message + } + }) + } + else if (result instanceof Error) { + formattedErrors = [{ + field: "global", + message: result.message + }] + } + else if (typeof result === "string") { + formattedErrors = [{ + field: "global", + message: result + }] + } + else { + formattedErrors = [{ + field: "unknown", + message: "Unknown validation error" + }] + } + + const message = config.message || "Validation failed" + const statusCode = config.code || 400 + + super(statusCode, message, { errors: formattedErrors }) + + this.config = config + this.formattedErrors = formattedErrors + this.context = context + + this.logError() + } + + logError() { + const { method, path, ip } = this.context + if (method && path) { + logger.warn( + `Validation failed for ${method} ${path} (${this.config.errorFormat || "Standard"}) ` + + ``, + ["WEB", "yellow"] + ) + } + } + + serialize() { + if (this.config.errorFormat === "YggdrasilError") { + const err = new YggdrasilError( + this.code, + this.config.errorName || "IllegalArgumentException", + this.message, + JSON.stringify(this.formattedErrors) + ) + return err.serialize() + } + + if (this.config.errorFormat === "SessionError") { + const err = new SessionError( + this.code, + this.config.errorName || "Forbidden", + this.message, + this.context.path || "" + ) + return err.serialize() + } + + if (this.config.errorFormat === "ServiceError") { + const err = new ServiceError( + this.code, + this.context.path || "", + this.config.errorName || "ValidationException", + this.message, + this.formattedErrors + ) + return err.serialize() + } + const response = { + code: this.code, + message: this.message, + errors: this.formattedErrors + } + + if (this.cause) { + response.cause = this.cause + } + + return response + } +} + +module.exports = ValidationError \ No newline at end of file diff --git a/errors/YggdrasilError.js b/errors/YggdrasilError.js new file mode 100644 index 0000000..e6738f1 --- /dev/null +++ b/errors/YggdrasilError.js @@ -0,0 +1,26 @@ +class YggdrasilError extends Error { + constructor(statusCode, error, errorMessage, cause) { + super(errorMessage) + this.statusCode = statusCode + + this.error = error + this.errorMessage = errorMessage + this.cause = cause + + this.isOperational = true + Error.captureStackTrace(this, this.constructor) + } + + serialize() { + const response = { + error: this.error, + errorMessage: this.errorMessage + } + if (this.cause) { + response.cause = this.cause + } + return response + } +} + +module.exports = YggdrasilError \ No newline at end of file diff --git a/errors/errors.js b/errors/errors.js new file mode 100644 index 0000000..f5339ad --- /dev/null +++ b/errors/errors.js @@ -0,0 +1,13 @@ +const DefaultError = require("./DefaultError") +const ServiceError = require("./ServiceError") +const SessionError = require("./SessionError") +const YggdrasilError = require("./YggdrasilError") +const ValidationError = require("./ValidationError") + +module.exports = { + DefaultError, + SessionError, + ServiceError, + YggdrasilError, + ValidationError +} \ No newline at end of file diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..b47f6c9 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,28 @@ +const js = require("@eslint/js") +const globals = require("globals") + +module.exports = [ + { + ignores: ["node_modules", "data", "logs", "coverage", ".env", "*.log"], + }, + js.configs.recommended, + { + languageOptions: { + ecmaVersion: "latest", + sourceType: "commonjs", + globals: { + ...globals.node, + ...globals.jest, + }, + }, + rules: { + "no-unused-vars": "warn", + "no-undef": "error", + "eqeqeq": "error", + "indent": ["error", 4], + "quotes": ["error", "double"], + "semi": ["error", "never"], + "no-console": "warn", + }, + }, +] \ No newline at end of file diff --git a/modules/certificatesManager.js b/modules/certificatesManager.js new file mode 100644 index 0000000..df3365e --- /dev/null +++ b/modules/certificatesManager.js @@ -0,0 +1,64 @@ +const fs = require("node:fs") +const path = require("node:path") +const crypto = require("node:crypto") +const keysRoot = path.join(process.cwd(), "data", "keys") +const keysList = ["authenticationKeys", "profilePropertyKeys", "playerCertificateKeys"] + +function generateKeysPair() { + try { + const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", { + modulusLength: 2048, + publicKeyEncoding: { + type: "spki", + format: "pem" + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem" + } + }) + return { privateKey, publicKey } + } catch (error) { + console.error("Erreur lors de la génération des clés :", error) + return { publicKey: null, privateKey: null } + } +} + +function setupKeys() { + if (!fs.existsSync(keysRoot)) { + fs.mkdirSync(keysRoot, { recursive: true }) + } + for (const key of keysList) { + if (!fs.existsSync(path.join(keysRoot, `${key}-public.pem`)) || !fs.existsSync(path.join(keysRoot, `${key}-private.pem`))) { + const { publicKey, privateKey } = generateKeysPair() + fs.writeFileSync(path.join(keysRoot, `${key}-public.pem`), publicKey) + fs.writeFileSync(path.join(keysRoot, `${key}-private.pem`), privateKey) + } + } +} + +function getKeys() { + const keys = {} + for (const key of keysList) { + keys[key] = {} + keys[key].public = fs.readFileSync(path.join(keysRoot, `${key}-public.pem`)).toString("utf8") + keys[key].private = fs.readFileSync(path.join(keysRoot, `${key}-private.pem`)).toString("utf8") + } + return keys +} + +function extractKeyFromPem(pemKey) { + const keyRegex = /-----BEGIN (?:PUBLIC|PRIVATE) KEY-----\s*([\s\S]+?)\s*-----END (?:PUBLIC|PRIVATE) KEY-----/ + const match = pemKey.match(keyRegex) + if (match && match[1]) { + const rawKey = match[1].replace(/\s/g, "") + return rawKey + } + return null +} + +module.exports = { + extractKeyFromPem, + setupKeys, + getKeys, +} \ No newline at end of file diff --git a/modules/database.js b/modules/database.js new file mode 100644 index 0000000..463f5b2 --- /dev/null +++ b/modules/database.js @@ -0,0 +1,16 @@ +const mariadb = require("mariadb") + +const pool = mariadb.createPool({ + host: process.env.DATABASE_HOST, + user: process.env.DATABASE_USER, + password: process.env.DATABASE_PASSWORD, + database: process.env.DATABASE_NAME, + connectionLimit: process.env.DATABASE_CONNECTION_LIMIT || 10, + acquireTimeout: 20000, + connectTimeout: 20000, + bigIntAsNumber: true, + insertIdAsNumber: true, + decimalAsNumber: true +}) + +module.exports = pool \ No newline at end of file diff --git a/modules/databaseGlobals.js b/modules/databaseGlobals.js new file mode 100644 index 0000000..d55e327 --- /dev/null +++ b/modules/databaseGlobals.js @@ -0,0 +1,390 @@ +const path = require("node:path") +const mariadb = require("mariadb") +const logger = require("./logger") +const crypto = require("node:crypto") + +const rootConfig = { + host: process.env.DATABASE_HOST, + user: process.env.DATABASE_USER, + password: process.env.DATABASE_PASSWORD, + connectionLimit: 1, + connectTimeout: 20000 +} + +async function setupDatabase() { + let conn + + try { + conn = await mariadb.createConnection(rootConfig) + await conn.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DATABASE_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`) + logger.log(`Base de données '${process.env.DB_NAME}' vérifiée.`, ["MariaDB", "yellow"]) + await conn.end() + + conn = await mariadb.createConnection({ + ...rootConfig, + database: process.env.DB_NAME, + multipleStatements: true + }) + logger.log("Checking and synchronising the schema...", ["MariaDB", "yellow"]) + await conn.query(`USE \`${process.env.DATABASE_NAME}\``) + + await conn.query(` + CREATE TABLE IF NOT EXISTS players ( + email VARCHAR(255) NULL UNIQUE, + username VARCHAR(16) NOT NULL UNIQUE, + password TEXT NOT NULL, + uuid VARCHAR(36) NOT NULL UNIQUE PRIMARY KEY, + nameChangeAllowed TINYINT(1) DEFAULT 1, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `) + logger.log(`${"players".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playersProperties ( + name VARCHAR(256) NOT NULL, + value VARCHAR(512) NOT NULL, + uuid VARCHAR(36) NOT NULL, + UNIQUE KEY unique_property (uuid, name), + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"playersProperties".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS clientSessions ( + accessToken TEXT NOT NULL, + clientToken VARCHAR(36) NOT NULL, + uuid VARCHAR(36) NOT NULL, + FOREIGN KEY (uuid) REFERENCES players(uuid) + ) + `) + logger.log(`${"clientSessions".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS legacyClientSessions ( + sessionId VARCHAR(36) NOT NULL, + uuid VARCHAR(36) NOT NULL, + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"legacyClientSessions".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS uuidToNameHistory ( + uuid VARCHAR(36) NOT NULL, + username VARCHAR(255) NOT NULL, + changedAt DATETIME NULL, + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"uuidToNameHistory".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(`CREATE INDEX IF NOT EXISTS idx_uuidToNameHistory_uuid ON uuidToNameHistory (uuid)`) + logger.log(`${"idx_uuidToNameHistory_uuid".bold} index ready`, ["MariaDB", "yellow"]) + + await conn.query(`DROP TRIGGER IF EXISTS log_new_user_name`) + await conn.query(` + CREATE TRIGGER log_new_user_name + AFTER INSERT ON players + FOR EACH ROW + BEGIN + INSERT INTO uuidToNameHistory (uuid, username, changedAt) + VALUES (NEW.uuid, NEW.username, NULL); + END; + `) + logger.log(`${"log_new_user_name".bold} trigger ready`, ["MariaDB", "yellow"]) + + await conn.query(`DROP TRIGGER IF EXISTS log_user_name_change`) + await conn.query(` + CREATE TRIGGER log_user_name_change + AFTER UPDATE ON players + FOR EACH ROW + BEGIN + IF OLD.username != NEW.username THEN + INSERT INTO uuidToNameHistory (uuid, username, changedAt) + VALUES (NEW.uuid, NEW.username, CURRENT_TIMESTAMP); + END IF; + END; + `) + logger.log(`${"log_user_name_change".bold} trigger ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS blockedServers ( + hashedIp VARCHAR(40) NOT NULL PRIMARY KEY, + banner VARCHAR(256) DEFAULT 'CONSOLE', + reason VARCHAR(512) NULL + ) + `) + logger.log(`${"blockedServers".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playersPrivileges ( + uuid VARCHAR(36) PRIMARY KEY, + onlineChat TINYINT(1) DEFAULT 1, + multiplayerServer TINYINT(1) DEFAULT 1, + multiplayerRealms TINYINT(1) DEFAULT 1, + telemetry TINYINT(1) DEFAULT 1, + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"playersPrivileges".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playersPreferences ( + uuid VARCHAR(36) PRIMARY KEY, + profanityFilter TINYINT(1) DEFAULT 0, + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"playersPreferences".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS banReasons ( + id INTEGER PRIMARY KEY AUTO_INCREMENT, + reason_key VARCHAR(512) UNIQUE NOT NULL + ) + `) + logger.log(`${"banReasons".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS bans ( + banId VARCHAR(512) PRIMARY KEY NOT NULL, + uuid VARCHAR(36) NOT NULL, + expires BIGINT DEFAULT NULL, + reason INTEGER NOT NULL, + reasonMessage VARCHAR(1024) DEFAULT NULL, + FOREIGN KEY(reason) REFERENCES banReasons(id), + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"bans".bold} table ready`, ["MariaDB", "yellow"]) + await conn.query(`CREATE INDEX IF NOT EXISTS idx_bans_uuid ON bans (uuid)`) + logger.log(`${"idx_bans_uuid".bold} index ready`, ["MariaDB", "yellow"]) + + await conn.query(`DROP TRIGGER IF EXISTS auto_init_player_settings`) + await conn.query(` + CREATE TRIGGER auto_init_player_settings + AFTER INSERT ON players + FOR EACH ROW + BEGIN + INSERT INTO playersPrivileges (uuid) VALUES (NEW.uuid); + INSERT INTO playersPreferences (uuid) VALUES (NEW.uuid); + END; + `) + logger.log(`${"auto_init_player_settings".bold} trigger ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playersBlockslist ( + blockerUuid VARCHAR(36) NOT NULL, + blockedUuid VARCHAR(36) NOT NULL, + PRIMARY KEY (blockerUuid, blockedUuid), + FOREIGN KEY (blockerUuid) REFERENCES players(uuid) ON DELETE CASCADE, + FOREIGN KEY (blockedUuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"playersBlockslist".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS usernameRules ( + id INTEGER PRIMARY KEY AUTO_INCREMENT, + rule VARCHAR(255) NOT NULL, + type INTEGER DEFAULT 0 + ) + `) + logger.log(`${"usernameRules".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS textures ( + uuid VARCHAR(36) NOT NULL UNIQUE, + hash VARCHAR(64) PRIMARY KEY NOT NULL, + type VARCHAR(10) NOT NULL, + url VARCHAR(2048) NOT NULL, + alias VARCHAR(64) NULL, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `) + logger.log(`${"textures".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playersSkins ( + playerUuid VARCHAR(36) NOT NULL, + assetHash VARCHAR(64) NOT NULL, + variant VARCHAR(10) DEFAULT "CLASSIC", + isSelected TINYINT(1) DEFAULT 0, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (playerUuid, assetHash), + FOREIGN KEY (playerUuid) REFERENCES players(uuid) ON DELETE CASCADE, + FOREIGN KEY (assetHash) REFERENCES textures(hash) + ) + `) + logger.log(`${"playersSkins".bold} table ready`, ["MariaDB", "yellow"]) + await conn.query(`CREATE INDEX IF NOT EXISTS idx_active_skin ON playersSkins (playerUuid, isSelected)`) + logger.log(`${"idx_active_skin".bold} index ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playersCapes ( + id INTEGER PRIMARY KEY AUTO_INCREMENT, + playerUuid VARCHAR(36) NOT NULL, + assetHash VARCHAR(64) NOT NULL, + isSelected TINYINT(1) DEFAULT 0, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (playerUuid) REFERENCES players(uuid) ON DELETE CASCADE, + FOREIGN KEY (assetHash) REFERENCES textures(hash) + ) + `) + logger.log(`${"playersCapes".bold} table ready`, ["MariaDB", "yellow"]) + await conn.query(`CREATE INDEX IF NOT EXISTS idx_active_cape ON playersCapes (playerUuid, assetHash)`) + logger.log(`${"idx_active_cape".bold} index ready`, ["MariaDB", "yellow"]) + + await conn.query(`INSERT IGNORE INTO textures (hash, type, url, uuid) VALUES ('df8ed96c557d441a63e7b6a4a911ab84fa453b42fc2ae6b01c3e1b02e138168c', 'SKIN', '/texture/alex.png', '${crypto.randomUUID()}')`) + await conn.query(`INSERT IGNORE INTO textures (hash, type, url, uuid) VALUES ('4c7b0468044bfecacc43d00a3a69335a834b73937688292c20d3988cae58248d', 'SKIN', '/texture/steve.png', '${crypto.randomUUID()}')`) + logger.log(`defaults skins (steve, alex) ready`, ["MariaDB", "yellow"]) + + await conn.query(`DROP TRIGGER IF EXISTS unique_active_skin`) + await conn.query(` + CREATE TRIGGER unique_active_skin + AFTER UPDATE ON playersSkins + FOR EACH ROW + BEGIN + IF NEW.isSelected = 1 THEN + UPDATE playersSkins + SET isSelected = 0 + WHERE playerUuid = NEW.playerUuid + AND assetHash != NEW.assetHash; + END IF; + END; + `) + logger.log(`${"unique_active_skin".bold} trigger ready`, ["MariaDB", "yellow"]) + + await conn.query(`DROP TRIGGER IF EXISTS unique_active_cape`) + await conn.query(` + CREATE TRIGGER unique_active_cape + AFTER UPDATE ON playersCapes + FOR EACH ROW + BEGIN + IF NEW.isSelected = 1 THEN + UPDATE playersCapes + SET isSelected = 0 + WHERE playerUuid = NEW.playerUuid + AND id != NEW.id; + END IF; + END; + `) + logger.log(`${"unique_active_cape".bold} trigger ready`, ["MariaDB", "yellow"]) + + await conn.query(`DROP TRIGGER IF EXISTS auto_assign_random_default_skin`) + await conn.query(` + CREATE TRIGGER auto_assign_random_default_skin + AFTER INSERT ON players + FOR EACH ROW + BEGIN + INSERT INTO playersSkins (playerUuid, assetHash, variant, isSelected) + SELECT + NEW.uuid, + hash, + CASE + WHEN hash = '4c7b0468044bfecacc43d00a3a69335a834b73937688292c20d3988cae58248d' THEN 'CLASSIC' + ELSE 'SLIM' + END, + 1 + FROM textures + WHERE hash IN ( + '4c7b0468044bfecacc43d00a3a69335a834b73937688292c20d3988cae58248d', + 'df8ed96c557d441a63e7b6a4a911ab84fa453b42fc2ae6b01c3e1b02e138168c' + ) + ORDER BY RAND() + LIMIT 1; + END; + `) + logger.log(`${"auto_assign_random_default_skin".bold} trigger ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playerCertificates ( + uuid VARCHAR(36) PRIMARY KEY, + privateKey TEXT NOT NULL, + publicKey TEXT NOT NULL, + publicKeySignatureV2 TEXT NOT NULL, + expiresAt DATETIME NOT NULL, + refreshedAfter DATETIME NOT NULL, + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"playerCertificates".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS playerProfileActions ( + uuid VARCHAR(36) NOT NULL, + action VARCHAR(64) NOT NULL, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (uuid, action), + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"playerProfileActions".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS serverSessions ( + uuid VARCHAR(36) PRIMARY KEY, + accessToken TEXT NOT NULL, + serverId VARCHAR(255) NOT NULL, + ip VARCHAR(45) NULL, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (uuid) REFERENCES players(uuid) ON DELETE CASCADE + ) + `) + logger.log(`${"serverSessions".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(`SET GLOBAL event_scheduler = ON;`) + logger.log("MariaDB Event Scheduler enabled.", ["MariaDB", "yellow"]) + + await conn.query(` + CREATE EVENT IF NOT EXISTS clean_expired_certificates + ON SCHEDULE EVERY 1 HOUR + DO + DELETE FROM playerCertificates WHERE expiresAt < NOW(); + `) + logger.log(`${"clean_expired_certificates".bold} event ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS api_administrators ( + id INTEGER PRIMARY KEY AUTO_INCREMENT, + username VARCHAR(255) UNIQUE NOT NULL, + password TEXT NOT NULL, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `) + logger.log(`${"api_administrators".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS api_administrators_permissions_list ( + permission_key VARCHAR(64) PRIMARY KEY + ) + `) + logger.log(`${"api_administrators_permissions_list".bold} table ready`, ["MariaDB", "yellow"]) + + await conn.query(` + CREATE TABLE IF NOT EXISTS api_administrators_permissions ( + administrator_id INTEGER NOT NULL, + permission_key VARCHAR(64) NOT NULL, + PRIMARY KEY (administrator_id, permission_key), + FOREIGN KEY (administrator_id) REFERENCES api_administrators(id) ON DELETE CASCADE, + FOREIGN KEY (permission_key) REFERENCES api_administrators_permissions_list(permission_key) ON DELETE CASCADE + ) + `) + logger.log(`${"api_administrators_permissions".bold} table ready`, ["MariaDB", "yellow"]) + + logger.log("MariaDB database successfully initialised!", ["MariaDB", "yellow"]) + + } catch (err) { + logger.error("Critical error during DB initialisation: " + err.message, ["MariaDB", "yellow"]) + console.error(err) + process.exit(1) + } finally { + if (conn) conn.end() + } +} + +module.exports = { + setupDatabase +} \ No newline at end of file diff --git a/modules/loader.js b/modules/loader.js new file mode 100644 index 0000000..4a2663a --- /dev/null +++ b/modules/loader.js @@ -0,0 +1,52 @@ +const fs = require("node:fs") +const path = require("node:path") + +function getRecursiveFiles(dir) { + let results = [] + + if (!fs.existsSync(dir)) { + return results + } + + const list = fs.readdirSync(dir) + + for (const file of list) { + const fullPath = path.join(dir, file) + const stat = fs.statSync(fullPath) + + if (stat && stat.isDirectory()) { + results = results.concat(getRecursiveFiles(fullPath)) + } else { + if (fullPath.endsWith(".js")) { + results.push(fullPath) + } + } + } + + return results +} + +function computeRoutePath(baseDir, filePath) { + const relativePath = path.relative(baseDir, filePath) + let route = "/" + relativePath.split(path.sep).join("/") + + if (route.endsWith(".js")) { + route = route.slice(0, -3) + } + if (route.endsWith("/index")) { + route = route.slice(0, -6) + } + + route = route.replace(/\[([^\]]+)\]/g, ":$1") + + if (route === "") { + return "/" + } + + return route +} + +module.exports = { + getRecursiveFiles, + computeRoutePath +} \ No newline at end of file diff --git a/modules/logger.js b/modules/logger.js new file mode 100644 index 0000000..7026d44 --- /dev/null +++ b/modules/logger.js @@ -0,0 +1,89 @@ +const fs = require("node:fs") +const path = require("node:path") +const utils = require("./utils") +require("colors") +require("dotenv").config({ + quiet: true +}) + +function cleanup($stream) { + if (!$stream.destroyed) { + $stream.end() + } +} + +function write($stream, level, color, content, extraLabels = []) { + const date = new Date().toISOString() + const message = typeof content === "string" ? content : JSON.stringify(content, null, 2) + + let consoleLabels = "" + let fileLabels = "" + + if (Array.isArray(extraLabels) && extraLabels.length > 0) { + for (let i = 0; i < extraLabels.length; i += 2) { + const labelName = extraLabels[i] + const labelColor = extraLabels[i + 1] + if (labelName) { + fileLabels += ` [${labelName}]` + if (labelColor && labelName[labelColor]) { + consoleLabels += ` [${labelName[labelColor]}]` + } else { + consoleLabels += ` [${labelName.white}]` + } + } + } + } + + // eslint-disable-next-line no-console + console.log(`[${date}] `.magenta + `[${level}]`[color] + consoleLabels + " " + message) + $stream.write(`[${date}] [${level}]${fileLabels} ${stripColors(message)}\n`) +} + +function createLogger(root) { + // eslint-disable-next-line no-useless-escape + const fileName = utils.isTrueFromDotEnv("IS_PROD") ? new Date().toLocaleString("fr-FR", { timeZone: "UTC" }).replace(/[\/:]/g, "-").replace(/ /g, "_") : "DEV-LOG" + + const logsDir = path.join(root, "logs") + + if (!fs.existsSync(logsDir)) { + fs.mkdirSync(logsDir, { recursive: true }) + } + + const stream = fs.createWriteStream(path.join(logsDir, `${fileName}.log`), { flags: "a" }) + + process.on("exit", () => { + cleanup(stream) + }) + + process.on("SIGINT", () => { + cleanup(stream) + process.exit() + }) + + return { + log: (content, labels) => { + write(stream, "INFO", "green", content, labels) + }, + error: (content, labels) => { + write(stream, "ERROR", "red", content, labels) + }, + warn: (content, labels) => { + write(stream, "WARN", "yellow", content, labels) + }, + debug: (content, labels) => { + write(stream, "DEBUG", "white", content, labels) + } + } +} + +function stripColors(string) { + if (!string || typeof string !== "string") { + return string + } + // eslint-disable-next-line no-control-regex + return string.replace(/\x1B\[[0-9;]*[mK]/g, "") +} + +const logger = createLogger(process.cwd()) + +module.exports = logger \ No newline at end of file diff --git a/modules/utils.js b/modules/utils.js new file mode 100644 index 0000000..40a0860 --- /dev/null +++ b/modules/utils.js @@ -0,0 +1,63 @@ +const crypto = require("node:crypto") +const certificatesManager = require("./certificatesManager") + +async function getRegistrationCountryFromIp(ipAddress) { + const apiUrl = `https://ip-api.com/json/${ipAddress}?fields=countryCode` + + try { + const response = await fetch(apiUrl) + if (!response.ok) { + return "FR" + } + + const data = await response.json() + if (data && data.countryCode) { + const countryCode = data.countryCode + return countryCode + } else { + return "FR" + } + + } catch (error) { + return "??" + } +} + +function signProfileData(dataBase64) { + const serverKeys = certificatesManager.getKeys() + try { + const privateKey = serverKeys.profilePropertyKeys.private + const signer = crypto.createSign("SHA1") + signer.update(dataBase64) + signer.end() + return signer.sign(privateKey, "base64") + } catch (err) { + console.error("Signing failed:", err) + return null + } +} + +function addDashesToUUID(uuid) { + if (typeof uuid !== "string" || uuid.length !== 32) { + return uuid + } + + return ( + uuid.slice(0, 8) + "-" + + uuid.slice(8, 12) + "-" + + uuid.slice(12, 16) + "-" + + uuid.slice(16, 20) + "-" + + uuid.slice(20) + ) +} + +function isTrueFromDotEnv(key) { + return (process.env[key] || "").trim().toLowerCase() === "true" +} + +module.exports = { + signProfileData, + addDashesToUUID, + isTrueFromDotEnv, + getRegistrationCountryFromIp, +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..9a2d1b8 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2703 @@ +{ + "name": "base-rest-api", + "version": "0.0.1-alpha", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "base-rest-api", + "version": "0.0.1-alpha", + "license": "AGPL-3.0-only", + "dependencies": { + "bcryptjs": "^3.0.3", + "colors": "^1.4.0", + "cors": "^2.8.5", + "dotenv": "^17.2.3", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "helmet": "^8.1.0", + "hpp": "^0.2.3", + "jsonwebtoken": "^9.0.3", + "mariadb": "^3.4.5", + "multer": "^2.0.2", + "path-to-regexp": "^8.3.0", + "ssrfcheck": "^1.2.0", + "zod": "^4.2.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.2", + "eslint": "^9.39.2", + "globals": "^16.5.0", + "nodemon": "^3.1.11" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", + "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz", + "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.3.tgz", + "integrity": "sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.2.tgz", + "integrity": "sha512-q1mjIoW1VX4IvSocvM/vbTiveKC4k9eLrajNEuSsmjymSDEbpGddtpfOoN7YGAqBK3NG+uqo8ia4PDTt8buCYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.10.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz", + "integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/bcryptjs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", + "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", + "license": "BSD-3-Clause", + "bin": { + "bcrypt": "bin/bcrypt" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz", + "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "license": "MIT", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dotenv": { + "version": "17.2.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", + "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.2.tgz", + "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.1", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.39.2", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz", + "integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==", + "license": "MIT", + "dependencies": { + "ip-address": "10.0.1" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globals": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/helmet": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz", + "integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/hpp": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/hpp/-/hpp-0.2.3.tgz", + "integrity": "sha512-4zDZypjQcxK/8pfFNR7jaON7zEUpXZxz4viyFmqjb3kWNWAHsLEUmWXcdn25c5l76ISvnD6hbOGO97cXUI3Ryw==", + "license": "ISC", + "dependencies": { + "lodash": "^4.17.12", + "type-is": "^1.6.12" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/hpp/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/hpp/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/hpp/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/hpp/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", + "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true, + "license": "ISC" + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz", + "integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/mariadb": { + "version": "3.4.5", + "resolved": "https://registry.npmjs.org/mariadb/-/mariadb-3.4.5.tgz", + "integrity": "sha512-gThTYkhIS5rRqkVr+Y0cIdzr+GRqJ9sA2Q34e0yzmyhMCwyApf3OKAC1jnF23aSlIOqJuyaUFUcj7O1qZslmmQ==", + "license": "LGPL-2.1-or-later", + "dependencies": { + "@types/geojson": "^7946.0.16", + "@types/node": "^24.0.13", + "denque": "^2.1.0", + "iconv-lite": "^0.6.3", + "lru-cache": "^10.4.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/mariadb/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz", + "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "mkdirp": "^0.5.6", + "object-assign": "^4.1.1", + "type-is": "^1.6.18", + "xtend": "^4.0.2" + }, + "engines": { + "node": ">= 10.16.0" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemon": { + "version": "3.1.11", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.11.tgz", + "integrity": "sha512-is96t8F/1//UHAjNPHpbsNY46ELPpftGUoSVNXwUfMk/qdjSylYrWSu1XavVTBOn526kFiOR733ATgNBCQyH0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ssrfcheck": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/ssrfcheck/-/ssrfcheck-1.2.0.tgz", + "integrity": "sha512-tWmE4yluJK+GKL/Q6atEEVkmN7s0MdQvOJThCl+BY0ntLg/APRqR5st8EUnyI+dzWohrcMFvxMYzSZlsitvgEw==", + "license": "MIT", + "bin": { + "ssrfcheck": "src/cli.js" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.2.0.tgz", + "integrity": "sha512-Bd5fw9wlIhtqCCxotZgdTOMwGm1a0u75wARVEY9HMs1X17trvA/lMi4+MGK5EUfYkXVTbX8UDiDKW4OgzHVUZw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2ef1169 --- /dev/null +++ b/package.json @@ -0,0 +1,47 @@ +{ + "name": "base-rest-api", + "version": "0.0.1-alpha", + "description": "", + "repository": { + "type": "git", + "url": "https://gitea.azures.fr/azures04/Yggdrasil" + }, + "license": "AGPL-3.0-only", + "author": { + "name": "azures04", + "url": "https://gitea.azures.fr/azures04/Yggdrasil", + "email": "gilleslazure04@gmail.com" + }, + "type": "commonjs", + "main": "server.js", + "scripts": { + "start:dev": "nodemon .", + "start": "node .", + "lint": "eslint .", + "lint:fix": "eslint . --fix" + }, + "homepage": "https://gitea.azures.fr/azures04/Yggdrasil", + "readme": "https://gitea.azures.fr/azures04/Yggdrasil/src/branch/main/README.md", + "dependencies": { + "bcryptjs": "^3.0.3", + "colors": "^1.4.0", + "cors": "^2.8.5", + "dotenv": "^17.2.3", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "helmet": "^8.1.0", + "hpp": "^0.2.3", + "jsonwebtoken": "^9.0.3", + "mariadb": "^3.4.5", + "multer": "^2.0.2", + "path-to-regexp": "^8.3.0", + "ssrfcheck": "^1.2.0", + "zod": "^4.2.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.2", + "eslint": "^9.39.2", + "globals": "^16.5.0", + "nodemon": "^3.1.11" + } +} diff --git a/repositories/adminRepository.js b/repositories/adminRepository.js new file mode 100644 index 0000000..7f2891b --- /dev/null +++ b/repositories/adminRepository.js @@ -0,0 +1,131 @@ +const logger = require("../modules/logger") +const database = require("../modules/database") +const { DefaultError } = require("../errors/errors") + +async function getAdminById(id) { + try { + const sql = "SELECT id, username, createdAt FROM api_administrators WHERE id = ?" + const rows = await database.query(sql, [id]) + return rows[0] || null + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function createAdmin(username, hashedPassword) { + try { + const sql = "INSERT INTO api_administrators (username, password) VALUES (?, ?)" + const result = await database.query(sql, [username, hashedPassword]) + + if (result.affectedRows > 0) { + return { code: 200, id: result.insertId, username } + } else { + throw new DefaultError(500, "Failed to create administrator.") + } + } catch (error) { + if (error.code === "ER_DUP_ENTRY") { + throw new DefaultError(409, "Administrator username already exists.") + } + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function hasPermission(adminId, permissionKey) { + try { + const sql = ` + SELECT COUNT(*) as count + FROM api_administrators_permissions + WHERE administrator_id = ? AND permission_key = ? + ` + const rows = await database.query(sql, [adminId, permissionKey]) + return rows[0].count === 1 + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function assignPermission(adminId, permissionKey) { + try { + const sql = "INSERT INTO api_administrators_permissions (administrator_id, permission_key) VALUES (?, ?)" + const result = await database.query(sql, [adminId, permissionKey]) + + return result.affectedRows > 0 + } catch (error) { + if (error.code === "ER_DUP_ENTRY") return true + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function revokePermission(adminId, permissionKey) { + try { + const sql = "DELETE FROM api_administrators_permissions WHERE administrator_id = ? AND permission_key = ?" + const result = await database.query(sql, [adminId, permissionKey]) + + return result.affectedRows > 0 + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getAdminPermissions(adminId) { + try { + const sql = ` + SELECT permission_key + FROM api_administrators_permissions + WHERE administrator_id = ? + ` + const rows = await database.query(sql, [adminId]) + return rows.map(r => r.permission_key) + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function updateAdminPassword(adminId, newHashedPassword) { + try { + const sql = "UPDATE api_administrators SET password = ? WHERE id = ?" + const result = await database.query(sql, [newHashedPassword, adminId]) + + if (result.affectedRows > 0) { + return { + code: 200, + message: "Password updated successfully." + } + } else { + throw new DefaultError(404, "Administrator not found.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getAdminByUsername(username) { + try { + const sql = "SELECT id, username, password, createdAt FROM api_administrators WHERE username = ?" + const rows = await database.query(sql, [username]) + + return rows[0] || null + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +module.exports = { + createAdmin, + getAdminById, + hasPermission, + assignPermission, + revokePermission, + getAdminByUsername, + getAdminPermissions, + updateAdminPassword +} \ No newline at end of file diff --git a/repositories/authRepository.js b/repositories/authRepository.js new file mode 100644 index 0000000..5cd423a --- /dev/null +++ b/repositories/authRepository.js @@ -0,0 +1,208 @@ +const logger = require("../modules/logger") +const bcrypt = require("bcryptjs") +const database = require("../modules/database") +const { DefaultError } = require("../errors/errors") + +async function getUser(identifier, requirePassword = false) { + try { + const sql = `SELECT * FROM players WHERE uuid = ? OR email = ? OR username = ?` + const rows = await database.query(sql, [identifier, identifier, identifier]) + const user = rows[0] + if (!user) { + throw new DefaultError(404, "User not found") + } + + delete user.email + if (!requirePassword) { + delete user.password + } + return { code: 200, user } + + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function register(email, username, password) { + try { + const sql = `INSERT INTO players (email, username, password, uuid) VALUES (?, ?, ?, ?)` + const uuid = crypto.randomUUID() + const hashedPassword = await bcrypt.hash(password, 10) + const result = await database.query(sql, [email, username, hashedPassword, uuid]) + if (result.affectedRows > 0) { + return { code: 200, email, username, uuid } + } else { + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } + } catch (error) { + if (error instanceof DefaultError) throw error + + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + console.log(error) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function insertClientSession(accessToken, clientToken, uuid) { + try { + const sql = `INSERT INTO clientSessions (accessToken, clientToken, uuid) VALUES (?, ?, ?)` + const result = await database.query(sql, [accessToken, clientToken, uuid]) + + if (result.affectedRows > 0) { + return { code: 204, accessToken, clientToken } + } else { + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + } +} + +async function getPlayerProperties(uuid) { + try { + const sql = `SELECT * FROM playersProperties WHERE uuid = ?` + const properties = await database.query(sql, [uuid]) + + if (properties.length === 0) { + throw new DefaultError(404, "Properties not found for this user.", "InternalServerError") + } + return { code: 200, properties: properties.map(property => { return { name: property.name, value: property.value } }) } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getClientSession(accessToken, clientToken) { + try { + const sql = `SELECT * FROM clientSessions WHERE accessToken = ? AND clientToken = ?` + const rows = await database.query(sql, [accessToken, clientToken]) + + const session = rows[0] + if (session) { + return { + code: 200, + session: session + } + } else { + throw new DefaultError(404, "Client session not found") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function validateClientSession(accessToken, clientToken) { + try { + const sql = `SELECT * FROM clientSessions WHERE accessToken = ? AND clientToken = ?` + const rows = await database.query(sql, [accessToken, clientToken]) + + const session = rows[0] + if (session) { + return { + code: 200, + message: "Client session valid." + } + } else { + throw new DefaultError(404, "Client session not found for this accessToken/clientToken combination.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function validateClientSessionWithoutClientToken(accessToken) { + try { + const sql = `SELECT * FROM clientSessions WHERE accessToken = ?` + const rows = await database.query(sql, [accessToken]) + + const session = rows[0] + if (session) { + return { + code: 200, + message: "Client session valid." + } + } else { + throw new DefaultError(404, "Client session not found for this accessToken.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function invalidateClientSession(accessToken, clientToken) { + try { + const sql = `DELETE FROM clientSessions WHERE accessToken = ? AND clientToken = ?` + const result = await database.query(sql, [accessToken, clientToken]) + + if (result.affectedRows > 0) { + return { + code: 200, + message: "Client session successfully invalidated." + } + } else { + throw new DefaultError(404, "Client session not found for this accessToken/clientToken combination.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function revokeAccessTokens(uuid) { + try { + const sql = `DELETE FROM clientSessions WHERE uuid = ?` + const result = await database.query(sql, [uuid]) + + if (result.affectedRows > 0) { + return { + code: 200, + message: "Access tokens successfully revoked." + } + } else { + throw new DefaultError(404, "No access token found for this user.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getUsernamesRules() { + try { + const rows = await database.query("SELECT rule, type FROM usernameRules") + return rows.map(row => { + if (row.type === 1) { + return { type: "regex", pattern: new RegExp(row.rule, "i") } + } else { + return { type: "literal", value: row.rule.toLowerCase() } + } + }) + } catch (err) { + throw err + } +} + +module.exports = { + getUser, + register, + getClientSession, + getUsernamesRules, + revokeAccessTokens, + insertClientSession, + getPlayerProperties, + validateClientSession, + invalidateClientSession, + validateClientSessionWithoutClientToken +} \ No newline at end of file diff --git a/repositories/sessionsRepository.js b/repositories/sessionsRepository.js new file mode 100644 index 0000000..6961bed --- /dev/null +++ b/repositories/sessionsRepository.js @@ -0,0 +1,174 @@ +const logger = require("../modules/logger") +const database = require("../modules/database") +const { DefaultError } = require("../errors/errors") + +async function insertLegacyClientSessions(sessionId, uuid) { + try { + await database.query(`DELETE FROM legacyClientSessions WHERE uuid = ?`, [uuid]) + + const sql = `INSERT INTO legacyClientSessions (sessionId, uuid) VALUES (?, ?)` + const result = await database.query(sql, [sessionId, uuid]) + + if (result.affectedRows > 0) { + return { code: 200, sessionId, uuid } + } else { + throw new DefaultError(500, "Internal Server Error", "Unknown DB Error") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function validateLegacyClientSession(sessionId, uuid) { + try { + const sql = `SELECT * FROM legacyClientSessions WHERE sessionId = ? AND uuid = ?` + const rows = await database.query(sql, [sessionId, uuid]) + + const session = rows[0] + if (session) { + return { + code: 200, + message: "Client session valid." + } + } else { + return { + code: 404, + message: "Client session not found for this accessToken/clientToken combination" + } + } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function getBlockedServers() { + try { + const sql = `SELECT * FROM blockedServers` + const blockedServers = await database.query(sql) + + return { + code: 200, + blockedServers: blockedServers.map(bannedServer => ({ sha1: bannedServer.hashedIp })) + } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function getActiveSkin(uuid) { + try { + const sql = ` + SELECT t.url, ps.variant + FROM playersSkins ps + JOIN textures t ON ps.assetHash = t.hash + WHERE ps.playerUuid = ? AND ps.isSelected = 1 + ` + const rows = await database.query(sql, [uuid]) + const skin = rows[0] + if (!skin) { + throw new DefaultError(404, "Not found", "Not found") + } + return { code: 200, data: skin || null } + } catch (error) { + if (error instanceof DefaultError) { + throw error + } + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function getActiveCape(uuid) { + try { + const sql = ` + SELECT t.url + FROM playersCapes pc + JOIN textures t ON pc.assetHash = t.hash + WHERE pc.playerUuid = ? AND pc.isSelected = 1 + ` + const rows = await database.query(sql, [uuid]) + const cape = rows[0] + if (!cape) { + throw new DefaultError(404, "Not found", "Not found") + } + return { code: 200, data: cape || null } + } catch (error) { + if (error instanceof DefaultError) { + throw error + } + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function getProfileActionsList(uuid) { + try { + const cleanUuid = uuid.replace(/-/g, "") + const sql = "SELECT action FROM playerProfileActions WHERE uuid = ?" + const rows = await database.query(sql, [cleanUuid]) + + const actions = rows.map(row => row.action) + + return { code: 200, data: actions } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function saveServerSession(uuid, accessToken, serverId, ip) { + try { + const sql = ` + INSERT INTO serverSessions (uuid, accessToken, serverId, ip, createdAt) + VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) + ON DUPLICATE KEY UPDATE + accessToken = VALUES(accessToken), + serverId = VALUES(serverId), + ip = VALUES(ip), + createdAt = CURRENT_TIMESTAMP + ` + const result = await database.query(sql, [uuid, accessToken, serverId, ip]) + + return { code: 200, success: result.affectedRows > 0 } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +async function getServerSession(uuid, serverId) { + try { + const sql = ` + SELECT ip + FROM serverSessions + WHERE uuid = ? AND serverId = ? + AND createdAt > (NOW() - INTERVAL 30 SECOND) + ` + const rows = await database.query(sql, [uuid, serverId]) + const session = rows[0] + + if (!session) { + return { code: 404, valid: false } + } + + return { code: 200, valid: true, ip: session.ip } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Please contact an administrator.") + } +} + +module.exports = { + insertLegacyClientSessions, + validateLegacyClientSession, + getBlockedServers, + getActiveSkin, + getActiveCape, + getProfileActionsList, + saveServerSession, + getServerSession +} \ No newline at end of file diff --git a/repositories/userRepository.js b/repositories/userRepository.js new file mode 100644 index 0000000..e6917eb --- /dev/null +++ b/repositories/userRepository.js @@ -0,0 +1,774 @@ +const crypto = require("node:crypto") +const logger = require("../modules/logger") +const database = require("../modules/database") +const { DefaultError } = require("../errors/errors") + +async function addPropertyToPlayer(key, value, uuid) { + try { + const sql = ` + INSERT INTO playersProperties (name, value, uuid) + VALUES (?, ?, ?) + ON DUPLICATE KEY UPDATE value = VALUES(value) + ` + const result = await database.query(sql, [key, value, uuid]) + + if (result.affectedRows > 0) { + return { code: 200, key, value, uuid } + } else { + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function deletePropertyToPlayer(key, uuid) { + try { + const sql = `DELETE FROM playersProperties WHERE name = ? AND uuid = ?` + const result = await database.query(sql, [key, uuid]) + + if (result.affectedRows > 0) { + return { code: 200, key, uuid } + } else { + throw new DefaultError(500, "Property not found for this user/key combination.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function updatePropertyToPlayer(key, value, uuid) { + try { + const sql = `UPDATE playersProperties SET value = ? WHERE name = ? AND uuid = ?` + const result = await database.query(sql, [value, key, uuid]) + if (result.affectedRows > 0) { + return { code: 200, key, value, uuid } + } else { + throw new DefaultError(404, "Property not found for this user/key combination") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getPlayerProperties(uuid) { + try { + const sql = `SELECT * FROM playersProperties WHERE uuid = ?` + const rows = await database.query(sql, [uuid]) + if (rows.length === 0) { + throw new DefaultError(404, "Properties not found for this user") + } + return { + code: 200, + properties: rows.map(property => ({ name: property.name, value: property.value })) + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getPlayerProperty(key, uuid) { + try { + const sql = `SELECT * FROM playersProperties WHERE name = ? AND uuid = ?` + const rows = await database.query(sql, [key, uuid]) + const property = rows[0] + if (!property) { + throw new DefaultError(404, "Property not found for this user/key combination") + } + return { code: 200, property } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getPlayerSettingsSchema() { + const RAW_SCHEMA_CACHE = { + privileges: {}, + preferences: {} + } + try { + const privilegesRows = await database.query("DESCRIBE playersPrivileges") + const preferencesRows = await database.query("DESCRIBE playersPreferences") + RAW_SCHEMA_CACHE.privileges = privilegesRows.map(c => c.Field).filter(n => n !== "uuid") + RAW_SCHEMA_CACHE.preferences = preferencesRows.map(c => c.Field).filter(n => n !== "uuid") + return RAW_SCHEMA_CACHE + } catch (err) { + logger.log("Database Schema Error: " + err.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Schema Error") + } +} + +async function updatePlayerPreferences(uuid, updates) { + try { + const keys = Object.keys(updates) + if (keys.length === 0) { + throw new DefaultError(400, "No fields provided for update.") + } + const setClause = keys.map(key => `\`${key}\` = ?`).join(', ') + const sql = `UPDATE playersPreferences SET ${setClause} WHERE uuid = ?` + const values = keys.map(key => updates[key]) + values.push(uuid) + const result = await database.query(sql, values) + if (result.affectedRows > 0) { + return { + code: 200, + message: "Preferences updated successfully." + } + } else { + throw new DefaultError(404, "Player preferences not found or no changes made.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getPlayerPreferences(uuid) { + try { + const sql = `SELECT profanityFilter FROM playersPreferences WHERE uuid = ?` + const rows = await database.query(sql, [uuid]) + const data = rows[0] + + if (data) { + return { + code: 200, + message: "Preferences retrieved successfully.", + data: data + } + } else { + throw new DefaultError(404, "Preferences not found for this UUID.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getPlayerPrivileges(uuid) { + try { + const sql = ` + SELECT onlineChat, multiplayerServer, multiplayerRealms, telemetry + FROM playersPrivileges + WHERE uuid = ? + ` + const rows = await database.query(sql, [uuid]) + const data = rows[0] + if (data) { + return { + code: 200, + message: "Privileges retrieved successfully.", + data: data + } + } else { + throw new DefaultError(404, "Privileges not found for this UUID.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function updatePlayerPrivileges(uuid, updates) { + try { + const keys = Object.keys(updates) + if (keys.length === 0) { + throw new DefaultError(404, "No fields provided for update.") + } + const setClause = keys.map(key => `\`${key}\` = ?`).join(', ') + const sql = `UPDATE playersPrivileges SET ${setClause} WHERE uuid = ?` + const values = keys.map(key => updates[key]) + values.push(uuid) + const result = await database.query(sql, values) + if (result.affectedRows > 0) { + return { + code: 200, + message: "Privileges updated successfully." + } + } else { + throw new DefaultError(404, "Player privileges not found or no changes made.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function banUser(uuid, { reasonKey, reasonMessage, expires = null }) { + try { + if (!uuid || !reasonKey) { + throw new DefaultError(400, "Missing uuid or reasonKey.") + } + + let reasonId + const reasonRows = await database.query("SELECT id FROM banReasons WHERE reason_key = ?", [reasonKey]) + if (reasonRows.length > 0) { + reasonId = reasonRows[0].id + } else { + const insertReason = await database.query("INSERT INTO banReasons (reason_key) VALUES (?)", [reasonKey]) + reasonId = insertReason.insertId + } + + const banId = crypto.randomUUID() + const insertSql = ` + INSERT INTO bans (banId, uuid, reason, reasonMessage, expires) + VALUES (?, ?, ?, ?, ?) + ` + const result = await database.query(insertSql, [banId, uuid, reasonId, reasonMessage || "Banned by operator", expires]) + + if (result.affectedRows > 0) { + return { + code: 200, + message: "User successfully banned.", + banId: banId + } + } else { + throw new DefaultError(500, "Failed to ban user.") + } + + } catch (error) { + if (error instanceof DefaultError) throw error + if (error.code === "ER_NO_REFERENCED_ROW_2" || error.toString().includes("foreign key constraint")) { + throw new DefaultError(404, "User not found (cannot ban a ghost).") + } + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", error.toString()) + } +} + +async function unbanUser(uuid) { + try { + if (!uuid) { + throw new DefaultError(400, "Missing uuid.") + } + const sql = "DELETE FROM bans WHERE uuid = ?" + const result = await database.query(sql, [uuid]) + if (result.affectedRows > 0) { + return { + code: 200, + message: "User successfully unbanned.", + count: result.affectedRows + } + } else { + throw new DefaultError(404, "User was not banned.") + } + + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function getPlayerBans(uuid) { + try { + const sql = ` + SELECT + b.banId, + b.expires, + b.reasonMessage, + r.reason_key as reason + FROM bans b + JOIN banReasons r ON b.reason = r.id + WHERE b.uuid = ? + ORDER BY b.expires ASC + ` + const rows = await database.query(sql, [uuid]) + + if (rows.length > 0) { + return { code: 200, bans: rows } + } else { + return { code: 204 } + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Please contact an administrator.", "InternalServerError") + } +} + +async function changeUsername(uuid, newName) { + try { + const sql = "UPDATE players SET username = ? WHERE uuid = ?" + const result = await database.query(sql, [newName, uuid]) + if (result.affectedRows > 0) { + return { code: 200, message: "Username changed successfully" } + } else { + throw new DefaultError(404, "User not found") + } + } catch (error) { + if (error instanceof DefaultError) throw error + if (error.code === "ER_DUP_ENTRY" || error.errno === 1062) { + throw new DefaultError(409, "Username already taken", "ForbiddenOperationException") + } + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", error.toString()) + } +} + +async function createTexture(uuid, hash, type, url, alias) { + try { + const sql = ` + INSERT INTO textures (uuid, hash, type, url, alias) + VALUES (?, ?, ?, ?, ?) + ` + await database.query(sql, [uuid, hash, type, url, alias]) + return true + } catch (error) { + if (error.code === 'ER_DUP_ENTRY') { + return false + } + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + + +async function getTextureByUuid(textureUuid) { + try { + const sql = "SELECT hash FROM textures WHERE uuid = ?" + const rows = await database.query(sql, [textureUuid]) + return rows[0] || null + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getTextureByHash(hash) { + try { + const sql = "SELECT uuid FROM textures WHERE hash = ?" + const rows = await database.query(sql, [hash]) + return rows[0] + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function resetSkin(uuid, hash, variant) { + try { + const insertSql = ` + INSERT IGNORE INTO playersSkins (playerUuid, assetHash, variant, isSelected) + VALUES (?, ?, ?, 0) + ` + await database.query(insertSql, [uuid, hash, variant]) + const updateSql = ` + UPDATE playersSkins + SET isSelected = (assetHash = ?) + WHERE playerUuid = ? + ` + await database.query(updateSql, [hash, uuid]) + return { code: 200 } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function hideCape(uuid) { + try { + const sql = "UPDATE playersCapes SET isSelected = 0 WHERE playerUuid = ?" + await database.query(sql, [uuid]) + return { code: 200 } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function showCape(uuid, hash) { + try { + const sql = ` + UPDATE playersCapes + SET isSelected = (assetHash = ?) + WHERE playerUuid = ? + ` + const result = await database.query(sql, [hash, uuid]) + return { code: 200, changed: result.affectedRows > 0 } + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function checkCapeOwnership(uuid, hash) { + try { + const sql = "SELECT 1 FROM playersCapes WHERE playerUuid = ? AND assetHash = ?" + const rows = await database.query(sql, [uuid, hash]) + return rows.length > 0 + } catch (error) { + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getPlayerMeta(uuid) { + try { + const sql = `SELECT createdAt, nameChangeAllowed FROM players WHERE uuid = ?` + const rows = await database.query(sql, [uuid]) + return rows[0] + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getLastNameChange(uuid) { + try { + const sql = ` + SELECT changedAt + FROM uuidToNameHistory + WHERE uuid = ? AND changedAt IS NOT NULL + ORDER BY changedAt DESC + LIMIT 1 + ` + const rows = await database.query(sql, [uuid]) + return rows[0] + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getPlayerCertificate(uuid) { + try { + const sql = "SELECT * FROM playerCertificates WHERE uuid = ?" + const rows = await database.query(sql, [uuid]) + return rows[0] + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function savePlayerCertificate(uuid, privateKey, publicKey, signatureV2, expiresAt, refreshedAfter) { + try { + const sql = ` + REPLACE INTO playerCertificates + (uuid, privateKey, publicKey, publicKeySignatureV2, expiresAt, refreshedAfter) + VALUES (?, ?, ?, ?, ?, ?) + ` + const result = await database.query(sql, [uuid, privateKey, publicKey, signatureV2, expiresAt, refreshedAfter]) + return result.affectedRows > 0 + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function deleteExpiredCertificates(isoDate) { + try { + const sql = "DELETE FROM playerCertificates WHERE expiresAt < ?" + const result = await database.query(sql, [isoDate]) + return result.affectedRows + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function addProfileAction(uuid, actionCode) { + try { + const cleanUuid = uuid.replace(/-/g, "") + const sql = "INSERT IGNORE INTO playerProfileActions (uuid, action) VALUES (?, ?)" + const result = await database.query(sql, [cleanUuid, actionCode]) + return result.affectedRows > 0 + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function removeProfileAction(uuid, actionCode) { + try { + const cleanUuid = uuid.replace(/-/g, "") + const sql = "DELETE FROM playerProfileActions WHERE uuid = ? AND action = ?" + const result = await database.query(sql, [cleanUuid, actionCode]) + return result.affectedRows + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getPlayerActions(uuid) { + try { + const cleanUuid = uuid.replace(/-/g, "") + const sql = "SELECT action FROM playerProfileActions WHERE uuid = ?" + const rows = await database.query(sql, [cleanUuid]) + return rows.map(r => r.action) + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function clearAllPlayerActions(uuid) { + try { + const cleanUuid = uuid.replace(/-/g, "") + const sql = "DELETE FROM playerProfileActions WHERE uuid = ?" + const result = await database.query(sql, [cleanUuid]) + return result.affectedRows + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function blockPlayer(blockerUuid, blockedUuid) { + try { + const sql = `INSERT IGNORE INTO playersBlockslist (blockerUuid, blockedUuid) VALUES (?, ?)` + const result = await database.query(sql, [blockerUuid, blockedUuid]) + return result.affectedRows > 0 + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function unblockPlayer(blockerUuid, blockedUuid) { + try { + const sql = `DELETE FROM playersBlockslist WHERE blockerUuid = ? AND blockedUuid = ?` + const result = await database.query(sql, [blockerUuid, blockedUuid]) + return result.affectedRows > 0 + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getBlockedUuids(blockerUuid) { + try { + const sql = `SELECT blockedUuid FROM playersBlockslist WHERE blockerUuid = ?` + const rows = await database.query(sql, [blockerUuid]) + return rows.map(r => r.blockedUuid) + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function isBlocked(blockerUuid, targetUuid) { + try { + const sql = `SELECT 1 FROM playersBlockslist WHERE blockerUuid = ? AND blockedUuid = ? LIMIT 1` + const rows = await database.query(sql, [blockerUuid, targetUuid]) + return rows.length > 0 + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getUsersByNames(usernames) { + try { + if (!usernames || usernames.length === 0) return [] + const uniqueNames = [...new Set(usernames)] + + const placeholders = uniqueNames.map(() => "?").join(", ") + const sql = `SELECT uuid, username FROM players WHERE username IN (${placeholders})` + + const rows = await database.query(sql, uniqueNames) + return rows + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getUuidAndUsername(username) { + try { + const sql = "SELECT uuid, username FROM players WHERE username = ?" + const rows = await database.query(sql, [username]) + + return rows[0] || null + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getProfileByUsername(username) { + try { + const sql = "SELECT uuid, username FROM players WHERE username = ?" + const rows = await database.query(sql, [username]) + return rows[0] || null + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getProfileByHistory(username, isoDate) { + try { + const sql = ` + SELECT uuid, username + FROM uuidToNameHistory + WHERE username = ? + AND (changedAt <= ? OR changedAt IS NULL) + ORDER BY changedAt DESC + LIMIT 1 + ` + const rows = await database.query(sql, [username, isoDate]) + return rows[0] || null + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function getNameHistory(uuid) { + try { + const sql = ` + SELECT username, changedAt + FROM uuidToNameHistory + WHERE uuid = ? + ORDER BY changedAt ASC + ` + const rows = await database.query(sql, [uuid]) + return rows + } catch (error) { + logger.log("Database Error: " + error.toString(), ["MariaDB", "red"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function setSkin(uuid, hash, variant) { + const insertSql = ` + INSERT INTO playersSkins (playerUuid, assetHash, variant, isSelected) + VALUES (?, ?, ?, 1) + ON DUPLICATE KEY UPDATE isSelected = 1, variant = ? + ` + await database.query(insertSql, [uuid, hash, variant, variant]) + const updateSql = ` + UPDATE playersSkins + SET isSelected = 0 + WHERE playerUuid = ? AND assetHash != ? + ` + await database.query(updateSql, [uuid, hash]) + return true +} + +async function updatePassword(uuid, hashedPassword) { + try { + const sql = "UPDATE players SET password = ? WHERE uuid = ?" + const result = await database.query(sql, [hashedPassword, uuid]) + + if (result.affectedRows > 0) { + return { code: 200, message: "Password updated successfully" } + } else { + throw new DefaultError(404, "User not found") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function addCapeToPlayer(uuid, hash) { + try { + const sql = ` + INSERT INTO playersCapes (playerUuid, assetHash, isSelected) + VALUES (?, ?, 0) + ` + const result = await database.query(sql, [uuid, hash]) + + if (result.affectedRows > 0) { + return { code: 200, message: "Cape accordée au joueur." } + } + throw new DefaultError(500, "Erreur lors de l'attribution de la cape.") + } catch (error) { + if (error.code === 'ER_DUP_ENTRY') { + throw new DefaultError(409, "Le joueur possède déjà cette cape.") + } + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function removeCapeFromPlayer(uuid, hash) { + try { + const sql = "DELETE FROM playersCapes WHERE playerUuid = ? AND assetHash = ?" + const result = await database.query(sql, [uuid, hash]) + + if (result.affectedRows > 0) { + return { code: 200, message: "Cape retirée du joueur." } + } else { + throw new DefaultError(404, "Le joueur ne possède pas cette cape.") + } + } catch (error) { + if (error instanceof DefaultError) throw error + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +async function deleteTexture(hash) { + try { + const sql = "DELETE FROM textures WHERE hash = ?" + const result = await database.query(sql, [hash]) + return result.affectedRows > 0 + } catch (error) { + logger.log("Internal Server Error".bold + " : " + error.toString(), ["MariaDB", "yellow"]) + throw new DefaultError(500, "Internal Server Error", "Database Error") + } +} + +module.exports = { + setSkin, + banUser, + showCape, + hideCape, + resetSkin, + isBlocked, + unbanUser, + blockPlayer, + deleteTexture, + createTexture, + getPlayerBans, + getPlayerMeta, + unblockPlayer, + changeUsername, + getNameHistory, + updatePassword, + getBlockedUuids, + getUsersByNames, + addCapeToPlayer, + getPlayerActions, + getTextureByUuid, + getTextureByHash, + addProfileAction, + getLastNameChange, + getPlayerProperty, + getUuidAndUsername, + checkCapeOwnership, + getProfileByHistory, + getPlayerPrivileges, + getPlayerProperties, + removeProfileAction, + addPropertyToPlayer, + removeCapeFromPlayer, + getProfileByUsername, + getPlayerPreferences, + getPlayerCertificate, + clearAllPlayerActions, + savePlayerCertificate, + updatePlayerPrivileges, + deletePropertyToPlayer, + updatePropertyToPlayer, + getPlayerSettingsSchema, + updatePlayerPreferences, + deleteExpiredCertificates, +} \ No newline at end of file diff --git a/routes/admin/ban/index.js b/routes/admin/ban/index.js new file mode 100644 index 0000000..7ffaa39 --- /dev/null +++ b/routes/admin/ban/index.js @@ -0,0 +1,32 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../services/userService") +const adminService = require("../../../services/adminService") + +router.get("/:uuid", adminService.hasPermission("PLAYER_BAN_STATUS"), async (req, res) => { + const banStatus = await userService.getPlayerBanStatus(req.params.uuid) + return res.status(200).json(banStatus) +}) + +router.get("/:uuid/actions", adminService.hasPermission("PLAYER_ACTIONS_LIST"), async (req, res) => { + const playerActions = await userService.getPlayerActions(req.params.uuid) + return res.status(200).json(playerActions) +}) + +router.get("/:uuid/history", adminService.hasPermission("PLAYER_BAN_HISTORY"), async (req, res) => { + const banHistory = await userService.getPlayerBans(req.params.uuid) + return res.status(200).json(banHistory) +}) + +router.put("/:uuid", adminService.hasPermission("PLAYER_BAN"), async (req, res) => { + const { reasonKey, reasonMessage, expires } = req.body + const ban = await userService.banUser(req.params.uuid, { reasonKey, reasonMessage, expires }) + return res.status(200).json(ban) +}) + +router.delete("/:uuid", adminService.hasPermission("PLAYER_UNBAN"), async (req, res) => { + const ban = await userService.unbanUser(req.params.uuid) + return res.status(200).json(ban) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/admin/cosmetics/capes.js b/routes/admin/cosmetics/capes.js new file mode 100644 index 0000000..4d75e51 --- /dev/null +++ b/routes/admin/cosmetics/capes.js @@ -0,0 +1,20 @@ +const express = require("express") +const path = require("node:path") +const multer = require("multer") +const router = express.Router() +const userService = require("../../../services/userService") +const adminService = require("../../../services/adminService") + +const upload = multer({ dest: path.join(process.cwd(), "data/temp/") }) + +router.post("/upload", adminService.hasPermission("UPLOAD_CAPE"), upload.single("file"), async (req, res) => { + const result = await adminService.uploadCape(req.file, req.body.alias) + res.status(201).json(result) +}) + +router.delete("/:hash", adminService.hasPermission("DELETE_CAPES"), async (req, res) => { + const result = await userService.deleteGlobalCape(req.params.hash) + res.status(200).json(result) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/admin/index.js b/routes/admin/index.js new file mode 100644 index 0000000..4c2ef61 --- /dev/null +++ b/routes/admin/index.js @@ -0,0 +1,4 @@ +const express = require("express") +const router = express.Router() + +module.exports = router \ No newline at end of file diff --git a/routes/admin/players/password.js b/routes/admin/players/password.js new file mode 100644 index 0000000..6188685 --- /dev/null +++ b/routes/admin/players/password.js @@ -0,0 +1,12 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../services/userService") +const adminService = require("../../../services/adminService") + +router.patch("/:uuid", adminService.hasPermission("CHANGE_PLAYER_PASSWORD"), async (req, res) => { + const { newPassword } = req.body + const result = await userService.changePassword(req.params.uuid, newPassword) + return res.status(200).json(result) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/admin/players/textures.js b/routes/admin/players/textures.js new file mode 100644 index 0000000..cb2e926 --- /dev/null +++ b/routes/admin/players/textures.js @@ -0,0 +1,23 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../services/userService") +const adminService = require("../../../services/adminService") + +router.delete("/skin/:uuid", adminService.hasPermission("RESET_PLAYER_SKIN"), async (req, res) => { + const result = await userService.resetSkin(req.params.uuid) + return res.status(200).json(result) +}) + +router.put("/cape/:uuid/:hash", adminService.hasPermission("GRANT_PLAYER_CAPE"), async (req, res) => { + const { uuid, hash } = req.params + const result = await userService.grantCape(uuid, hash) + return res.status(200).json(result) +}) + +router.delete("/cape/:uuid/:hash", adminService.hasPermission("REMOVE_PLAYER_CAPE"), async (req, res) => { + const { uuid, hash } = req.params + const result = await userService.removeCape(uuid, hash) + return res.status(200).json(result) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/admin/players/username.js b/routes/admin/players/username.js new file mode 100644 index 0000000..809ed26 --- /dev/null +++ b/routes/admin/players/username.js @@ -0,0 +1,12 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../services/userService") +const adminService = require("../../../services/adminService") + +router.patch("/:uuid", adminService.hasPermission("CHANGE_PLAYER_USERNAME"), async (req, res) => { + const { newUsername } = req.body + const result = await userService.changeUsername(req.params.uuid, newUsername) + return res.status(200).json(result) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/api/minecraft/profile/lookup/bulk/byname.js b/routes/api/minecraft/profile/lookup/bulk/byname.js new file mode 100644 index 0000000..b194acd --- /dev/null +++ b/routes/api/minecraft/profile/lookup/bulk/byname.js @@ -0,0 +1,10 @@ +const express = require("express") +const userService = require("../../../../../../services/userService") +const router = express.Router() + +router.post("/", async (req, res) => { + const profiles = await userService.bulkLookup(req.body) + return res.status(200).json(profiles) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/api/profile/lookup/name/[username].js b/routes/api/profile/lookup/name/[username].js new file mode 100644 index 0000000..50f8c41 --- /dev/null +++ b/routes/api/profile/lookup/name/[username].js @@ -0,0 +1,28 @@ +const express = require("express") +const utils = require("../../../../../modules/utils") +const userService = require("../../../../../services/userService") +const authService = require("../../../../../services/authService") +const { ServiceError } = require("../../../../../errors/errors") +const router = express.Router({ mergeParams: true }) + + +router.get("", async (req, res) => { + const profile = await userService.getLegacyProfile(req.params.username) + const isUsernameOK = await authService.checkUsernameAvailability(newName) + const at = req.query.at + if (at != undefined && utils.isTrueFromDotEnv("SUPPORT_UUID_TO_NAME_HISTORY")) { + const history = await userService.getNameUUIDs(parseInt(at)) + return res.status(history.code).json(history.data) + } else { + throw new ServiceError(400, req.originalUrl, "IllegalArgumentException", "Invalid timestamp.") + } + if (isUsernameOK.status != "AVAILABLE") { + throw new ServiceError(400, req.originalUrl, "CONSTRAINT_VIOLATION", "Invalid username.") + } + if (!profile) { + return res.status(204).send() + } + return res.status(200).json(profile) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/api/profiles/minecraft.js b/routes/api/profiles/minecraft.js new file mode 100644 index 0000000..971fece --- /dev/null +++ b/routes/api/profiles/minecraft.js @@ -0,0 +1,10 @@ +const express = require("express") +const userService = require("../../../services/userService") +const router = express.Router() + +router.post("/", async (req, res) => { + const profiles = await userService.bulkLookup(req.body) + return res.status(200).json(profiles) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/api/user/profiles/[uuid]/names.js b/routes/api/user/profiles/[uuid]/names.js new file mode 100644 index 0000000..6dd32c0 --- /dev/null +++ b/routes/api/user/profiles/[uuid]/names.js @@ -0,0 +1,15 @@ +const express = require("express") +const utils = require("../../../../../modules/utils") +const userService = require("../../../../../services/userService") +const { ServiceError } = require("../../../../../errors/errors") +const router = express.Router({ mergeParams: true }) + +router.get("/", async (req, res) => { + if (!utils.isTrueFromDotEnv("SUPPORT_UUID_TO_NAME_HISTORY")) { + throw new ServiceError(404, req.originalUrl, "Not found", null, null) + } + const history = await userService.getPlayerUsernamesHistory(req.params.uuid) + return res.status(200).json(history) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/api/users/profiles/minecraft/[username].js b/routes/api/users/profiles/minecraft/[username].js new file mode 100644 index 0000000..fa38356 --- /dev/null +++ b/routes/api/users/profiles/minecraft/[username].js @@ -0,0 +1,27 @@ +const express = require("express") +const utils = require("../../../../../modules/utils") +const userService = require("../../../../../services/userService") +const authService = require("../../../../../services/authService") +const { ServiceError } = require("../../../../../errors/errors") +const router = express.Router({ mergeParams: true }) + +router.get("", async (req, res) => { + const profile = await userService.getLegacyProfile(req.params.username) + const isUsernameOK = await authService.checkUsernameAvailability(newName) + const at = req.query.at + if (at != undefined && utils.isTrueFromDotEnv("SUPPORT_UUID_TO_NAME_HISTORY")) { + const history = await userService.getNameUUIDs(parseInt(at)) + return res.status(history.code).json(history.data) + } else { + throw new ServiceError(400, req.originalUrl, "IllegalArgumentException", "Invalid timestamp.") + } + if (isUsernameOK.status != "AVAILABLE") { + throw new ServiceError(400, req.originalUrl, "CONSTRAINT_VIOLATION", "Invalid username.") + } + if (!profile) { + return res.status(204).send() + } + return res.status(200).json(profile) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/authserver/authenticate.js b/routes/authserver/authenticate.js new file mode 100644 index 0000000..56ee8ed --- /dev/null +++ b/routes/authserver/authenticate.js @@ -0,0 +1,41 @@ +const express = require("express") +const router = express.Router() +const { YggdrasilError } = require("../../errors/errors") +const rateLimit = require("express-rate-limit") +const authService = require("../../services/authService") +const logger = require("../../modules/logger") + +const limiter = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 20, + standardHeaders: true, + legacyHeaders: false, + handler: (req, res) => { + return res.status(429).json({ + error: "TooManyRequestsException", + errorMessage: "Too many login attempts, please try again later." + }) + } +}) + +router.post("/", limiter, async (req, res) => { + const { username, password, clientToken, requestUser } = req.body + try { + const result = await authService.authenticate({ + identifier: username, + password, + clientToken, + requireUser: requestUser || false + }) + + logger.log(`User authenticated: ${username}`, ["AUTH", "green"]) + return res.status(200).json(result.response) + } catch (err) { + if (err instanceof DefaultError) { + throw new YggdrasilError( err.code, err.error || "ForbiddenOperationException", err.message, "Invalid credentials") + } + throw err + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/authserver/invalidate.js b/routes/authserver/invalidate.js new file mode 100644 index 0000000..d6db19a --- /dev/null +++ b/routes/authserver/invalidate.js @@ -0,0 +1,20 @@ +const express = require("express") +const router = express.Router() +const authService = require("../../services/authService") +const YggdrasilError = require("../../errors/YggdrasilError") +const { DefaultError } = require("../../errors/errors") + +router.post("/", async (req, res) => { + const { accessToken, clientToken } = req.body + try { + await authService.invalidate({ accessToken, clientToken }) + return res.sendStatus(204) + } catch (err) { + if (err instanceof DefaultError) { + throw new YggdrasilError(err.code, err.error || "ForbiddenOperationException", err.message, "Invalid token.") + } + throw err + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/authserver/refresh.js b/routes/authserver/refresh.js new file mode 100644 index 0000000..7b234dc --- /dev/null +++ b/routes/authserver/refresh.js @@ -0,0 +1,28 @@ +const express = require("express") +const router = express.Router() +const authService = require("../../services/authService") +const logger = require("../../modules/logger") +const { DefaultError, YggdrasilError } = require("../../errors/errors") + +router.post("/", async (req, res) => { + const { accessToken, clientToken, requestUser } = req.body + + try { + const result = await authService.refreshToken({ + clientToken, + previousAccessToken: accessToken, + requireUser: requestUser || false + }) + + const profileName = result.response.selectedProfile ? result.response.selectedProfile.name : "Unknown" + logger.log(`Session refreshed for: ${profileName}`, ["AUTH", "green"]) + return res.status(200).json(result.response) + } catch (err) { + if (err instanceof DefaultError) { + throw new YggdrasilError(err.code, err.error || "ForbiddenOperationException", err.message, "Invalid token.") + } + throw err + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/authserver/signout.js b/routes/authserver/signout.js new file mode 100644 index 0000000..80c9090 --- /dev/null +++ b/routes/authserver/signout.js @@ -0,0 +1,29 @@ +const express = require("express") +const router = express.Router() +const authService = require("../../services/authService") +const logger = require("../../modules/logger") +const { DefaultError, YggdrasilError } = require("../../errors/errors") + +router.post("/", async (req, res) => { + const { username, password } = req.body + try { + const authResult = await authService.authenticate({ + identifier: username, + password, + requireUser: false + }) + + const userUuid = authResult.response.selectedProfile.id + await authService.signout({ uuid: userUuid }) + + logger.log(`User signed out globally: ${username}`, ["AUTH", "green"]) + return res.sendStatus(204) + } catch (err) { + if (err instanceof DefaultError) { + throw new YggdrasilError(err.code === 403 ? 403 : 500, err.error || "ForbiddenOperationException", err.message || "Invalid credentials.", "Invalid credentials.") + } + throw err + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/authserver/validate.js b/routes/authserver/validate.js new file mode 100644 index 0000000..db6e72c --- /dev/null +++ b/routes/authserver/validate.js @@ -0,0 +1,20 @@ +const express = require("express") +const router = express.Router() +const authService = require("../../services/authService") +const YggdrasilError = require("../../errors/YggdrasilError") +const { DefaultError } = require("../../errors/errors") + +router.post("/", async (req, res) => { + const { accessToken, clientToken } = req.body + try { + await authService.validate({ accessToken, clientToken }) + return res.sendStatus(204) + } catch (err) { + if (err instanceof DefaultError) { + throw new YggdrasilError(err.code, err.error || "ForbiddenOperationException", err.message, "Invalid token.") + } + throw err + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/index.js b/routes/index.js new file mode 100644 index 0000000..34db0fb --- /dev/null +++ b/routes/index.js @@ -0,0 +1,17 @@ +const express = require("express") +const router = express.Router() +const utils = require("../modules/utils") +const serverService = require("../services/serverService") + +if (utils.isTrueFromDotEnv("SUPPORT_AUTHLIB_INJECTOR")) { + router.get("/", (req, res) => { + const hostname = req.hostname + const metadata = serverService.getServerMetadata(hostname) + res.header("X-Authlib-Injector-Date", new Date().toISOString()) + return res.status(200).json(metadata) + }) +} else { + router.get("/", (req, res, next) => next()) +} + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/MinecraftCloaks/[username].js b/routes/legacy/MinecraftCloaks/[username].js new file mode 100644 index 0000000..6f426a9 --- /dev/null +++ b/routes/legacy/MinecraftCloaks/[username].js @@ -0,0 +1,10 @@ +const express = require("express") +const router = express.Router({ mergeParams: true }) +const sessionsService = require("../../../services/sessionsService") + +router.get("", async (req, res) => { + const cape = await sessionsService.getActiveCape({ username: req.params.username.replace(".png", "") }) + return res.redirect(`/textures${cape.data.url}`) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/MinecraftSkins/[username].js b/routes/legacy/MinecraftSkins/[username].js new file mode 100644 index 0000000..b2aa20b --- /dev/null +++ b/routes/legacy/MinecraftSkins/[username].js @@ -0,0 +1,10 @@ +const express = require("express") +const router = express.Router({ mergeParams: true }) +const sessionsService = require("../../../services/sessionsService") + +router.get("", async (req, res) => { + const cape = await sessionsService.getActiveSkin({ username: req.params.username.replace(".png", "") }) + return res.redirect(`/textures${cape.data.url}`) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/checkserver.js b/routes/legacy/checkserver.js new file mode 100644 index 0000000..40ad74d --- /dev/null +++ b/routes/legacy/checkserver.js @@ -0,0 +1,24 @@ +const express = require("express") +const router = express.Router() +const sessionsService = require("../../services/sessionsService") + +router.get("/", async (req, res) => { + const { user, serverId } = req.query + try { + const result = await sessionsService.hasJoinedServer({ + username: user, + serverId, + ip: null + }) + + if (result.code === 200) { + return res.send("YES") + } else { + return res.send("NO") + } + } catch (err) { + return res.send("NO") + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/cloaks/[username].js b/routes/legacy/cloaks/[username].js new file mode 100644 index 0000000..6f426a9 --- /dev/null +++ b/routes/legacy/cloaks/[username].js @@ -0,0 +1,10 @@ +const express = require("express") +const router = express.Router({ mergeParams: true }) +const sessionsService = require("../../../services/sessionsService") + +router.get("", async (req, res) => { + const cape = await sessionsService.getActiveCape({ username: req.params.username.replace(".png", "") }) + return res.redirect(`/textures${cape.data.url}`) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/joinserver.js b/routes/legacy/joinserver.js new file mode 100644 index 0000000..62802fe --- /dev/null +++ b/routes/legacy/joinserver.js @@ -0,0 +1,26 @@ +const express = require("express") +const router = express.Router() +const sessionsService = require("../../services/sessionsService") +const logger = require("../../modules/logger") + +router.get("/", async (req, res) => { + const { user, sessionId, serverId } = req.query + const clientIp = req.ip || req.connection.remoteAddress + + try { + await sessionsService.joinLegacyServer({ + name: user, + sessionId, + serverId, + ip: clientIp + }) + + logger.log(`Legacy Join: ${user} -> ${serverId}`, ["AUTH", "green"]) + return res.send("OK") + + } catch (err) { + return res.send("Bad login") + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/login.js b/routes/legacy/login.js new file mode 100644 index 0000000..7f4ccbe --- /dev/null +++ b/routes/legacy/login.js @@ -0,0 +1,36 @@ +const express = require("express") +const router = express.Router() +const crypto = require("crypto") +const authService = require("../../services/authService") +const sessionsService = require("../../services/sessionsService") +const logger = require("../../modules/logger") + +router.all("/", async (req, res) => { + const { user, password } = { ...req.query, ...req.body } + + try { + const result = await authService.authenticate({ + identifier: user, + password, + clientToken: "", + requireUser: false + }) + + const profile = result.response.selectedProfile + const sessionId = crypto.randomBytes(16).toString("hex") + + await sessionsService.registerLegacySession({ + uuid: profile.id, + sessionId + }) + + logger.log(`Legacy Login: ${user}`, ["AUTH", "green"]) + + const timestamp = Date.now() + return res.send(`${timestamp}:deprecated:${profile.name}:${sessionId}:${profile.id}`) + } catch (err) { + return res.send("Bad login") + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/legacy/skins/[username].js b/routes/legacy/skins/[username].js new file mode 100644 index 0000000..b2aa20b --- /dev/null +++ b/routes/legacy/skins/[username].js @@ -0,0 +1,10 @@ +const express = require("express") +const router = express.Router({ mergeParams: true }) +const sessionsService = require("../../../services/sessionsService") + +router.get("", async (req, res) => { + const cape = await sessionsService.getActiveSkin({ username: req.params.username.replace(".png", "") }) + return res.redirect(`/textures${cape.data.url}`) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/capes/active.js b/routes/minecraftservices/minecraft/profile/capes/active.js new file mode 100644 index 0000000..d99b869 --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/capes/active.js @@ -0,0 +1,26 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../../../services/userService") +const authService = require("../../../../../services/authService") + +router.delete("/", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + await userService.hideCape(player.user.uuid) + return res.status(200).send() +}) + +router.put("/", async (req, res) => { + const player = await authService.verifyAccessToken(req.headers.authorization) + + await userService.showCape(player.user.uuid, req.body.capeId) + const [skinsResult, capesResult] = await Promise.all([userService.getSkins(player.user.uuid), userService.getCapes(player.user.uuid)]) + + return res.status(200).json({ + id: player.user.uuid.replace(/-/g, ""), + name: player.user.username, + skins: skinsResult.data || [], + capes: capesResult.data || [] + }) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/index.js b/routes/minecraftservices/minecraft/profile/index.js new file mode 100644 index 0000000..89914f3 --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/index.js @@ -0,0 +1,18 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../../services/userService") +const authService = require("../../../../services/authService") + +router.get("/", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer ", "") }) + const [skinsResult, capesResult] = await Promise.all([userService.getSkins(player.user.uuid), userService.getCapes(player.user.uuid)]) + + return res.status(200).json({ + id: player.uuid.replace(/-/g, ""), + name: player.user.username, + skins: skinsResult.data || [], + capes: capesResult.data || [] + }) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/lookup/bulk/byname.js b/routes/minecraftservices/minecraft/profile/lookup/bulk/byname.js new file mode 100644 index 0000000..b194acd --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/lookup/bulk/byname.js @@ -0,0 +1,10 @@ +const express = require("express") +const userService = require("../../../../../../services/userService") +const router = express.Router() + +router.post("/", async (req, res) => { + const profiles = await userService.bulkLookup(req.body) + return res.status(200).json(profiles) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/lookup/name/[username].js b/routes/minecraftservices/minecraft/profile/lookup/name/[username].js new file mode 100644 index 0000000..2367069 --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/lookup/name/[username].js @@ -0,0 +1,27 @@ +const express = require("express") +const utils = require("../../../../../../modules/utils") +const userService = require("../../../../../../services/userService") +const authService = require("../../../../../../services/authService") +const { ServiceError } = require("../../../../../../errors/errors") +const router = express.Router({ mergeParams: true }) + +router.get("", async (req, res) => { + const profile = await userService.getLegacyProfile(req.params.username) + const isUsernameOK = await authService.checkUsernameAvailability(newName) + const at = req.query.at + if (at != undefined && utils.isTrueFromDotEnv("SUPPORT_UUID_TO_NAME_HISTORY")) { + const history = await userService.getNameUUIDs(parseInt(at)) + return res.status(history.code).json(history.data) + } else { + throw new ServiceError(400, req.originalUrl, "IllegalArgumentException", "Invalid timestamp.") + } + if (isUsernameOK.status != "AVAILABLE") { + throw new ServiceError(400, req.originalUrl, "CONSTRAINT_VIOLATION", "Invalid username.") + } + if (!profile) { + return res.status(204).send() + } + return res.status(200).json(profile) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/name/[name].js b/routes/minecraftservices/minecraft/profile/name/[name].js new file mode 100644 index 0000000..effc594 --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/name/[name].js @@ -0,0 +1,44 @@ +const express = require("express") +const authService = require("../../../../../services/authService") +const { DefaultError, ServiceError } = require("../../../../../errors/errors") +const router = express.Router({ mergeParams: true }) + +router.get("/available", async (req, res) => { + try { + await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + const isAvailable = await authService.checkUsernameAvailability(req.params.name) + return res.status(200).json({ status: isAvailable.status }) + } catch (error) { + if (error instanceof DefaultError) { + throw new ServiceError(error.code, req.originalUrl, null, null, null) + } + throw error + } +}) + +router.put("/", async (req, res) => { + try { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + const newName = req.params.name + + await userService.changeUsername(player.uuid, newName) + + const skinsResult = await userService.getSkins({ uuid: player.uuid }) + const capesResult = await userService.getCapes({ uuid: player.uuid }) + + return res.status(200).json({ + id: player.uuid.replace(/-/g, ""), + name: newName, + skins: skinsResult.data || [], + capes: capesResult.data || [] + }) + + } catch (err) { + const mcStatus = err.code === 409 ? "DUPLICATE" : (err.code === 400 || err.code === 403) ? "NOT_ALLOWED" : null + const finalCode = (mcStatus === "DUPLICATE") ? 403 : (err.code || 500) + const errorType = mcStatus ? "FORBIDDEN" : (err.error || "Internal Server Error") + throw new ServiceError(finalCode, req.originalUrl, errorType, err.message, mcStatus ? { status: mcStatus } : null) + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/namechange.js b/routes/minecraftservices/minecraft/profile/namechange.js new file mode 100644 index 0000000..f4578c0 --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/namechange.js @@ -0,0 +1,12 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../../services/userService") +const authService = require("../../../../services/authService") + +router.get("/", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer ", "") }) + const nameChangeInformation = await userService.getPlayerNameChangeStatus(player.user.uuid) + return res.status(nameChangeInformation.code).json(nameChangeInformation.data) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/skins/active.js b/routes/minecraftservices/minecraft/profile/skins/active.js new file mode 100644 index 0000000..6cd257c --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/skins/active.js @@ -0,0 +1,12 @@ +const express = require("express") +const router = express.Router() +const userService = require("../../../../../services/userService") +const authService = require("../../../../../services/authService") + +router.delete("/", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + await userService.resetSkin(player.user.uuid) + return res.status(200).send() +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/minecraft/profile/skins/index.js b/routes/minecraftservices/minecraft/profile/skins/index.js new file mode 100644 index 0000000..e875bc6 --- /dev/null +++ b/routes/minecraftservices/minecraft/profile/skins/index.js @@ -0,0 +1,77 @@ +const fs = require("node:fs") +const path = require("node:path") +const express = require("express") +const router = express.Router() +const multer = require("multer") +const rateLimit = require("express-rate-limit") +const userService = require("../../../../../services/userService") +const authService = require("../../../../../services/authService") +const { DefaultError } = require("../../../../../errors/errors") + +const TEMP_DIR = path.join(process.cwd(), "data", "temp") + +if (!fs.existsSync(TEMP_DIR)) { + fs.mkdirSync(TEMP_DIR, { recursive: true }) +} + +const upload = multer({ + dest: TEMP_DIR, + limits: { fileSize: 2 * 1024 * 1024 } +}) + +const uploadLimiter = rateLimit({ + windowMs: 60 * 1000, + max: 20, + standardHeaders: true, + legacyHeaders: false, + validate: { + ip: false + }, + keyGenerator: (req) => { + rateLimit.ipKeyGenerator() + return req.headers.authorization || req.ip + }, + handler: (req, res, next, options) => { + throw new DefaultError(429, "Too many requests. Please try again later.") + } +}) + + +router.post("/", uploadLimiter, async (req, res, next) => { + if (req.is('application/json')) { + try { + const token = req.headers.authorization.replace("Bearer ", "").trim() + const player = await authService.verifyAccessToken({ accessToken: token }) + + await userService.uploadSkinFromUrl(player.user.uuid, req.body.url, req.body.variant) + + return res.status(200).send() + } catch (err) { + return next(err) + } + } + + else { + upload.single("file")(req, res, async (err) => { + if (err) return next(err) + try { + if (!req.headers.authorization) { + if (req.file) await fs.promises.unlink(req.file.path).catch(() => {}) + throw new DefaultError(401, "Missing Authorization Header") + } + + const token = req.headers.authorization.replace("Bearer ", "").trim() + const player = await authService.verifyAccessToken({ accessToken: token }) + + await userService.uploadSkin(player.user.uuid, req.file, req.body.variant) + + return res.status(200).send() + } catch (error) { + if (req.file) await fs.promises.unlink(req.file.path).catch(() => {}) + return next(error) + } + }) + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/player/attributes.js b/routes/minecraftservices/player/attributes.js new file mode 100644 index 0000000..e69088c --- /dev/null +++ b/routes/minecraftservices/player/attributes.js @@ -0,0 +1,34 @@ +const express = require("express") +const userService = require("../../../services/userService") +const authService = require("../../../services/authService") +const router = express.Router() + +router.get("", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + + const [preferencesResult, privilegesResult, banStatus] = await Promise.all([userService.getPreferences(player.user.uuid), userService.getPrivileges(player.user.uuid), userService.getPlayerBanStatus(player.user.uuid)]) + return res.status(200).json({ + privileges: privilegesResult.data, + ...preferencesResult.data, + banStatus: { + bannedScopes: banStatus.isBanned ? { MULTIPLAYER: banStatus.activeBan } : {} + } + }) +}) + +router.post("", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + + await userService.updatePreferences(player.user.uuid, req.body) + + const [preferencesResult, privilegesResult, banStatus] = await Promise.all([userService.getPreferences(player.user.uuid), userService.getPrivileges(player.user.uuid), userService.getPlayerBanStatus(player.user.uuid)]) + return res.status(200).json({ + privileges: privilegesResult.data, + ...preferencesResult.data, + banStatus: { + bannedScopes: banStatus.isBanned ? { MULTIPLAYER: banStatus.activeBan } : {} + } + }) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/player/certificates.js b/routes/minecraftservices/player/certificates.js new file mode 100644 index 0000000..a0e607c --- /dev/null +++ b/routes/minecraftservices/player/certificates.js @@ -0,0 +1,12 @@ +const express = require("express") +const userService = require("../../../services/userService") +const authService = require("../../../services/authService") +const router = express.Router() + +router.post("", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + const certificates = await userService.fetchOrGenerateCertificate(player.user.uuid) + return res.status(200).json(certificates.data) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/privacy/blocklist.js b/routes/minecraftservices/privacy/blocklist.js new file mode 100644 index 0000000..20895f5 --- /dev/null +++ b/routes/minecraftservices/privacy/blocklist.js @@ -0,0 +1,39 @@ +const express = require("express") +const router = express.Router() +const utils = require("../../../modules/utils") // Pour addDashesToUUID +const authService = require("../../../services/authService") +const userService = require("../../../services/userService") + +router.get("/", async (req, res, next) => { + const user = await authService.verifyUserFromHeader(req.headers.authorization) + const result = await userService.getBlockedUuids(user.uuid) + return res.status(200).json({ + blockedProfiles: result.data || [] + }) +}) + +router.put("/:uuid", async (req, res, next) => { + const user = await authService.verifyUserFromHeader(req.headers.authorization) + const targetUuid = utils.addDashesToUUID(req.params.uuid) + + await userService.blockPlayer(user.uuid, targetUuid) + + const result = await userService.getBlockedUuids(user.uuid) + return res.status(200).json({ + blockedProfiles: result.data || [] + }) +}) + +router.delete("/:uuid", async (req, res, next) => { + const user = await authService.verifyUserFromHeader(req.headers.authorization) + const targetUuid = utils.addDashesToUUID(req.params.uuid) + + await userService.unblockPlayer(user.uuid, targetUuid) + + const result = await userService.getBlockedUuids(user.uuid) + return res.status(200).json({ + blockedProfiles: result.data || [] + }) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/privileges.js b/routes/minecraftservices/privileges.js new file mode 100644 index 0000000..3d82079 --- /dev/null +++ b/routes/minecraftservices/privileges.js @@ -0,0 +1,34 @@ +const express = require("express") +const userService = require("../../services/userService") +const authService = require("../../services/authService") +const router = express.Router() + +router.get("", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + + const [preferencesResult, privilegesResult, banStatus] = await Promise.all([userService.getPreferences(player.user.uuid), userService.getPrivileges(player.user.uuid), userService.getPlayerBanStatus(player.user.uuid)]) + return res.status(200).json({ + privileges: privilegesResult.data, + ...preferencesResult.data, + banStatus: { + bannedScopes: banStatus.isBanned ? { MULTIPLAYER: banStatus.activeBan } : {} + } + }) +}) + +router.post("", async (req, res) => { + const player = await authService.verifyAccessToken({ accessToken: req.headers.authorization.replace("Bearer", "").trim() }) + + await userService.updatePreferences(player.user.uuid, req.body) + + const [preferencesResult, privilegesResult, banStatus] = await Promise.all([userService.getPreferences(player.user.uuid), userService.getPrivileges(player.user.uuid), userService.getPlayerBanStatus(player.user.uuid)]) + return res.status(200).json({ + privileges: privilegesResult.data, + ...preferencesResult.data, + banStatus: { + bannedScopes: banStatus.isBanned ? { MULTIPLAYER: banStatus.activeBan } : {} + } + }) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/productvoucher.js b/routes/minecraftservices/productvoucher.js new file mode 100644 index 0000000..7bf08e4 --- /dev/null +++ b/routes/minecraftservices/productvoucher.js @@ -0,0 +1,14 @@ +const express = require("express") +const router = express.Router() + +router.get("/giftcode", (req, res) => { + return res.status(404).json({ + path: "/productvoucher/giftcode", + errorType: "NOT_FOUND", + error: "NOT_FOUND", + errorMessage: "The server has not found anything matching the request URI", + developerMessage: "The server has not found anything matching the request URI" + }) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/minecraftservices/publickeys.js b/routes/minecraftservices/publickeys.js new file mode 100644 index 0000000..9c1b44e --- /dev/null +++ b/routes/minecraftservices/publickeys.js @@ -0,0 +1,18 @@ +const express = require("express") +const router = express.Router() +const certificatesManager = require("../../modules/certificatesManager") + +router.get("", (req, res) => { + const keys = certificatesManager.getKeys() + const publicKeys = {} + for (const key in keys) { + publicKeys[key] = [ + { + publicKey: certificatesManager.extractKeyFromPem(keys[key].public) + } + ] + } + return res.status(200).json(publicKeys) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/register.js b/routes/register.js new file mode 100644 index 0000000..5ca62fa --- /dev/null +++ b/routes/register.js @@ -0,0 +1,44 @@ +const express = require("express") +const router = express.Router() +const utils = require("../modules/utils") +const logger = require("../modules/logger") +const authService = require("../services/authService") +const adminService = require("../services/adminService") + +if (utils.isTrueFromDotEnv("SUPPORT_REGISTER")) { + router.post("/", adminService.hasPermission("REGISTER_USER"), async (req, res) => { + const { username, password, email, registrationCountry, preferredLanguage } = req.body + const clientIp = req.headers["x-forwarded-for"] || req.connection.remoteAddress + + const result = await authService.registerUser({ + username, + password, + email, + registrationCountry, + preferredLanguage, + clientIp + }) + + logger.log(`New user registered: ${username}`, ["Web", "yellow", "AUTH", "green"]) + return res.status(200).json(result) + }) +} else { + router.post("/", async (req, res) => { + const { username, password, email, registrationCountry, preferredLanguage } = req.body + const clientIp = req.headers["x-forwarded-for"] || req.connection.remoteAddress + + const result = await authService.registerUser({ + username, + password, + email, + registrationCountry, + preferredLanguage, + clientIp + }) + + logger.log(`New user registered: ${username}`, ["Web", "yellow", "AUTH", "green"]) + return res.status(200).json(result) + }) +} + +module.exports = router \ No newline at end of file diff --git a/routes/sessionserver/blockedservers.js b/routes/sessionserver/blockedservers.js new file mode 100644 index 0000000..d0a57bd --- /dev/null +++ b/routes/sessionserver/blockedservers.js @@ -0,0 +1,18 @@ +const express = require("express") +const router = express.Router() +const sessionsService = require("../../services/sessionsService") +const { DefaultError } = require("../../errors/errors") + +router.get("", async (req, res) => { + const serviceResult = await sessionsService.getBlockedServers() + if (serviceResult instanceof DefaultError) { + return res.status(200).send("") + } + const finalList = [] + for (const server of serviceResult.blockedServers) { + finalList.push(server.sha1) + } + return res.status(200).send(finalList.join("\r\n")) +}) + +module.exports = router \ No newline at end of file diff --git a/routes/sessionserver/session/minecraft/hasJoined.js b/routes/sessionserver/session/minecraft/hasJoined.js new file mode 100644 index 0000000..17e1615 --- /dev/null +++ b/routes/sessionserver/session/minecraft/hasJoined.js @@ -0,0 +1,24 @@ +const express = require("express") +const router = express.Router() +const sessionsService = require("../../../../services/sessionsService") +const logger = require("../../../../modules/logger") +const { YggdrasilError, DefaultError } = require("../../../../errors/errors") + +router.get("/", async (req, res) => { + const { username, serverId, ip } = req.query + try { + const result = await sessionsService.hasJoinedServer({ username, serverId, ip }) + if (result.code === 200) { + logger.log(`Server join verified for: ${username}`, ["SESSION", "green"]) + return res.status(200).json(result.data) + } + return res.status(204).end() + } catch (err) { + if (err instanceof DefaultError) { + throw new YggdrasilError(err.code, err.error || "InternalServerError", err.message, err.cause) + } + throw err + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/sessionserver/session/minecraft/join.js b/routes/sessionserver/session/minecraft/join.js new file mode 100644 index 0000000..4e5e50f --- /dev/null +++ b/routes/sessionserver/session/minecraft/join.js @@ -0,0 +1,66 @@ +const path = require("path") +const express = require("express") +const router = express.Router() +const utils = require("../../../../modules/utils") +const authService = require("../../../../services/authService") +const sessionsService = require("../../../../services/sessionsService") +const userRepository = require("../../../../repositories/userRepository") +const logger = require("../../../../modules/logger") +const { SessionError, DefaultError } = require("../../../../errors/errors") + +router.post("/", async (req, res) => { + const { accessToken, selectedProfile, serverId } = req.body + + try { + const verificationResult = await authService.verifyAccessToken({ accessToken }) + const tokenUuid = verificationResult.user.uuid + const requestedProfile = utils.addDashesToUUID(selectedProfile) + + if (tokenUuid !== requestedProfile) { + throw new SessionError(403, "Forbidden", "You cannot join with a profile that is not yours.", req.originalUrl) + } + + const bansResult = await userRepository.getPlayerBans(tokenUuid) + if (bansResult.code === 200 && bansResult.bans && bansResult.bans.length > 0) { + const activeBan = bansResult.bans[0] + throw new SessionError( + 403, + "UserBannedException", + activeBan.reasonMessage || "You are banned from multiplayer.", + req.originalUrl + ) + } + + try { + const privsResult = await userRepository.getPlayerPrivileges(tokenUuid) + if (privsResult.code === 200 && privsResult.data) { + if (!privsResult.data.multiplayerServer) { + throw new SessionError(403, "InsufficientPrivilegesException", "Multiplayer is disabled for your account.", req.originalUrl) + } + } + } catch (privError) { + if (privError instanceof DefaultError && privError.code !== 404) throw privError + } + const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress + await sessionsService.joinServer({ + clientToken: verificationResult.session.clientToken, + accessToken, + selectedProfile: requestedProfile, + serverId, + ip + }) + logger.log(`Server join success: ${verificationResult.user.username}`, ["SESSION", "green"]) + return res.status(204).end() + } catch (err) { + console.log(err) + if (err instanceof SessionError) throw err + if (err instanceof DefaultError) { + const statusCode = err.code === 401 ? 403 : (err.code || 500) + const errorName = "Forbidden" + throw new SessionError(statusCode, errorName, err.message, req.originalUrl) + } + throw new SessionError(500, "Forbidden", "Internal Server Error", req.originalUrl) + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/sessionserver/session/minecraft/profile/[uuid].js b/routes/sessionserver/session/minecraft/profile/[uuid].js new file mode 100644 index 0000000..daf0a7f --- /dev/null +++ b/routes/sessionserver/session/minecraft/profile/[uuid].js @@ -0,0 +1,29 @@ +const express = require("express") +const router = express.Router({ mergeParams: true }) +const sessionsService = require("../../../../../services/sessionsService") +const { SessionError, DefaultError } = require("../../../../../errors/errors") + +router.get("", async (req, res) => { + const { uuid } = req.params + const { unsigned } = req.query + const isUnsigned = (unsigned == undefined || unsigned == "true") ? true : false + + try { + const result = await sessionsService.getProfile({ + uuid: uuid, + unsigned: isUnsigned + }) + if (result.code === 200) { + return res.status(200).json(result.data) + } + if (result.code === 204) { + throw new SessionError(404, undefined, "Not a valid UUID", req.originalUrl) + } + throw new DefaultError(500, undefined, "Unknown error", req.originalUrl) + } catch (err) { + const errorMessage = err.message || "Not a valid UUID" + throw new SessionError(400, undefined, errorMessage, req.originalUrl) + } +}) + +module.exports = router \ No newline at end of file diff --git a/routes/textures/texture/[hash].js b/routes/textures/texture/[hash].js new file mode 100644 index 0000000..09bf57c --- /dev/null +++ b/routes/textures/texture/[hash].js @@ -0,0 +1,22 @@ +const express = require("express") +const router = express.Router({ mergeParams: true }) +const path = require("node:path") +const fs = require("node:fs") +const { DefaultError } = require("../../../errors/errors") + +const TEXTURES_DIR = path.join(process.cwd(), "data", "textures") + +router.get("/", async (req, res, next) => { + try { + const hash = req.params.hash + const filePath = path.join(TEXTURES_DIR, hash) + if (!fs.existsSync(filePath)) { + throw new DefaultError(404, "Texture not found") + } + res.sendFile(filePath) + } catch (err) { + return next(err) + } +}) + +module.exports = router \ No newline at end of file diff --git a/schemas/admin/admin/cosmetics/capes/[hash].js b/schemas/admin/admin/cosmetics/capes/[hash].js new file mode 100644 index 0000000..f518227 --- /dev/null +++ b/schemas/admin/admin/cosmetics/capes/[hash].js @@ -0,0 +1,9 @@ +const z = require("zod") + +module.exports = { + DELETE: { + query: z.object({ + hash: z.string().length(64) + }) + } +} \ No newline at end of file diff --git a/schemas/admin/ban/[uuid]/actions.js b/schemas/admin/ban/[uuid]/actions.js new file mode 100644 index 0000000..d258b18 --- /dev/null +++ b/schemas/admin/ban/[uuid]/actions.js @@ -0,0 +1,9 @@ +const z = require("zod") + +module.exports = { + GET: { + query: z.object({ + uuid: z.string().uuid() + }) + } +} \ No newline at end of file diff --git a/schemas/admin/ban/[uuid]/history.js b/schemas/admin/ban/[uuid]/history.js new file mode 100644 index 0000000..d258b18 --- /dev/null +++ b/schemas/admin/ban/[uuid]/history.js @@ -0,0 +1,9 @@ +const z = require("zod") + +module.exports = { + GET: { + query: z.object({ + uuid: z.string().uuid() + }) + } +} \ No newline at end of file diff --git a/schemas/admin/ban/[uuid]/index.js b/schemas/admin/ban/[uuid]/index.js new file mode 100644 index 0000000..2532a8f --- /dev/null +++ b/schemas/admin/ban/[uuid]/index.js @@ -0,0 +1,26 @@ +const z = require("zod") + +const uuidSchema = z.object({ + uuid: z.string().uuid() +}) + +module.exports = { + GET: { + query: uuidSchema + }, + PUT: { + body: z.object({ + reasonKey: z.string().min(1), + reasonMessage: z.string().optional(), + expires: z.number().int().positive().optional() + }), + error: { + code: 400, + error: "CONSTRAINT_VIOLATION", + errorMessage: "Invalid ban format" + } + }, + DELETE: { + query: uuidSchema + } +} \ No newline at end of file diff --git a/schemas/admin/players/password/[uuid].js b/schemas/admin/players/password/[uuid].js new file mode 100644 index 0000000..ef84376 --- /dev/null +++ b/schemas/admin/players/password/[uuid].js @@ -0,0 +1,12 @@ +const z = require("zod") + +module.exports = { + PATCH: { + body: z.object({ + newPassword: z.string() + .min(8, { message: "The password must be at least 8 characters long." }) + .regex(/[A-Z]/, { message: "The password must contain a capital letter." }) + .regex(/[0-9]/, { message: "The password must contain a number." }), + }) + } +} \ No newline at end of file diff --git a/schemas/admin/players/textures/cape/[uuid]/[hash].js b/schemas/admin/players/textures/cape/[uuid]/[hash].js new file mode 100644 index 0000000..1cabf15 --- /dev/null +++ b/schemas/admin/players/textures/cape/[uuid]/[hash].js @@ -0,0 +1,16 @@ +const z = require("zod") + +module.exports = { + PUT: { + query: z.object({ + uuid: z.string().uuid(), + hash: z.string().length(64) + }) + }, + DELETE: { + query: z.object({ + uuid: z.string().uuid(), + hash: z.string().length(64) + }) + } +} \ No newline at end of file diff --git a/schemas/api/minecraft/profile/lookup/bulk/byname.js b/schemas/api/minecraft/profile/lookup/bulk/byname.js new file mode 100644 index 0000000..3d14200 --- /dev/null +++ b/schemas/api/minecraft/profile/lookup/bulk/byname.js @@ -0,0 +1,18 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.array(z.string().trim().min(1)) + .min(1, { message: "RequestPayload is an empty array." }) + .max(10, { message: "RequestPayload has more than 10 elements." }), + error: { + code: 400, + error: "CONSTRAINT_VIOLATION", + errorMessage: "size must be between 1 and 10" + } + } +} \ No newline at end of file diff --git a/schemas/api/profile/lookup/name/[username].js b/schemas/api/profile/lookup/name/[username].js new file mode 100644 index 0000000..de0b261 --- /dev/null +++ b/schemas/api/profile/lookup/name/[username].js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + GET: { + params: z.object({ + username: z.string().min(1, { message: "Username is required." }) + }), + error: { + code: 404, + message: "Not Found" + } + } +} \ No newline at end of file diff --git a/schemas/api/profiles/minecraft.js b/schemas/api/profiles/minecraft.js new file mode 100644 index 0000000..3d14200 --- /dev/null +++ b/schemas/api/profiles/minecraft.js @@ -0,0 +1,18 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.array(z.string().trim().min(1)) + .min(1, { message: "RequestPayload is an empty array." }) + .max(10, { message: "RequestPayload has more than 10 elements." }), + error: { + code: 400, + error: "CONSTRAINT_VIOLATION", + errorMessage: "size must be between 1 and 10" + } + } +} \ No newline at end of file diff --git a/schemas/api/user/profiles/[uuid]/names.js b/schemas/api/user/profiles/[uuid]/names.js new file mode 100644 index 0000000..169d871 --- /dev/null +++ b/schemas/api/user/profiles/[uuid]/names.js @@ -0,0 +1,18 @@ +const z = require("zod") + +module.exports = { + GET: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + .optional() + }), + params: z.object({ + uuid: z.string().uuid({ message: "Invalid UUID format." }) + }), + error: { + code: 204, + message: "No content" + } + } +} \ No newline at end of file diff --git a/schemas/api/users/profiles/minecraft/[username].js b/schemas/api/users/profiles/minecraft/[username].js new file mode 100644 index 0000000..de0b261 --- /dev/null +++ b/schemas/api/users/profiles/minecraft/[username].js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + GET: { + params: z.object({ + username: z.string().min(1, { message: "Username is required." }) + }), + error: { + code: 404, + message: "Not Found" + } + } +} \ No newline at end of file diff --git a/schemas/authserver/authenticate.js b/schemas/authserver/authenticate.js new file mode 100644 index 0000000..842139d --- /dev/null +++ b/schemas/authserver/authenticate.js @@ -0,0 +1,31 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.object({ + agent: z.object({ + name: z.string(), + version: z.number() + }).optional(), + username: z.string() + .min(3, { message: "The username must be at least 3 characters long." }) + .max(16, { message: "The username must be no longer than 16 characters." }), + password: z.string() + .min(8, { message: "The password must be at least 8 characters long." }) + .regex(/[A-Z]/, { message: "The password must contain a capital letter." }) + .regex(/[0-9]/, { message: "The password must contain a number." }), + clientToken: z.string().optional(), + requestUser: z.boolean().optional() + }), + error: { + code: 415, + error: "Unsupported Media Type", + errorFormat: "YggdrasilError", + errorMessage: "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method." + } + } +} \ No newline at end of file diff --git a/schemas/authserver/invalidate.js b/schemas/authserver/invalidate.js new file mode 100644 index 0000000..5b5f46c --- /dev/null +++ b/schemas/authserver/invalidate.js @@ -0,0 +1,23 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.object({ + accessToken: z.string() + .min(1, { message: "Access token is required." }), + + clientToken: z.string() + .min(1, { message: "Client token is required." }) + }), + error: { + code: 415, + error: "Unsupported Media Type", + errorFormat: "YggdrasilError", + errorMessage: "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method." + } + } +} \ No newline at end of file diff --git a/schemas/authserver/refresh.js b/schemas/authserver/refresh.js new file mode 100644 index 0000000..65b3398 --- /dev/null +++ b/schemas/authserver/refresh.js @@ -0,0 +1,23 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.object({ + accessToken: z.string() + .min(1, { message: "Access token is required." }), + clientToken: z.string() + .min(1, { message: "Client token is required." }), + requestUser: z.boolean().optional() + }), + error: { + code: 415, + error: "Unsupported Media Type", + errorFormat: "YggdrasilError", + errorMessage: "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method." + } + } +} \ No newline at end of file diff --git a/schemas/authserver/signout.js b/schemas/authserver/signout.js new file mode 100644 index 0000000..16987ee --- /dev/null +++ b/schemas/authserver/signout.js @@ -0,0 +1,25 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.object({ + username: z.string() + .min(3, { message: "The username must be at least 3 characters long." }) + .max(16, { message: "The username must be no longer than 16 characters." }), + password: z.string() + .min(8, { message: "The password must be at least 8 characters long." }) + .regex(/[A-Z]/, { message: "The password must contain a capital letter." }) + .regex(/[0-9]/, { message: "The password must contain a number." }) + }), + error: { + code: 403, + errorFormat: "YggdrasilError", + errorName: "ForbiddenOperationException", + message: "Invalid credentials." + } + } +} \ No newline at end of file diff --git a/schemas/authserver/validate.js b/schemas/authserver/validate.js new file mode 100644 index 0000000..db3058e --- /dev/null +++ b/schemas/authserver/validate.js @@ -0,0 +1,23 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.object({ + accessToken: z.string() + .min(1, { message: "Access token is required." }), + + clientToken: z.string() + .optional() + }), + error: { + code: 415, + error: "Unsupported Media Type", + errorFormat: "YggdrasilError", + errorMessage: "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method." + } + } +} \ No newline at end of file diff --git a/schemas/legacy/joinserver.js b/schemas/legacy/joinserver.js new file mode 100644 index 0000000..02d5cff --- /dev/null +++ b/schemas/legacy/joinserver.js @@ -0,0 +1,11 @@ +const z = require("zod") + +module.exports = { + GET: { + query: z.object({ + user: z.string().min(1), + sessionId: z.string().min(1), + serverId: z.string().min(1) + }) + } +} \ No newline at end of file diff --git a/schemas/legacy/legacy/checkserver.js b/schemas/legacy/legacy/checkserver.js new file mode 100644 index 0000000..2487bc0 --- /dev/null +++ b/schemas/legacy/legacy/checkserver.js @@ -0,0 +1,10 @@ +const z = require("zod") + +module.exports = { + GET: { + query: z.object({ + user: z.string().min(1), + serverId: z.string().min(1) + }) + } +} \ No newline at end of file diff --git a/schemas/legacy/login.js b/schemas/legacy/login.js new file mode 100644 index 0000000..6037e22 --- /dev/null +++ b/schemas/legacy/login.js @@ -0,0 +1,16 @@ +const z = require("zod") + +const loginShape = { + user: z.string().min(1, { message: "Username required" }), + password: z.string().min(1, { message: "Password required" }), + version: z.union([z.string(), z.number()]).optional() +} + +module.exports = { + POST: { + body: z.object(loginShape), + }, + GET: { + query: z.object(loginShape) + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile.js b/schemas/minecraftservices/minecraft/profile.js new file mode 100644 index 0000000..655f12d --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile.js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + GET: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/capes/active.js b/schemas/minecraftservices/minecraft/profile/capes/active.js new file mode 100644 index 0000000..3161da4 --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/capes/active.js @@ -0,0 +1,28 @@ +const z = require("zod") + +module.exports = { + DELETE: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + }, + PUT: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }), + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + body: z.object({ + capeId: z.string().uuid({ message: "Invalid Cape UUID." }) + }), + error: { + code: 400, + message: "profile does not own cape", + error: "IllegalArgumentException" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/lookup/bulk/byname.js b/schemas/minecraftservices/minecraft/profile/lookup/bulk/byname.js new file mode 100644 index 0000000..3d14200 --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/lookup/bulk/byname.js @@ -0,0 +1,18 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }) + }), + body: z.array(z.string().trim().min(1)) + .min(1, { message: "RequestPayload is an empty array." }) + .max(10, { message: "RequestPayload has more than 10 elements." }), + error: { + code: 400, + error: "CONSTRAINT_VIOLATION", + errorMessage: "size must be between 1 and 10" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/lookup/name/[username].js b/schemas/minecraftservices/minecraft/profile/lookup/name/[username].js new file mode 100644 index 0000000..e1fca5c --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/lookup/name/[username].js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + GET: { + params: z.object({ + username: z.string().min(1) + }), + error: { + code: 404, + message: "Not Found" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/name/[name].js b/schemas/minecraftservices/minecraft/profile/name/[name].js new file mode 100644 index 0000000..dde4fa8 --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/name/[name].js @@ -0,0 +1,22 @@ +const z = require("zod") + +const nameSchema = z.string() + .min(1) + .max(16) + .regex(/^[a-zA-Z0-9_]+$/, { message: "Name can only contain alphanumeric characters and underscores." }); + +module.exports = { + PUT: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + params: z.object({ + name: nameSchema + }), + error: { + code: 400, + error: "CONSTRAINT_VIOLATION", + errorMessage: "Invalid profile name" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/name/[name]/available.js b/schemas/minecraftservices/minecraft/profile/name/[name]/available.js new file mode 100644 index 0000000..9515db1 --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/name/[name]/available.js @@ -0,0 +1,21 @@ +const z = require("zod") + +const nameSchema = z.string() + .min(1) + .max(16) + .regex(/^[a-zA-Z0-9_]+$/, { message: "Name can only contain alphanumeric characters and underscores." }); + +module.exports = { + GET: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + params: z.object({ + name: nameSchema + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/namechange.js b/schemas/minecraftservices/minecraft/profile/namechange.js new file mode 100644 index 0000000..655f12d --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/namechange.js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + GET: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/skins.js b/schemas/minecraftservices/minecraft/profile/skins.js new file mode 100644 index 0000000..9ed9d94 --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/skins.js @@ -0,0 +1,24 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }), + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + body: z.object({ + variant: z.enum(["classic", "slim"], { + errorMap: () => ({ message: "Variant must be 'classic' or 'slim'." }) + }), + url: z.string() + .url({ message: "Invalid URL format." }) + .max(2048, { message: "URL is too long." }) + }), + error: { + code: 400, + message: "Invalid skin URL or variant.", + error: "IllegalArgumentException" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/minecraft/profile/skins/active.js b/schemas/minecraftservices/minecraft/profile/skins/active.js new file mode 100644 index 0000000..4f24f83 --- /dev/null +++ b/schemas/minecraftservices/minecraft/profile/skins/active.js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + DELETE: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/player/attributes.js b/schemas/minecraftservices/player/attributes.js new file mode 100644 index 0000000..b1b5f11 --- /dev/null +++ b/schemas/minecraftservices/player/attributes.js @@ -0,0 +1,29 @@ +const z = require("zod") + +module.exports = { + GET: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + }, + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }), + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + body: z.object({ + profanityFilterPreferences: z.object({ + profanityFilterOn: z.boolean({ required_error: "profanityFilterOn is required" }) + }) + }), + error: { + code: 400, + message: "Invalid attributes format." + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/player/certificates.js b/schemas/minecraftservices/player/certificates.js new file mode 100644 index 0000000..3c3a827 --- /dev/null +++ b/schemas/minecraftservices/player/certificates.js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/privacy/blocklist.js b/schemas/minecraftservices/privacy/blocklist.js new file mode 100644 index 0000000..655f12d --- /dev/null +++ b/schemas/minecraftservices/privacy/blocklist.js @@ -0,0 +1,13 @@ +const z = require("zod") + +module.exports = { + GET: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/privacy/blocklist/[uuid].js b/schemas/minecraftservices/privacy/blocklist/[uuid].js new file mode 100644 index 0000000..5e4cbe3 --- /dev/null +++ b/schemas/minecraftservices/privacy/blocklist/[uuid].js @@ -0,0 +1,28 @@ +const z = require("zod") + +module.exports = { + PUT: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + params: z.object({ + uuid: z.string().uuid({ message: "Invalid UUID." }) + }), + error: { + code: 400, + message: "Invalid UUID" + } + }, + DELETE: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + params: z.object({ + uuid: z.string().uuid({ message: "Invalid UUID." }) + }), + error: { + code: 400, + message: "Invalid UUID" + } + } +} \ No newline at end of file diff --git a/schemas/minecraftservices/privileges.js b/schemas/minecraftservices/privileges.js new file mode 100644 index 0000000..565226b --- /dev/null +++ b/schemas/minecraftservices/privileges.js @@ -0,0 +1,29 @@ +const z = require("zod") + +module.exports = { + GET: { + headers: z.object({ + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + error: { + code: 401, + message: "Unauthorized" + } + }, + POST: { + headers: z.object({ + "content-type": z.string() + .regex(/application\/json/i, { message: "Content-Type must be application/json" }), + "authorization": z.string().min(1, { message: "Authorization header is required." }) + }), + body: z.object({ + profanityFilterPreferences: z.object({ + profanityFilterOn: z.boolean({ required_error: "profanityFilterOn is required" }) + }).optional() + }), + error: { + code: 401, + message: "Unauthorized" + } + } +} \ No newline at end of file diff --git a/schemas/register.js b/schemas/register.js new file mode 100644 index 0000000..4e5a5bc --- /dev/null +++ b/schemas/register.js @@ -0,0 +1,25 @@ +const z = require("zod") + +module.exports = { + POST: { + headers: z.object({ + "content-type": z.string().regex(/application\/json/i) + }), + body: z.object({ + email: z.string() + .email({ message: "Invalid E-Mail format." }) + .toLowerCase(), + username: z.string() + .min(3, { message: "The username must be at least 3 characters long." }) + .max(16, { message: "The username must be no longer than 16 characters." }), + password: z.string() + .min(8, { message: "The password must be at least 8 characters long." }) + .regex(/[A-Z]/, { message: "The password must contain a capital letter." }) + .regex(/[0-9]/, { message: "The password must contain a number." }) + }), + error: { + code: 422, + message: "Invalid request data" + } + } +} \ No newline at end of file diff --git a/schemas/sessionsserver/session/minecraft/hasJoined.js b/schemas/sessionsserver/session/minecraft/hasJoined.js new file mode 100644 index 0000000..ebdce31 --- /dev/null +++ b/schemas/sessionsserver/session/minecraft/hasJoined.js @@ -0,0 +1,19 @@ +const z = require("zod") + +module.exports = { + GET: { + query: z.object({ + username: z.string() + .min(3) + .max(16), + serverId: z.string() + .min(1), + ip: z.string() + .optional() + }), + error: { + code: 204, + message: "Ignored" + } + } +} \ No newline at end of file diff --git a/schemas/sessionsserver/session/minecraft/join.js b/schemas/sessionsserver/session/minecraft/join.js new file mode 100644 index 0000000..311489c --- /dev/null +++ b/schemas/sessionsserver/session/minecraft/join.js @@ -0,0 +1,22 @@ +const z = require("zod") + +module.exports = { + POST: { + body: z.object({ + accessToken: z.string() + .min(1, { message: "Access Token is required." }), + selectedProfile: z.string() + .length(32, { message: "Selected Profile must be a valid UUID without dashes." }) + .regex(/^[0-9a-fA-F]+$/, { message: "Selected Profile must be hexadecimal." }), + serverId: z.string() + .min(1, { message: "Server ID is required." }) + .max(42, { message: "Server ID is too long." }) + }), + error: { + code: 400, + message: "Missing or invalid parameters.", + errorFormat: "SessionError", + errorName: "Forbidden" + } + } +} \ No newline at end of file diff --git a/schemas/sessionsserver/session/minecraft/profile/[uuid].js b/schemas/sessionsserver/session/minecraft/profile/[uuid].js new file mode 100644 index 0000000..ca145b0 --- /dev/null +++ b/schemas/sessionsserver/session/minecraft/profile/[uuid].js @@ -0,0 +1,16 @@ +const z = require("zod") + +module.exports = { + GET: { + params: z.object({ + uuid: z.string().length(32).regex(/^[0-9a-fA-F]+$/, { message: "Invalid UUID (no dashes expected)." }) + }), + query: z.object({ + unsigned: z.enum(["true", "false"]).optional() + }), + error: { + code: 204, + message: "No content (UUID not found)" + } + } +} \ No newline at end of file diff --git a/server.js b/server.js new file mode 100644 index 0000000..1274077 --- /dev/null +++ b/server.js @@ -0,0 +1,167 @@ +const express = require("express") +const hpp = require("hpp") +const app = express() +const cors = require("cors") +const path = require("node:path") +const utils = require("./modules/utils") +const logger = require("./modules/logger") +const helmet = require("helmet") +const loader = require("./modules/loader") +const DefaultError = require("./errors/DefaultError") +const path2regex = require("path-to-regexp") +const databaseGlobals = require("./modules/databaseGlobals") +const certificates = require("./modules/certificatesManager") +const { ValidationError } = require("./errors/errors") +const routes = loader.getRecursiveFiles(path.join(__dirname, "routes")) +const schemas = loader.getRecursiveFiles(path.join(__dirname, "schemas")) + +const schemaRegistry = {} + +databaseGlobals.setupDatabase() +certificates.setupKeys() + +app.use(hpp()) +app.use(helmet()) +app.use(cors({ origin: "*" })) + +app.use(express.json()) +app.use(express.urlencoded({ extended: true })) + +app.set("trust proxy", true) + +logger.log("Initializing routes", ["WEB", "yellow"]) + +for (const schemaFile of schemas) { + try { + const schemaConfig = require(schemaFile) + const routePath = loader.computeRoutePath(path.join(__dirname, "schemas"), schemaFile) + schemaRegistry[routePath] = schemaConfig + + logger.log(`${routePath.cyan.bold} schema loaded in memory`, ["WEB", "yellow"]) + } catch (error) { + logger.error(error.toString(), ["WEB", "yellow"]) + } +} + +app.all(/.*/, (req, res, next) => { + let currentPath = req.path + if (currentPath.length > 1 && currentPath.endsWith("/")) { + currentPath = currentPath.slice(0, -1) + } + + let schemaConfig = schemaRegistry[currentPath] + let matchedParams = {} + + if (!schemaConfig) { + const registeredRoutes = Object.keys(schemaRegistry) + for (const routePattern of registeredRoutes) { + if (!routePattern.includes(":")) { + continue + } + + const matcher = path2regex.match(routePattern, { decode: decodeURIComponent }) + const result = matcher(currentPath) + + if (result) { + schemaConfig = schemaRegistry[routePattern] + matchedParams = result.params + break + } + } + } + + if (!schemaConfig || !schemaConfig[req.method]) { + return next() + } + + req.params = { ...req.params, ...matchedParams } + + const methodConfig = schemaConfig[req.method] + const errorConfig = methodConfig.error || { code: 400, message: "Validation Error" } + + const context = { + method: req.method, + path: req.originalUrl, + ip: req.headers["x-forwarded-for"] || req.socket.remoteAddress + } + + if (methodConfig.headers) { + const headerResult = methodConfig.headers.safeParse(req.headers) + if (!headerResult.success) { + throw new ValidationError(headerResult, errorConfig, context) + } + } + + let dataSchema = null + let dataToValidate = null + let validationType = "body" + + if (req.method === "GET" || req.method === "DELETE") { + dataSchema = methodConfig.query + dataToValidate = req.query + validationType = "query" + } else { + dataSchema = methodConfig.body + dataToValidate = req.body + } + + if (dataSchema) { + const result = dataSchema.safeParse(dataToValidate) + if (!result.success) { + throw new ValidationError(result, errorConfig, context) + } + if (validationType === "query") { + req.query = result.data + } else { + req.body = result.data + } + } + + return next() +}) + +for (const route of routes) { + try { + const router = require(route) + const routePath = loader.computeRoutePath(path.join(__dirname, "routes"), route) + if (router.stack) { + for (const layer of router.stack) { + if (layer.route && layer.route.methods) { + const method = Object.keys(layer.route.methods).join(", ").toUpperCase() + const innerPath = layer.route.path === "/" ? "" : layer.route.path + const mountPrefix = routePath === "/" ? "" : routePath + const fullDisplayPath = mountPrefix + innerPath + logger.log(`${method.cyan} ${fullDisplayPath.cyan.bold} route registered`, ["WEB", "yellow"]) + } + } + } + app.use(routePath, router) + } catch (error) { + logger.error(route, ["WEB", "yellow"]) + logger.error(error.toString(), ["WEB", "yellow"]) + } +} + +app.all(/.*/, (req, res, next) => { + next(new DefaultError(404, `Can't find ${req.originalUrl} on this server!`, null, "NotFound")) +}) + +app.use((err, req, res, next) => { + const statusCode = err.statusCode || err.code || 500 + + logger.error(`Error occured on: ${req.originalUrl.bold}`, ["API", "red"]) + logger.error(err.message, ["API", "red"]) + + if (typeof err.serialize === "function") { + return res.status(statusCode).json(err.serialize()) + } + + return res.status(500).json({ + status: "error", + message: "Internal Server Error" + }) +}) + +app.listen(process.env.WEB_PORT || 3000, () => { + logger.log(`Server listening at port : ${process.env.WEB_PORT.bold || 3000}`, ["WEB", "yellow"]) +}) diff --git a/services/adminService.js b/services/adminService.js new file mode 100644 index 0000000..3f6f369 --- /dev/null +++ b/services/adminService.js @@ -0,0 +1,145 @@ +const userRepository = require("../repositories/userRepository") +const adminRepository = require("../repositories/adminRepository") +const bcrypt = require("bcryptjs") +const { DefaultError } = require("../errors/errors") + +const ADMIN_JWT_SECRET = process.env.ADMIN_JWT_SECRET || "udjJLGCOq7m3NmGpdVLJ@#" + +async function registerAdmin(username, plainPassword, permissions = []) { + const hashedPassword = await bcrypt.hash(plainPassword, 10) + + const result = await adminRepository.createAdmin(username, hashedPassword) + + if (permissions.length > 0) { + for (const perm of permissions) { + await adminRepository.assignPermission(result.id, perm) + } + } + + return { id: result.id, username, message: "Administrateur créé avec succès." } +} + +async function checkAdminAccess(adminId, requiredPermission) { + if (!adminId || !requiredPermission) { + throw new DefaultError(400, "ID administrateur ou permission manquante.") + } + + return await adminRepository.hasPermission(adminId, requiredPermission) +} + +async function changeAdminPassword(adminId, newPlainPassword) { + if (!newPlainPassword || newPlainPassword.length < 6) { + throw new DefaultError(400, "Le mot de passe doit contenir au moins 6 caractères.") + } + + const hashed = await bcrypt.hash(newPlainPassword, 10) + return await adminRepository.updateAdminPassword(adminId, hashed) +} + +async function getAdminProfile(adminId) { + const admin = await adminRepository.getAdminById(adminId) + if (!admin) { + throw new DefaultError(404, "Administrateur introuvable.") + } + + const permissions = await adminRepository.getAdminPermissions(adminId) + + return { + id: admin.id, + username: admin.username, + createdAt: admin.createdAt, + permissions: permissions + } +} + +async function grantPermission(adminId, permissionKey) { + return await adminRepository.assignPermission(adminId, permissionKey) +} + +async function revokePermission(adminId, permissionKey) { + return await adminRepository.revokePermission(adminId, permissionKey) +} + +async function loginAdmin(username, password) { + const admin = await adminRepository.getAdminByUsername(username) + if (!admin) { + throw new DefaultError(403, "Invalid credentials.") + } + + const isMatch = await bcrypt.compare(password, admin.password) + if (!isMatch) { + throw new DefaultError(403, "Invalid credentials.") + } + + const token = jwt.sign( + { id: admin.id, username: admin.username, type: "admin" }, + ADMIN_JWT_SECRET, + { expiresIn: "8h" } + ) + + return { token } +} + +function hasPermission(requiredPermission) { + return async (req, res, next) => { + try { + const authHeader = req.headers.authorization + if (!authHeader || !authHeader.startsWith("Bearer ")) { + throw new DefaultError(401, "Authentification admin requise.") + } + + const token = authHeader.split(" ")[1] + + const decoded = jwt.verify(token, ADMIN_JWT_SECRET) + if (decoded.type !== "admin") { + throw new DefaultError(403, "Invalid token.") + } + + const hasAccess = await adminService.checkAdminAccess(decoded.id, requiredPermission) + if (!hasAccess) { + throw new DefaultError(403, `Missing permission : ${requiredPermission}`) + } + + req.admin = decoded + next() + + } catch (err) { + if (err.name === "JsonWebTokenError") { + return next(new DefaultError(401, "Invalid session.")) + } + next(err) + } + } +} + +async function uploadCape(fileObject, alias = null) { + const buffer = await fs.readFile(fileObject.path) + const hash = crypto.createHash("sha256").update(buffer).digest("hex") + + const existing = await userRepository.getTextureByHash(hash) + if (existing) throw new DefaultError(409, "Cette cape existe déjà.") + + const textureUrl = `/texture/${hash}` + await userRepository.createTexture(crypto.randomUUID(), hash, 'CAPE', textureUrl, alias) + + return { hash, url: textureUrl } +} + +async function deleteGlobalCape(hash) { + const success = await userRepository.deleteTexture(hash) + if (!success) throw new DefaultError(404, "Cape introuvable.") + + return { message: "Texture supprimée globalement." } +} + +module.exports = { + loginAdmin, + uploadCape, + registerAdmin, + getAdminProfile, + grantPermission, + revokePermission, + checkAdminAccess, + changeAdminPassword, + hasPermission, +} \ No newline at end of file diff --git a/services/authService.js b/services/authService.js new file mode 100644 index 0000000..61e5966 --- /dev/null +++ b/services/authService.js @@ -0,0 +1,289 @@ +const jwt = require("jsonwebtoken") +const utils = require("../modules/utils") +const bcrypt = require("bcryptjs") +const crypto = require("node:crypto") +const userRepository = require("../repositories/userRepository") +const authRepository = require("../repositories/authRepository") +const certsManager = require("../modules/certificatesManager") +const { DefaultError } = require("../errors/errors") + +const keys = certsManager.getKeys() +const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/ +const usernameRegex = /^[a-zA-Z0-9_]{3,16}$/ + +async function registerUser({ username, password, email, registrationCountry, preferredLanguage, clientIp }) { + const availability = await checkUsernameAvailability(username) + if (availability.status === "DUPLICATE") { + throw new DefaultError(409, "Username taken.", "ForbiddenOperationException") + } + if (availability.status === "NOT_ALLOWED") { + throw new DefaultError(400, availability.message || "Username invalid.", "InvalidUsernameException") + } + + if (email) { + try { + await authRepository.getUser(email) + throw new DefaultError(409, "E-Mail taken.", "ForbiddenOperationException") + } catch (error) { + if (error.code !== 404) throw error + } + } + + const userRegistration = await authRepository.register(email || "", username, password) + const { uuid } = userRegistration + + const resolvedCountry = registrationCountry || await utils.getRegistrationCountryFromIp(clientIp) + await userRepository.addPropertyToPlayer("registrationCountry", resolvedCountry || "UNKNOWN", uuid) + await userRepository.addPropertyToPlayer("userPreferredLanguage", preferredLanguage || "fr-FR", uuid) + + return { code: 200, message: "User created successfully", uuid } +} + +async function authenticate({ identifier, password, clientToken, requireUser }) { + let userResult + try { + userResult = await authRepository.getUser(identifier, true) + } catch (error) { + if (error.code === 404) { + throw new DefaultError(403, "Invalid credentials. Invalid username or password.", "ForbiddenOperationException") + } + throw error + } + const passwordValidationProcess = await bcrypt.compare(password, userResult.user.password) + if (!passwordValidationProcess) { + throw new DefaultError(403, "Invalid credentials. Invalid username or password.", "ForbiddenOperationException") + } + + delete userResult.user.password + + const $clientToken = clientToken || crypto.randomUUID() + const accessToken = jwt.sign({ + uuid: userResult.user.uuid, + username: userResult.user.username, + clientToken: $clientToken, + }, keys.authenticationKeys.private, { + subject: userResult.user.uuid, + issuer: "LentiaYggdrasil", + expiresIn: "1d", + algorithm: "RS256" + }) + + const clientSessionProcess = await authRepository.insertClientSession(accessToken, $clientToken, userResult.user.uuid) + + const userObject = { + clientToken: clientSessionProcess.clientToken, + accessToken: clientSessionProcess.accessToken, + availableProfiles: [{ + name: userResult.user.username, + id: userResult.user.uuid, + }], + selectedProfile: { + name: userResult.user.username, + id: userResult.user.uuid, + } + } + + if (requireUser) { + try { + const propertiesRequest = await authRepository.getPlayerProperties(userResult.user.uuid) + userObject.user = { + username: userResult.user.username, + properties: propertiesRequest.properties + } + } catch (error) { + if (error.code !== 404) throw error + userObject.user = { + username: userResult.user.username, + properties: [] + } + } + } + + return { + code: 200, + response: userObject + } +} + +async function refreshToken({ previousAccessToken, clientToken, requireUser }) { + let sessionCheck + try { + sessionCheck = await authRepository.getClientSession(previousAccessToken, clientToken) + } catch (error) { + throw new DefaultError(403, "Invalid token or session expired.", "ForbiddenOperationException") + } + + const uuid = sessionCheck.session.uuid + + const userResult = await authRepository.getUser(uuid, true) + delete userResult.user.password + + await authRepository.invalidateClientSession(previousAccessToken, clientToken) + + const $clientToken = clientToken || crypto.randomUUID() + const newAccessToken = jwt.sign({ + uuid: userResult.user.uuid, + username: userResult.user.username, + clientToken: $clientToken, + }, keys.authenticationKeys.private, { + subject: userResult.user.uuid, + issuer: "LentiaYggdrasil", + expiresIn: "1d", + algorithm: "RS256" + }) + + const clientSessionProcess = await authRepository.insertClientSession(newAccessToken, $clientToken, userResult.user.uuid) + + const userObject = { + clientToken: clientSessionProcess.clientToken, + accessToken: clientSessionProcess.accessToken, + selectedProfile: { + name: userResult.user.username, + id: userResult.user.uuid, + } + } + + if (requireUser) { + try { + const propertiesRequest = await authRepository.getPlayerProperties(userResult.user.uuid) + userObject.user = { + username: userResult.user.username, + properties: propertiesRequest.properties + } + } catch (error) { + if (error.code !== 404) throw error + userObject.user = { + username: userResult.user.username, + properties: [] + } + } + } + + return { + code: 200, + response: userObject + } +} + +async function validate({ accessToken, clientToken }) { + if (clientToken !== undefined) { + await authRepository.validateClientSession(accessToken, clientToken) + } else { + await authRepository.validateClientSessionWithoutClientToken(accessToken) + } + return { code: 204 } +} + +async function invalidate({ accessToken, clientToken }) { + await authRepository.invalidateClientSession(accessToken, clientToken) + return { code: 204 } +} + +async function signout({ uuid }) { + await authRepository.revokeAccessTokens(uuid) + return { code: 204 } +} + +async function verifyAccessToken({ accessToken }) { + try { + if (!accessToken) { + throw new DefaultError(400, "Token is missing.") + } + + const decoded = jwt.verify(accessToken, keys.authenticationKeys.public, { + algorithms: ["RS256"], + issuer: "LentiaYggdrasil" + }) + + const clientToken = decoded.clientToken + if (!clientToken) { + throw new DefaultError(403, "Token format invalid (missing clientToken).") + } + + try { + await authRepository.validateClientSession(accessToken, clientToken) + } catch (error) { + throw new DefaultError(401, "Session has been revoked or invalidated.") + } + + return { + code: 200, + user: { + uuid: decoded.sub, + username: decoded.username + }, + session: { + clientToken + } + } + + } catch (error) { + if (error instanceof DefaultError) throw error + + if (error.name === "TokenExpiredError") { + throw new DefaultError(401, "Token has expired.") + } + throw new DefaultError(500, "Internal Verification Error", error.toString()) + } +} + +async function checkUsernameAvailability(username) { + if (!usernameRegex.test(username)) { + return { + code: 200, + status: "NOT_ALLOWED", + message: "Invalid characters or length." + } + } + + try { + await authRepository.getUser(username) + return { + code: 200, + status: "DUPLICATE", + message: "Username is already in use." + } + } catch (error) { + if (error.code !== 404) throw error + } + + const blocklist = await authRepository.getUsernamesRules() + const normalizedUsername = username.toLowerCase() + + for (const entry of blocklist) { + if (entry.type === "literal") { + if (normalizedUsername === entry.value) { + return { + code: 200, + status: "NOT_ALLOWED", + message: "Username is reserved." + } + } + } + else if (entry.type === "regex") { + if (entry.pattern.test(username)) { + return { + code: 200, + status: "NOT_ALLOWED", + message: "Username contains forbidden words." + } + } + } + } + + return { + code: 200, + status: "AVAILABLE" + } +} + +module.exports = { + signout, + validate, + invalidate, + registerUser, + authenticate, + refreshToken, + verifyAccessToken, + checkUsernameAvailability +} \ No newline at end of file diff --git a/services/serverService.js b/services/serverService.js new file mode 100644 index 0000000..6c1c039 --- /dev/null +++ b/services/serverService.js @@ -0,0 +1,39 @@ +const certs = require("../modules/certificatesManager") +const utils = require("../modules/utils") +const package = require("../package.json") + +function getServerMetadata(hostname) { + const keys = certs.getKeys() + const publicKeyPEM = keys.profilePropertyKeys.public + + const serverMeta = { + meta: { + serverName: process.env.SERVER_NAME || "Yggdrasil Server", + implementationName: package.name, + implementationVersion: package.version, + + "feature.legacy_skin_api": utils.isTrueFromDotEnv("SUPPORT_LEGACY_SKIN_API"), + "feature.no_mojang_namespace": utils.isTrueFromDotEnv("SUPPORT_MOJANG_FALLBACK"), + "feature.enable_mojang_anti_features": utils.isTrueFromDotEnv("SUPPORT_MOJANG_TELEMETRY_BLOCKER"), + "feature.enable_profile_key": utils.isTrueFromDotEnv("SUPPORT_PROFILE_KEY"), + "feature.username_check": utils.isTrueFromDotEnv("SUPPORT_ONLY_DEFAULT_USERNAME"), + + links: { + homepage: process.env.HOMEPAGE_URL || `http://${hostname}`, + } + }, + skinDomains: [ + hostname, + `.${hostname}` + ], + signaturePublickey: publicKeyPEM + } + if (utils.isTrueFromDotEnv("SUPPORT_REGISTER")) { + serverMeta.meta.links.register = process.env.REGISTER_ENDPOINT || `http://${hostname}/register` + } + return serverMeta +} + +module.exports = { + getServerMetadata +} diff --git a/services/sessionsService.js b/services/sessionsService.js new file mode 100644 index 0000000..3283cb7 --- /dev/null +++ b/services/sessionsService.js @@ -0,0 +1,212 @@ +const utils = require("../modules/utils") +const authRepository = require("../repositories/authRepository") +const sessionRepository = require("../repositories/sessionsRepository") +const { DefaultError } = require("../errors/errors") + +async function registerLegacySession({ uuid, sessionId }) { + try { + await sessionRepository.insertLegacyClientSessions(sessionId, uuid) + return { code: 200 } + } catch (error) { + if (error instanceof DefaultError) throw error + throw new DefaultError(500, "Internal Server Error", error.toString()) + } +} + +async function validateLegacySession({ name, sessionId }) { + let userResult + try { + userResult = await authRepository.getUser(name) + } catch (error) { + if (error.code === 404) { + throw error + } + throw error + } + + try { + await sessionRepository.validateLegacyClientSession(sessionId, userResult.user.uuid) + return { code: 200 } + } catch (error) { + if (error.code === 404) { + throw new DefaultError(403, "Invalid session.", "ForbiddenOperationException") + } + throw error + } +} + +async function getBlockedServers() { + try { + return await sessionRepository.getBlockedServers() + } catch (error) { + throw new DefaultError(500, "Unable to fetch blocked servers.", error.toString()) + } +} + +async function getProfile({ uuid, unsigned = false }) { + let userResult, $uuid = utils.addDashesToUUID(uuid) + try { + userResult = await authRepository.getUser($uuid, false) + } catch (error) { + if (error.code === 404) { + return { code: 204, message: "User not found" } + } + throw error + } + + const dbUser = userResult.user + const username = dbUser.username + const cleanUuid = dbUser.uuid.replace(/-/g, "") + + const [skinResult, capeResult, actionsResult] = await Promise.all([ + sessionRepository.getActiveSkin(dbUser.uuid).catch(() => ({ data: null })), + sessionRepository.getActiveCape(dbUser.uuid).catch(() => ({ data: null })), + sessionRepository.getProfileActionsList(dbUser.uuid).catch(() => ({ data: [] })) + ]) + + const activeSkin = skinResult.data + const activeCape = capeResult.data + const profileActions = actionsResult.data || [] + + const isSkinBanned = profileActions.includes("USING_BANNED_SKIN") + const hasValidSkin = activeSkin && !isSkinBanned + const hasValidCape = !!activeCape + + const skinNode = hasValidSkin ? { + url: (process.env.TEXTURES_ENDPOINTS || `http://localhost:${process.env.WEB_PORT}/textures`) + activeSkin.url, + metadata: activeSkin.variant === "SLIM" ? { model: "slim" } : undefined + } : undefined + + const capeNode = hasValidCape ? { + url: (process.env.TEXTURES_ENDPOINTS || `http://localhost:${process.env.WEB_PORT}/textures`) + activeCape.url + } : undefined + + const texturesObject = { + ...(skinNode && { SKIN: skinNode }), + ...(capeNode && { CAPE: capeNode }) + } + + const texturePayload = { + timestamp: Date.now(), + profileId: cleanUuid, + profileName: username, + signatureRequired: !unsigned, + textures: texturesObject + } + + const payloadJson = JSON.stringify(texturePayload) + const base64Value = Buffer.from(payloadJson).toString("base64") + + const signature = unsigned ? null : utils.signProfileData(base64Value) + + const propertyNode = { + name: "textures", + value: base64Value, + ...(signature && { signature: signature }) + } + + return { + code: 200, + data: { + id: cleanUuid, + name: username, + properties: [propertyNode], + profileActions: profileActions + } + } +} + +async function joinServer({ accessToken, selectedProfile, clientToken, serverId, ip }) { + try { + await authRepository.validateClientSession(accessToken, clientToken) + } catch (error) { + throw new DefaultError(403, "Invalid access token", "ForbiddenOperationException") + } + + const existingSession = await sessionRepository.getServerSessionByUuid(selectedProfile) + if (existingSession && existingSession.serverId !== serverId) { + throw new DefaultError(403, "Already logged in on another server.", "ForbiddenOperationException") + } + + await sessionRepository.saveServerSession(selectedProfile, accessToken, serverId, ip) + return { code: 204 } +} + +async function hasJoinedServer({ username, serverId, ip }) { + let userResult + try { + userResult = await authRepository.getUser(username, false) + } catch (error) { + if (error.code === 404) return { code: 204, message: "User not found" } + throw error + } + + const { uuid } = userResult.user + const joinCheck = await sessionRepository.getServerSession(uuid, serverId) + + if (joinCheck.code !== 200 || !joinCheck.valid) { + return { code: 204, message: "Join verification failed" } + } + + if (ip && ip.trim() !== "" && joinCheck.ip !== ip) { + return { code: 204, message: "Invalid IP address" } + } + + return await getProfile({ + uuid: uuid, + unsigned: false + }) +} + +async function joinLegacyServer({ name, sessionId, serverId }) { + try { + await validateLegacySession({ name, sessionId }) + } catch (error) { + throw new DefaultError(403, "Bad login", "ForbiddenOperationException") + } + + const userResult = await authRepository.getUser(name) + const uuid = userResult.user.uuid + + await sessionRepository.saveServerSession(uuid, sessionId, serverId, "0.0.0.0") + + return { code: 200, message: "OK" } +} + +async function getActiveSkin({ username }) { + try { + const dbUser = await authRepository.getUser(username) + const activeSkin = await sessionRepository.getActiveSkin(dbUser.user.uuid) + return activeSkin + } catch (error) { + if (!(error instanceof DefaultError)) { + throw new DefaultError(400, "Bad Request", error.toString()) + } + throw error + } +} + +async function getActiveCape({ username }) { + try { + const dbUser = await authRepository.getUser(username) + const activeCape = await sessionRepository.getActiveCape(dbUser.user.uuid) + return activeCape + } catch (error) { + if (!(error instanceof DefaultError)) { + throw new DefaultError(400, "Bad Request", error.toString()) + } + throw error + } +} + +module.exports = { + getProfile, + joinServer, + getActiveCape, + getActiveSkin, + hasJoinedServer, + joinLegacyServer, + getBlockedServers, + registerLegacySession, + validateLegacySession, +} diff --git a/services/userService.js b/services/userService.js new file mode 100644 index 0000000..770b1ae --- /dev/null +++ b/services/userService.js @@ -0,0 +1,568 @@ +const fs = require("node:fs/promises") +const path = require("node:path") +const util = require("node:util") +const bcrypt = require("bcryptjs") +const logger = require("../modules/logger") +const crypto = require("node:crypto") +const ssrfcheck = require("ssrfcheck") +const certsManager = require("../modules/certificatesManager") +const userRepository = require("../repositories/userRepository") +const { DefaultError } = require("../errors/errors") +const generateKeyPairAsync = util.promisify(crypto.generateKeyPair) + +const TEMP_DIR = path.join(process.cwd(), "data", "temp") +const TEXTURES_DIR = path.join(process.cwd(), "data", "textures") + +async function getPlayerProperties(uuid) { + try { + const result = await userRepository.getPlayerProperties(uuid) + return result + } catch (error) { + if (error.code === 404) { + return { code: 200, properties: [] } + } + throw error + } +} + +async function getPlayerProperty(uuid, key) { + return await userRepository.getPlayerProperty(key, uuid) +} + +async function addPlayerProperty(uuid, key, value) { + return await userRepository.addPropertyToPlayer(key, value, uuid) +} + +async function updatePlayerProperty(uuid, key, value) { + return await userRepository.updatePropertyToPlayer(key, value, uuid) +} + +async function deletePlayerProperty(uuid, key) { + return await userRepository.deletePropertyToPlayer(key, uuid) +} + +async function getSettingsSchema() { + const schema = await userRepository.getPlayerSettingsSchema() + return { + code: 200, + schema + } +} + +async function getPreferences(uuid) { + return await userRepository.getPlayerPreferences(uuid) +} + +async function updatePreferences(uuid, updates) { + return await userRepository.updatePlayerPreferences(uuid, updates) +} + +async function getPrivileges(uuid) { + return await userRepository.getPlayerPrivileges(uuid) +} + +async function updatePrivileges(uuid, updates) { + return await userRepository.updatePlayerPrivileges(uuid, updates) +} + +async function banUser(uuid, { reasonKey, reasonMessage, expires }) { + if (!reasonKey) { + throw new DefaultError(400, "A reason key is required to ban a user.") + } + + return await userRepository.banUser(uuid, { + reasonKey, + reasonMessage: reasonMessage || "Banned by operator", + expires + }) +} + +async function unbanUser(uuid) { + return await userRepository.unbanUser(uuid) +} + +async function getPlayerBans(uuid) { + const result = await userRepository.getPlayerBans(uuid) + if (result.code === 204) { + return { code: 200, bans: [] } + } + return result +} + +async function changeUsername(uuid, newName) { + const availability = await authService.checkUsernameAvailability(newName) + if (availability.status === "DUPLICATE") { + throw new DefaultError(409, "Username already taken.", "ForbiddenOperationException") + } + if (availability.status === "NOT_ALLOWED") { + throw new DefaultError(400, availability.message || "Invalid username format.", "InvalidUsernameException") + } + + return await userRepository.changeUsername(uuid, newName) +} + +async function resetSkin(playerUuid) { + const isSteve = Math.random() < 0.5 + const targetHash = isSteve ? STEVE_HASH : ALEX_HASH + const variant = isSteve ? "CLASSIC" : "SLIM" + await userRepository.resetSkin(playerUuid, targetHash, variant) + return { + code: 200, + message: "Skin reset successfully", + model: variant + } +} + +async function hideCape(playerUuid) { + await userRepository.hideCape(playerUuid) + return { + code: 200, + message: "Cape hidden" + } +} + +async function showCape(playerUuid, textureUuid) { + const texture = await userRepository.getTextureByUuid(textureUuid) + if (!texture) { + throw new DefaultError(404, "Cape texture not found in server assets.", "TextureNotFoundException") + } + const ownsCape = await userRepository.checkCapeOwnership(playerUuid, texture.hash) + if (!ownsCape) { + throw new DefaultError(403, "You do not own this cape.", "ForbiddenOperationException") + } + await userRepository.showCape(playerUuid, texture.hash) + + return { + code: 200, + message: "Cape showed" + } +} + +async function getPlayerNameChangeStatus(uuid) { + const player = await userRepository.getPlayerMeta(uuid) + if (!player) { + throw new DefaultError(404, "User not found") + } + const history = await userRepository.getLastNameChange(uuid) + const response = { + changedAt: history ? history.changedAt : player.createdAt, + createdAt: player.createdAt, + nameChangeAllowed: !!player.nameChangeAllowed + } + + return { code: 200, data: response } +} + +async function getPlayerCertificate(uuid) { + const cert = await userRepository.getPlayerCertificate(uuid) + if (cert) { + return { code: 200, data: cert } + } + throw new DefaultError(404, "Certificate not found") +} + +async function savePlayerCertificate(uuid, keys) { + const success = await userRepository.savePlayerCertificate( + uuid, + keys.privateKey, + keys.publicKey, + keys.signatureV2, + keys.expiresAt, + keys.refreshedAfter + ) + + if (success) { + return { code: 200, message: "Certificate saved" } + } + throw new DefaultError(500, "Failed to save certificate") +} + +async function deleteExpiredCertificates(isoDate) { + const count = await userRepository.deleteExpiredCertificates(isoDate) + return { code: 200, deletedCount: count } +} + +async function addProfileAction(uuid, actionCode) { + const added = await userRepository.addProfileAction(uuid, actionCode) + return { + code: 200, + success: true, + added: added + } +} + +async function removeProfileAction(uuid, actionCode) { + const count = await userRepository.removeProfileAction(uuid, actionCode) + return { + code: 200, + deletedCount: count + } +} + +async function getPlayerActions(uuid) { + const actions = await userRepository.getPlayerActions(uuid) + return { + code: 200, + actions: actions + } +} + +async function clearAllPlayerActions(uuid) { + const count = await userRepository.clearAllPlayerActions(uuid) + return { + code: 200, + deletedCount: count + } +} + +async function blockPlayer(blockerUuid, blockedUuid) { + if (blockerUuid === blockedUuid) { + throw new DefaultError(400, "You cannot block yourself.") + } + const changed = await userRepository.blockPlayer(blockerUuid, blockedUuid) + return { code: 200, changed: changed } +} + +async function unblockPlayer(blockerUuid, blockedUuid) { + const changed = await userRepository.unblockPlayer(blockerUuid, blockedUuid) + return { code: 200, changed: changed } +} + +async function getBlockedUuids(blockerUuid) { + const list = await userRepository.getBlockedUuids(blockerUuid) + return { code: 200, data: list } +} + +async function isBlocked(blockerUuid, targetUuid) { + const status = await userRepository.isBlocked(blockerUuid, targetUuid) + return { code: 200, isBlocked: status } +} + +async function getPlayerBanStatus(uuid) { + const result = await userRepository.getPlayerBans(uuid) + if (!result || result.code !== 200 || !result.bans || result.bans.length === 0) { + return { isBanned: false, activeBan: null } + } + + const now = new Date() + const activeBan = result.bans.find(b => !b.expires || new Date(b.expires) > now) + + if (!activeBan) { + return { isBanned: false, activeBan: null } + } + + return { + isBanned: true, + activeBan: { + banId: activeBan.banId, + expires: activeBan.expires, + reason: activeBan.reason, + reasonMessage: activeBan.reasonMessage + } + } +} + +async function fetchOrGenerateCertificate(uuid) { + try { + const cached = await userRepository.getPlayerCertificate(uuid) + if (cached) { + const expiresAtDate = new Date(cached.expiresAt) + if (expiresAtDate > new Date(Date.now() + 60000)) { + return { + code: 200, + data: { + keyPair: { + privateKey: cached.privateKey, + publicKey: cached.publicKey + }, + publicKeySignature: cached.publicKeySignatureV2, + publicKeySignatureV2: cached.publicKeySignatureV2, + expiresAt: cached.expiresAt, + refreshedAfter: cached.refreshedAfter + } + } + } + } + } catch (error) { + if (error.code !== 404 && error.code !== 500) { + logger.warn(`Error fetching cache for ${uuid}:` + error.message, ["Certificate", "yellow"]) + } + } + + const { privateKey, publicKey } = await generateKeyPairAsync("rsa", { + modulusLength: 4096, + publicKeyEncoding: { type: "pkcs1", format: "pem" }, + privateKeyEncoding: { type: "pkcs1", format: "pem" } + }) + + const now = new Date() + const expiresAt = new Date(now.getTime() + 48 * 60 * 60 * 1000).toISOString() + const refreshedAfter = new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString() + const keys = certsManager.getKeys() + const serverPrivateKey = keys.playerCertificateKeys.private + + const signer = crypto.createSign("SHA256") + signer.update(uuid) + signer.update(publicKey) + signer.update(expiresAt) + + const signatureV2 = signer.sign(serverPrivateKey, "base64") + await userRepository.savePlayerCertificate(uuid, privateKey, publicKey, signatureV2, expiresAt, refreshedAfter) + + return { + code: 200, + data: { + keyPair: { + privateKey: privateKey, + publicKey: publicKey + }, + publicKeySignature: signatureV2, + publicKeySignatureV2: signatureV2, + expiresAt: expiresAt, + refreshedAfter: refreshedAfter + } + } +} + +async function bulkLookup(usernames) { + if (!Array.isArray(usernames)) { + throw new DefaultError(400, "Invalid payload. Array of strings expected.") + } + + if (usernames.length > 10) { + throw new DefaultError(400, "Too many usernames provided (max 10).") + } + + if (usernames.length === 0) { + return [] + } + + const users = await userRepository.getUsersByNames(usernames) + + return users.map(u => ({ + id: u.uuid.replace(/-/g, ""), + name: u.username + })) +} + +async function getLegacyProfile(username) { + const user = await userRepository.getUuidAndUsername(username) + + if (!user) { + return null + } + + return { + id: user.uuid.replace(/-/g, ""), + name: user.username + } +} + +async function getNameUUIDs(username, dateInput) { + let profile + + if (!dateInput || dateInput == 0) { + profile = await userRepository.getProfileByUsername(username) + } else { + const targetDate = new Date(Number(dateInput)).toISOString() + profile = await userRepository.getProfileByHistory(username, targetDate) + } + + if (!profile) { + throw new DefaultError(404, "Couldn't find any profile with that name") + } + + return { + code: 200, + data: { + id: profile.uuid.replace(/-/g, ""), + name: profile.username + } + } +} + +async function getPlayerUsernamesHistory(uuid) { + const dashedUuid = utils.addDashesToUUID(uuid) + const history = await userRepository.getNameHistory(dashedUuid) + if (!history || history.length === 0) { + throw new DefaultError(404, "User not found") + } + + return history.map(entry => { + const cleanEntry = { + name: entry.username + } + + if (entry.changedAt) { + const dateObj = new Date(entry.changedAt) + if (!isNaN(dateObj.getTime())) { + cleanEntry.changedToAt = dateObj.getTime() + } + } + return cleanEntry + }) +} + +async function registerTexture(hash, type, url, alias = null) { + const existingTexture = await userRepository.getTextureByHash(hash) + + if (existingTexture) { + return { + code: 200, + textureUuid: existingTexture.uuid, + isNew: false + } + } + + const newUuid = crypto.randomUUID() + await userRepository.createTexture(newUuid, hash, type, url, alias) + + return { + code: 201, + textureUuid: newUuid, + isNew: true + } +} + +async function uploadSkin(uuid, fileObject, variant) { + if (!fileObject || !fileObject.path) { + throw new DefaultError(400, "No skin file provided.") + } + + const tempPath = fileObject.path + let buffer + + try { + buffer = await fs.readFile(tempPath) + if (buffer.length < 8 || !buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]))) { + throw new DefaultError(400, "Invalid file format. Only PNG is allowed.") + } + + try { + const width = buffer.readUInt32BE(16) + const height = buffer.readUInt32BE(20) + if (width !== 64 || (height !== 64 && height !== 32)) { + throw new DefaultError(400, `Invalid skin dimensions. Got ${width}x${height}, expected 64x64 or 64x32.`) + } + } catch (e) { + throw new DefaultError(400, "Could not read image dimensions.") + } + + const hash = crypto.createHash("sha256").update(buffer).digest("hex") + const existingTexture = await userRepository.getTextureByHash(hash) + + if (!existingTexture) { + const subDir = hash.substring(0, 2) + const targetDir = path.join(TEXTURES_DIR, subDir) + const targetPath = path.join(targetDir, hash) + + await fs.mkdir(targetDir, { recursive: true }) + await fs.writeFile(targetPath, buffer) + + const newTextureUuid = crypto.randomUUID() + const textureUrl = `texture/${hash}` + await userRepository.createTexture(newTextureUuid, hash, 'SKIN', textureUrl, null) + } + + const validVariant = (variant === "slim") ? "slim" : "classic" + await userRepository.setSkin(uuid, hash, validVariant) + + return { code: 200, message: "Skin uploaded successfully" } + + } catch (error) { + throw error + } finally { + await fs.unlink(tempPath).catch(() => {}) + } +} + +async function uploadSkinFromUrl(uuid, url, variant) { + if (!url) throw new DefaultError(400, "Missing 'url' parameter.") + if (ssrfcheck.isSSRFSafeURL(url)) throw new DefaultError(400, "Bad request", null) + + let buffer + try { + const response = await fetch(url) + if (!response.ok) throw new Error("Fetch failed") + const arrayBuffer = await response.arrayBuffer() + buffer = Buffer.from(arrayBuffer) + } catch (err) { + throw new DefaultError(400, "Could not download skin from the provided URL.") + } + + const tempFileName = crypto.randomBytes(16).toString("hex") + const tempPath = path.join(TEMP_DIR, tempFileName) + + await fs.mkdir(TEMP_DIR, { recursive: true }) + await fs.writeFile(tempPath, buffer) + + return await uploadSkin(uuid, { path: tempPath }, variant) +} + +async function changePassword(uuid, newPlainPassword) { + if (!newPlainPassword || newPlainPassword.length < 6) { + throw new DefaultError(400, "Password is too short. Minimum 6 characters.") + } + + const salt = await bcrypt.genSalt(10) + const hashedPassword = await bcrypt.hash(newPlainPassword, salt) + + return await userRepository.updatePassword(uuid, hashedPassword) +} + +async function grantCape(uuid, hash) { + const texture = await userRepository.getTextureByHash(hash) + if (!texture) { + throw new DefaultError(404, "Texture de cape introuvable dans la base globale.") + } + + return await userRepository.addCapeToPlayer(uuid, hash) +} + +async function removeCape(uuid, hash) { + return await userRepository.removeCapeFromPlayer(uuid, hash) +} + +module.exports = { + banUser, + showCape, + hideCape, + unbanUser, + resetSkin, + isBlocked, + grantCape, + bulkLookup, + uploadSkin, + removeCape, + blockPlayer, + getNameUUIDs, + unblockPlayer, + getPrivileges, + getPlayerBans, + changeUsername, + getPreferences, + changePassword, + getBlockedUuids, + registerTexture, + getLegacyProfile, + addProfileAction, + getPlayerActions, + updatePrivileges, + getPlayerProperty, + addPlayerProperty, + updatePreferences, + uploadSkinFromUrl, + getSettingsSchema, + getPlayerBanStatus, + removeProfileAction, + getPlayerProperties, + updatePlayerProperty, + deletePlayerProperty, + getPlayerCertificate, + savePlayerCertificate, + clearAllPlayerActions, + getPlayerNameChangeStatus, + getPlayerUsernamesHistory, + deleteExpiredCertificates, + fetchOrGenerateCertificate, +} \ No newline at end of file