From b4485b1e38fa735a8266d5165c57926fe98baf98 Mon Sep 17 00:00:00 2001 From: BaileyCodes Date: Fri, 27 Nov 2026 22:15:37 -0600 Subject: [PATCH] Archive eaglerproxy (server, 1.8.8, clean) --- eaglerproxy/PROVENANCE.json | 35 + eaglerproxy/README.md | 10 + eaglerproxy/files/.config/build.sh | 33 + eaglerproxy/files/.gitignore | 4 + eaglerproxy/files/.replit | 28 + eaglerproxy/files/README.md | 104 + .../example_plugins/AutokickPlugin/config.js | 4 + .../example_plugins/AutokickPlugin/index.js | 38 + .../AutokickPlugin/metadata.json | 14 + .../example_plugins/ExamplePlugin/index.js | 2 + .../ExamplePlugin/metadata.json | 9 + .../files/example_plugins/proxy-shimmer.js | 34 + eaglerproxy/files/package-lock.json | 2296 +++++++++++++++++ eaglerproxy/files/package.json | 34 + eaglerproxy/files/replit.nix | 10 + eaglerproxy/files/replit_launch.sh | 2 + eaglerproxy/files/replit_runtime/config.js | 9 + eaglerproxy/files/replit_runtime/index.js | 147 ++ eaglerproxy/files/replit_runtime/package.json | 5 + eaglerproxy/files/src/config.ts | 54 + eaglerproxy/files/src/globals.d.ts | 16 + eaglerproxy/files/src/index.ts | 32 + eaglerproxy/files/src/launcher_types.ts | 65 + eaglerproxy/files/src/logger.ts | 95 + eaglerproxy/files/src/meta.ts | 11 + eaglerproxy/files/src/plugins/DummyFile.ts | 1 + .../src/plugins/EagProxyAAS/CustomAuthflow.ts | 206 ++ .../files/src/plugins/EagProxyAAS/auth.ts | 69 + .../plugins/EagProxyAAS/auth_thealtening.ts | 26 + .../files/src/plugins/EagProxyAAS/commands.ts | 302 +++ .../files/src/plugins/EagProxyAAS/config.ts | 12 + .../files/src/plugins/EagProxyAAS/index.ts | 143 + .../src/plugins/EagProxyAAS/metadata.json | 34 + .../plugins/EagProxyAAS/service/endpoints.ts | 173 ++ .../files/src/plugins/EagProxyAAS/types.ts | 51 + .../files/src/plugins/EagProxyAAS/utils.ts | 1021 ++++++++ eaglerproxy/files/src/proxy/BungeeUtil.ts | 101 + eaglerproxy/files/src/proxy/Chat.ts | 57 + eaglerproxy/files/src/proxy/Constants.ts | 17 + eaglerproxy/files/src/proxy/Enums.ts | 71 + eaglerproxy/files/src/proxy/Motd.ts | 114 + eaglerproxy/files/src/proxy/Packet.ts | 44 + eaglerproxy/files/src/proxy/Player.ts | 372 +++ eaglerproxy/files/src/proxy/Protocol.ts | 100 + eaglerproxy/files/src/proxy/Proxy.ts | 412 +++ eaglerproxy/files/src/proxy/Util.ts | 196 ++ .../files/src/proxy/databases/DiskDB.ts | 53 + .../files/src/proxy/packets/CSLoginPacket.ts | 57 + .../files/src/proxy/packets/CSReadyPacket.ts | 17 + .../src/proxy/packets/CSSetSkinPacket.ts | 70 + .../src/proxy/packets/CSUsernamePacket.ts | 31 + .../src/proxy/packets/SCDisconnectPacket.ts | 37 + .../src/proxy/packets/SCIdentifyPacket.ts | 48 + .../files/src/proxy/packets/SCReadyPacket.ts | 17 + .../src/proxy/packets/SCSyncUuidPacket.ts | 33 + .../proxy/packets/channel/CSChannelMessage.ts | 32 + .../proxy/packets/channel/SCChannelMessage.ts | 32 + .../proxy/pluginLoader/PluginLoaderTypes.ts | 68 + .../src/proxy/pluginLoader/PluginManager.ts | 251 ++ .../src/proxy/ratelimit/BucketRatelimiter.ts | 129 + .../ExponentialBackoffRequestController.ts | 63 + .../proxy/ratelimit/ProxyRatelimitManager.ts | 21 + .../files/src/proxy/skins/EaglerSkins.ts | 192 ++ .../files/src/proxy/skins/ImageEditor.ts | 253 ++ .../files/src/proxy/skins/SkinServer.ts | 146 ++ eaglerproxy/files/tsconfig.json | 15 + 66 files changed, 8178 insertions(+) create mode 100644 eaglerproxy/PROVENANCE.json create mode 100644 eaglerproxy/README.md create mode 100644 eaglerproxy/files/.config/build.sh create mode 100644 eaglerproxy/files/.gitignore create mode 100644 eaglerproxy/files/.replit create mode 100644 eaglerproxy/files/README.md create mode 100644 eaglerproxy/files/example_plugins/AutokickPlugin/config.js create mode 100644 eaglerproxy/files/example_plugins/AutokickPlugin/index.js create mode 100644 eaglerproxy/files/example_plugins/AutokickPlugin/metadata.json create mode 100644 eaglerproxy/files/example_plugins/ExamplePlugin/index.js create mode 100644 eaglerproxy/files/example_plugins/ExamplePlugin/metadata.json create mode 100644 eaglerproxy/files/example_plugins/proxy-shimmer.js create mode 100644 eaglerproxy/files/package-lock.json create mode 100644 eaglerproxy/files/package.json create mode 100644 eaglerproxy/files/replit.nix create mode 100644 eaglerproxy/files/replit_launch.sh create mode 100644 eaglerproxy/files/replit_runtime/config.js create mode 100644 eaglerproxy/files/replit_runtime/index.js create mode 100644 eaglerproxy/files/replit_runtime/package.json create mode 100644 eaglerproxy/files/src/config.ts create mode 100644 eaglerproxy/files/src/globals.d.ts create mode 100644 eaglerproxy/files/src/index.ts create mode 100644 eaglerproxy/files/src/launcher_types.ts create mode 100644 eaglerproxy/files/src/logger.ts create mode 100644 eaglerproxy/files/src/meta.ts create mode 100644 eaglerproxy/files/src/plugins/DummyFile.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/CustomAuthflow.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/auth.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/auth_thealtening.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/commands.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/config.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/index.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/types.ts create mode 100644 eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts create mode 100644 eaglerproxy/files/src/proxy/BungeeUtil.ts create mode 100644 eaglerproxy/files/src/proxy/Chat.ts create mode 100644 eaglerproxy/files/src/proxy/Constants.ts create mode 100644 eaglerproxy/files/src/proxy/Enums.ts create mode 100644 eaglerproxy/files/src/proxy/Motd.ts create mode 100644 eaglerproxy/files/src/proxy/Packet.ts create mode 100644 eaglerproxy/files/src/proxy/Player.ts create mode 100644 eaglerproxy/files/src/proxy/Protocol.ts create mode 100644 eaglerproxy/files/src/proxy/Proxy.ts create mode 100644 eaglerproxy/files/src/proxy/Util.ts create mode 100644 eaglerproxy/files/src/proxy/databases/DiskDB.ts create mode 100644 eaglerproxy/files/src/proxy/packets/CSLoginPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/CSReadyPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/CSSetSkinPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/CSUsernamePacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/SCDisconnectPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/SCIdentifyPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/SCReadyPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/SCSyncUuidPacket.ts create mode 100644 eaglerproxy/files/src/proxy/packets/channel/CSChannelMessage.ts create mode 100644 eaglerproxy/files/src/proxy/packets/channel/SCChannelMessage.ts create mode 100644 eaglerproxy/files/src/proxy/pluginLoader/PluginLoaderTypes.ts create mode 100644 eaglerproxy/files/src/proxy/pluginLoader/PluginManager.ts create mode 100644 eaglerproxy/files/src/proxy/ratelimit/BucketRatelimiter.ts create mode 100644 eaglerproxy/files/src/proxy/ratelimit/ExponentialBackoffRequestController.ts create mode 100644 eaglerproxy/files/src/proxy/ratelimit/ProxyRatelimitManager.ts create mode 100644 eaglerproxy/files/src/proxy/skins/EaglerSkins.ts create mode 100644 eaglerproxy/files/src/proxy/skins/ImageEditor.ts create mode 100644 eaglerproxy/files/src/proxy/skins/SkinServer.ts create mode 100644 eaglerproxy/files/tsconfig.json diff --git a/eaglerproxy/PROVENANCE.json b/eaglerproxy/PROVENANCE.json new file mode 100644 index 0000000..33d9a13 --- /dev/null +++ b/eaglerproxy/PROVENANCE.json @@ -0,0 +1,35 @@ +{ + "slug": "eaglerproxy", + "name": "EaglerProxy", + "category": "server", + "mc_version": "1.8.8", + "author": "WorldEditAxe", + "license": "unknown", + "upstream_ref": "v1.1.0", + "sha256": "a8231150ab184f0936d8e1292c4c3ccbdcb9da55edb65ef8b4572cac787aeb1f", + "size": 300841, + "storage": { + "git_path": null, + "fs_url": null + }, + "play": null, + "sources": [ + { + "url": "https://github.com/WorldEditAxe/eaglerproxy", + "retrieved_at": "2026-11-28T03:12:00Z", + "type": "upstream", + "notes": "Official upstream repository" + } + ], + "vetting": { + "verdict": "clean", + "tools": [ + "vet-static.mjs", + "virustotal-hash" + ], + "date": "2026-11-28", + "notes": "Static scan: 0 flagged patterns across 64 files; VirusTotal hash lookup: 0 detections.", + "reviewer": "vet-static (automated)" + }, + "large_files_omitted_from_git": [] +} diff --git a/eaglerproxy/README.md b/eaglerproxy/README.md new file mode 100644 index 0000000..03c9e34 --- /dev/null +++ b/eaglerproxy/README.md @@ -0,0 +1,10 @@ +# EaglerProxy + +Standalone TypeScript WebSocket reverse proxy enabling Eaglercraft web clients to connect to standard vanilla Minecraft servers. + +- **Archive page:** https://archive.eaglercraft.tech/entries/eaglerproxy.html +- **MC Version:** 1.8.8 +- **Author:** WorldEditAxe +- **License:** unknown +- **SHA-256:** `a8231150ab184f0936d8e1292c4c3ccbdcb9da55edb65ef8b4572cac787aeb1f` +- **Vetting:** clean (2026-11-28) diff --git a/eaglerproxy/files/.config/build.sh b/eaglerproxy/files/.config/build.sh new file mode 100644 index 0000000..8ce763d --- /dev/null +++ b/eaglerproxy/files/.config/build.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +echo "installing dependencies..." +npm install + +echo "compiling eaglerproxy, please wait... " +echo "this may take a while when you first compile the proxy, or when the proxy has to be recompiled (usually due to modification of anything in the src folder, including config.ts)" +echo "after the initial compile, consequent startups will be a lot more faster and snappier" + +set +e + +cd ~/$REPL_SLUG/replit_runtime +node ./index.js +exit_code=$? + +if [ $exit_code -eq 0 ]; then + set -e + echo "detected that recompilation is not required, skipping and directly launching..." +elif [ $exit_code -eq 2 ]; then + set -e + echo "recompiling proxy..." + rm -rf .build + mkdir -p ./.build + cd ~/$REPL_SLUG/ + npm install typescript + npx tsc || true # work around dep compile failure + echo "finished compiling, launching..." +else + echo "received non-zero exit code ($?), exiting!" + set -e + exit 1 +fi + diff --git a/eaglerproxy/files/.gitignore b/eaglerproxy/files/.gitignore new file mode 100644 index 0000000..3572fbe --- /dev/null +++ b/eaglerproxy/files/.gitignore @@ -0,0 +1,4 @@ +node_modules +build +.sourcehash +.DS_Store diff --git a/eaglerproxy/files/.replit b/eaglerproxy/files/.replit new file mode 100644 index 0000000..d388b4f --- /dev/null +++ b/eaglerproxy/files/.replit @@ -0,0 +1,28 @@ +run = "chmod u+x ./replit_launch.sh && ./replit_launch.sh" +hidden = [".build", ".config"] +compile = "chmod u+x ./.config/build.sh && ./.config/build.sh" + +[packager] +language = "nodejs" + +[packager.features] +enabledForHosting = false +packageSearch = true +guessImports = true + +[nix] +channel = "stable-22_11" + +[gitHubImport] +requiredFiles = [".replit", "replit.nix", ".config"] + +[languages] + +[languages.typescript] +pattern = "**/{*.ts,*.js,*.tsx,*.jsx}" + +[languages.typescript.languageServer] +start = "typescript-language-server --stdio" + +[deployment] +run = ["sh", "-c"] diff --git a/eaglerproxy/files/README.md b/eaglerproxy/files/README.md new file mode 100644 index 0000000..9ca7791 --- /dev/null +++ b/eaglerproxy/files/README.md @@ -0,0 +1,104 @@ +# EaglerProxy + + +A standalone reimplementation of EaglercraftX's bungee plugin written in TypeScript, with plugin support. + +_Working for latest EaglercraftX client version as of `3/12/2025`_ + +## Known Issues + +- [EagProxyAAS] Player is missing skin when connected to server + - Due to Eaglercraft's skin system and how it works, forcing skins onto the client is impossible (from what I know so far). This is only a client-sided bug/glitch - others will only see your Mojang/Minecraft account skin and cape. + +## Installing and Running + +This assumes that you have [Node.js](https://nodejs.org/en) LTS or higher installed on your computer, and that you have basic Git and CLI (command line) knowledge. + +1. Clone/download this repository. +2. Modify and configure `config.ts` to your liking. +3. Install TypeScript and required dependencies (`npm i -g typescript` and `npm i`). +4. Compile the TypeScript code into normal JavaScript code (`tsc`). +5. Go into the `build` directory, and run `node index.js`. + +### Important: For non-traditional runtime environments + +For the most part, this proxy (and its dependencies) transpiles to pure JavaScript, and does not require anything more than a full implementation of the Node.js API (with the exception of node-gyp/native support). _Crypto support is required for the proxy to run._ +**If you are running the proxy through either Termux or CodeSandbox's on-device runtime:** + +1. Uninstall `sharp`, and ensure that `jimp` is installed. +2. Edit `config.ts` and set `adapter.useNatives` to `false`. + +The above steps can solve any issues where the proxy immediately crashes with a segfault/illegal instruction error. + +## Plugins + +As of right now, there only exists one plugin: EagProxyAAS (read below for more information). + +### EagProxyAAS + +EagProxyAAS aims to allow any Eaglercraft client to connect to a normal 1.8.9 Minecraft server, provided that players own a legitimate Minecraft Java copy. Although basic mitigations againt this exist in the plugin, **if you are hosting an instance of this proxy, please take steps to ensure that the proxy cannot access any internal IPs/hostnames as to prevent and mitigate the risk of network enumeration.** + +#### Client Support + +EagPAAS allows URL parameters to be passed to the proxy in the WebSocket server URL to supply information about the target server, such as the server IP, port, and method of authentication. +Example: `ws://example.com/?ip=example.com&port=25565&authType=[THEALTENING|ONLINE|OFFLINE]` + +#### `vanilla://` URL support + +A client-sided, Eaglercraft client-agnostic JavaScript shim that adds support for the custom `vanilla://` URL server protocol through URL rewriting is available in `example_plugins/proxy-shimmer.js`. An EaglerProxy server instance running the EagPAAS plugin is required. +Format (`[]` are optional): `vanilla[+online/+offline/+altening]://hostname[:port]` (`port` defaults to `25565`) + +#### I don't want to use this plugin! + +Remove all the folders in `src/plugins`. + +#### IMPORTANT: READ ME BEFORE USING + +EaglerProxy and EagProxyAAS: + +- is compatible with EaglercraftX and uses its handshake system, +- intercepts and reads Minecraft packet traffic between you and the server on the other end (necessary for functionality), +- only uses login data to authenticate with vanilla Minecraft servers, +- and is open source and safe to use. + +EaglerProxy and EagProxyAAS does NOT: + +- include any Microsoft/Mojang code, +- store or otherwise use authentication data for any other purpose as listed on the README, + - Unmodified versions will not maliciously handle your login data, although a modified version has the ability to do so. Only use trusted and unmodified versions of both this plugin and proxy. +- and intentionally put your account at risk. + +### Disclaimer + +The proxy's software utilizes its own plugin API written in JavaScript, rather than BungeeCord's plugin API. For this reason, plugins written for the official BungeeCord plugin will **not** work on this proxy. Below are some instructions for making your very own EaglerProxy plugin. +_Refer to `src/plugins/EagProxyAAS` for an example plugin._ +Each and every EaglerProxy plugin consists of two parts: + +- an entry point JavaScript file (this file is ran when the plugin is loaded) +- a `metadata.json` metadata file + +Below is a breakdown of everything inside of `metadata.json`: + +``` +{ + "name": "Example Plugin", + "id": "examplePlugin", + "version": "1.0.0", + "entry_point": "index.js", + "requirements": [{ id: "otherPlugin", version: "1.0.0" }], + "incompatibilities": [{ id: "someOtherPlugin", version: "2.0.0" }], + "load_after": ["otherPlugin"] +} +``` + +As of right now, there exists no API reference. Please refer to the preinstalled plugin for details regarding API usage. + +## Reporting Issues + +**NOTE:** Issues asking for help will be converted into discussions. You are expected to have **thoroughly** read all documentation prior to asking for help, and expect no help if you have not done so. + +- Security-related bugs/issues: Directly contact me on Discord (check my profile). +- Non-security-related bugs/issues: Open a new issue, with the following: + - Bug description + - Affected versions + - Reproduction steps (optional if you can't find) diff --git a/eaglerproxy/files/example_plugins/AutokickPlugin/config.js b/eaglerproxy/files/example_plugins/AutokickPlugin/config.js new file mode 100644 index 0000000..1a924a0 --- /dev/null +++ b/eaglerproxy/files/example_plugins/AutokickPlugin/config.js @@ -0,0 +1,4 @@ +export const config = { + bindInternalServerPort: 25569, + bindInternalServerIp: "127.0.0.1", +}; diff --git a/eaglerproxy/files/example_plugins/AutokickPlugin/index.js b/eaglerproxy/files/example_plugins/AutokickPlugin/index.js new file mode 100644 index 0000000..a7b0d50 --- /dev/null +++ b/eaglerproxy/files/example_plugins/AutokickPlugin/index.js @@ -0,0 +1,38 @@ +import metadata from "./metadata.json" assert { type: "json" }; +import { createServer } from "minecraft-protocol"; +import { config } from "./config.js"; +const PluginManager = PLUGIN_MANAGER; +const Logger = PluginManager.Logger; +const Enums = PluginManager.Enums; +const Chat = PluginManager.Chat; +const Constants = PluginManager.Constants; +const Motd = PluginManager.Motd; +const Player = PluginManager.Player; +const MineProtocol = PluginManager.MineProtocol; +const EaglerSkins = PluginManager.EaglerSkins; +const Util = PluginManager.Util; +const logger = new Logger("AutoKicker"); +logger.info(`Starting ${metadata.name} v${metadata.version}...`); +logger.info(`(internal server port: ${config.bindInternalServerPort}, internal server IP: ${config.bindInternalServerPort})`); +logger.info("Starting internal server..."); +let server = createServer({ + host: config.bindInternalServerIp, + port: config.bindInternalServerPort, + motdMsg: `${Enums.ChatColor.GOLD}EaglerProxy as a Service`, + "online-mode": false, + version: "1.8.9", +}); +server.on("login", (client) => { + logger.info(`Client ${client.username} has connected to the dummy server.`); + client.write("kick_disconnect", { + reason: "NO", + }); +}); +logger.info("Redirecting backend server IP... (this is required for the plugin to function)"); +CONFIG.adapter.server = { + host: config.bindInternalServerIp, + port: config.bindInternalServerPort, +}; +CONFIG.adapter.motd = { + l1: Enums.ChatColor.RED + "Server Under Maintenance", +}; diff --git a/eaglerproxy/files/example_plugins/AutokickPlugin/metadata.json b/eaglerproxy/files/example_plugins/AutokickPlugin/metadata.json new file mode 100644 index 0000000..62e992e --- /dev/null +++ b/eaglerproxy/files/example_plugins/AutokickPlugin/metadata.json @@ -0,0 +1,14 @@ +{ + "name": "AutoKick", + "id": "autokick", + "version": "1.2.0", + "entry_point": "index.js", + "load_after": [], + "requirements": [], + "incompatibilities": [ + { + "id": "eagpaas", + "version": "^0.0.0" + } + ] +} diff --git a/eaglerproxy/files/example_plugins/ExamplePlugin/index.js b/eaglerproxy/files/example_plugins/ExamplePlugin/index.js new file mode 100644 index 0000000..2152e93 --- /dev/null +++ b/eaglerproxy/files/example_plugins/ExamplePlugin/index.js @@ -0,0 +1,2 @@ +const logger = new PLUGIN_MANAGER.Logger("ExamplePlugin"); +logger.info("Hi!"); diff --git a/eaglerproxy/files/example_plugins/ExamplePlugin/metadata.json b/eaglerproxy/files/example_plugins/ExamplePlugin/metadata.json new file mode 100644 index 0000000..825af5d --- /dev/null +++ b/eaglerproxy/files/example_plugins/ExamplePlugin/metadata.json @@ -0,0 +1,9 @@ +{ + "name": "Example Plugin", + "id": "examplePlugin", + "version": "1.0.0", + "entry_point": "index.js", + "requirements": [], + "incompatibilities": [], + "load_after": [] +} diff --git a/eaglerproxy/files/example_plugins/proxy-shimmer.js b/eaglerproxy/files/example_plugins/proxy-shimmer.js new file mode 100644 index 0000000..f6f8584 --- /dev/null +++ b/eaglerproxy/files/example_plugins/proxy-shimmer.js @@ -0,0 +1,34 @@ +const oldWs = globalThis.WebSocket; +const route = "ws://localhost:8080"; // Replace with your proxy URL +const transformUrl = (url) => { + let { host: ip, port, protocol, searchParams } = new URL(url); + port = port || 25565; + let proto = null, + token = null; + if (protocol) { + if (protocol === "vanilla+offline:") { + proto = "&authType=OFFLINE"; + } else if (protocol === "vanilla+online:") { + proto = "&authType=ONLINE"; + } else if (protocol === "vanilla+altening:") { + proto = "&authType=THEALTENING"; + } + } + return `${route}/?ip=${ip}&port=${port}${proto || ""}`; +}; + +class ShimmedWebSocket extends oldWs { + constructor(url, ...args) { + if (url.startsWith("ws://") || url.startsWith("wss://")) { + const trimmedUrl = url.startsWith("wss://") ? url.substring(6) : url.substring(5); + if (trimmedUrl.startsWith("vanilla://") || trimmedUrl.startsWith("vanilla+offline://") || trimmedUrl.startsWith("vanilla+online://") || trimmedUrl.startsWith("vanilla+altening://")) { + const transformedUrl = transformUrl(trimmedUrl); + console.log(`Using proxy for vanilla URL: ${transformedUrl}`); + url = transformedUrl; + } + } + super(url, args); + } +} + +globalThis.WebSocket = ShimmedWebSocket; diff --git a/eaglerproxy/files/package-lock.json b/eaglerproxy/files/package-lock.json new file mode 100644 index 0000000..bea59ad --- /dev/null +++ b/eaglerproxy/files/package-lock.json @@ -0,0 +1,2296 @@ +{ + "name": "eaglerproxy", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "eaglerproxy", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@thi.ng/leb128": "3.0.5", + "@types/node": "18.11.18", + "@types/semver": "7.3.13", + "@types/sharp": "0.31.1", + "@types/ws": "8.5.4", + "chalk": "5.2.0", + "dotenv": "16.0.3", + "minecraft-protocol": "^1.26.5", + "node-fetch": "3.3.1", + "parse-domain": "7.0.1", + "prismarine-auth": "^2.7.0", + "prismarine-block": "1.16.3", + "prismarine-chunk": "1.33.0", + "prismarine-registry": "1.6.0", + "semver": "^7.6.3", + "sharp": "^0.33.5", + "ws": "^8.18.1" + } + }, + "node_modules/@azure/msal-common": { + "version": "14.16.0", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-14.16.0.tgz", + "integrity": "sha512-1KOZj9IpcDSwpNiQNjt0jDYZpQvNZay7QAEi/5DLubay40iGYtLzya/jbjRPLyOTZhEKyL1MzPuw2HqBCjceYA==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-node": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-2.16.2.tgz", + "integrity": "sha512-An7l1hEr0w1HMMh1LU+rtDtqL7/jw74ORlc9Wnh06v7TU/xpG39/Zdr1ZJu3QpjUfKJ+E0/OXMW8DRSWTlh7qQ==", + "license": "MIT", + "dependencies": { + "@azure/msal-common": "14.16.0", + "jsonwebtoken": "^9.0.0", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.3.1.tgz", + "integrity": "sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.2.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@thi.ng/api": { + "version": "8.11.22", + "resolved": "https://registry.npmjs.org/@thi.ng/api/-/api-8.11.22.tgz", + "integrity": "sha512-SbgnYcuyIKvJF+bdpFNZJxggYa6wBt7xh4OjWZwvmbZvibrjvk4xwLaJ8vm/bJoBYK/Oe631CApssa6kumZeNg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/arrays": { + "version": "2.10.19", + "resolved": "https://registry.npmjs.org/@thi.ng/arrays/-/arrays-2.10.19.tgz", + "integrity": "sha512-wC1Jkvej8zDfSXZmIGp6qMg452mjt4BExMWSaVqaLbMKYszGLgMHJAa8PTUfHrK5A2wQXn35uZwpVbWd+jeubA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22", + "@thi.ng/checks": "^3.7.2", + "@thi.ng/compare": "^2.4.14", + "@thi.ng/equiv": "^2.1.78", + "@thi.ng/errors": "^2.5.28", + "@thi.ng/random": "^4.1.13" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/binary": { + "version": "3.4.45", + "resolved": "https://registry.npmjs.org/@thi.ng/binary/-/binary-3.4.45.tgz", + "integrity": "sha512-VsLh3/zVWk+lquCDw90kIhZdS+VqBeSQyK29KVW66rQ7JAGn1glDhJuaqrucK/NEGnXmqxJfZqJdcEEJsn7M/Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/checks": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/@thi.ng/checks/-/checks-3.7.2.tgz", + "integrity": "sha512-FGFHQrLOUKxLoNQfaoVKW8xBhFNaxtV0QqREbxYgnpCg8WgX5O8dU/T212bVTOMe0GSzqCkjEs3/BmPb4lxW5Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/compare": { + "version": "2.4.14", + "resolved": "https://registry.npmjs.org/@thi.ng/compare/-/compare-2.4.14.tgz", + "integrity": "sha512-w/Bu2kNWVM94/BYYTB7QdNrd8UEKz/Wfv6w6ZZjdTGJ/69MrT+8m6jqnCeloD+WjkQ3vsfexLhRUmOft+fTrzQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/compose": { + "version": "3.0.25", + "resolved": "https://registry.npmjs.org/@thi.ng/compose/-/compose-3.0.25.tgz", + "integrity": "sha512-PAni1jk2b444GwGM+GLs++xeuOZ3OzJ6bVW+xr2D6iutLuqHsySFN2v44yTaWSVf1jxP0yqHla8en84b5ko92A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22", + "@thi.ng/errors": "^2.5.28" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/equiv": { + "version": "2.1.78", + "resolved": "https://registry.npmjs.org/@thi.ng/equiv/-/equiv-2.1.78.tgz", + "integrity": "sha512-dEyGSzf/62Fv9X9swfqFfsB2/zWOQK+ItlwIarUXWxijYUIw0smCca4oix+eWs4/2QnESV1p0I1Jp66d8Psydg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/errors": { + "version": "2.5.28", + "resolved": "https://registry.npmjs.org/@thi.ng/errors/-/errors-2.5.28.tgz", + "integrity": "sha512-ZYFe7Hq9Oh2e2mOxlTc22/btCkozb0tm0xNAKK5kOoU8BxByh2fnN/qK1rHOfx11TW6EYtMpfEMQDdjmclOwjw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/hex": { + "version": "2.3.66", + "resolved": "https://registry.npmjs.org/@thi.ng/hex/-/hex-2.3.66.tgz", + "integrity": "sha512-X4YVOByqPZYjIlqdDoZOpzNGW8FF5T2yWuAP3j80RPkVsgX2BM+gQYPyY7kkDe3gzWaRJIYE2TIwFHM+0RogJw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/leb128": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@thi.ng/leb128/-/leb128-3.0.5.tgz", + "integrity": "sha512-B4NP+A1JlZFwUVhAzmVwhGXqnbMGpIBdQq5tiQqMDryWutsgK+CXodQ4Aq6/8N6EctGwhGtVXB4+v9iGHrwdPQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/checks": "^3.3.7", + "@thi.ng/errors": "^2.2.8", + "@thi.ng/transducers-binary": "^2.1.35" + }, + "engines": { + "node": ">=12.7" + } + }, + "node_modules/@thi.ng/math": { + "version": "5.11.22", + "resolved": "https://registry.npmjs.org/@thi.ng/math/-/math-5.11.22.tgz", + "integrity": "sha512-HpYCjOAZWfpiaGd4dVYrqYI8MbnOCpJWBDCUmGIienNCNnjov4iwmsHhi52kVCEIz3bDJtaEkPqB6L663wvCSw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/memoize": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/@thi.ng/memoize/-/memoize-4.0.12.tgz", + "integrity": "sha512-fVNaCojN+thuWstM+/Dz6iPOlH1MJD4yHx+pLErfkJjStAH1UGRCZt2C05qJrSDy8KJxNRfxcQivPKiJClzMCg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/random": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@thi.ng/random/-/random-4.1.13.tgz", + "integrity": "sha512-FQXVYRLt98hItEpzLrGaG7EUuP6+bJYvXeQ65NjtC0pGf+x/DxubI8Jmqphr5EyH8odyxuDzxdnRbak+p3Dnyg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22", + "@thi.ng/errors": "^2.5.28" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/strings": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/@thi.ng/strings/-/strings-3.9.7.tgz", + "integrity": "sha512-J1cNbtSaYCiuTYJJE4rFHsnJIMVKKyjGLcBoGMPUTK40uiR+rwM7Rg3nIbalW7QcBfcNejAelHFzHO5aTD3u3w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22", + "@thi.ng/errors": "^2.5.28", + "@thi.ng/hex": "^2.3.66", + "@thi.ng/memoize": "^4.0.12" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/timestamp": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@thi.ng/timestamp/-/timestamp-1.1.7.tgz", + "integrity": "sha512-puu4cA5HqBoNeRpgPgKdwDHo6YI1PoS9S/X6HiMDfWVhv6Ln4SzydduvJF7fpCEs/01xtMu/8wSpGHH1icBdaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/transducers": { + "version": "9.2.22", + "resolved": "https://registry.npmjs.org/@thi.ng/transducers/-/transducers-9.2.22.tgz", + "integrity": "sha512-CFYXYRlGsRKUZdroQkEn09HagzXhIhs73jVcJ8ld05O8L+H2Y3RPgsOEcSd/ysB1oH/2LfVuFbYkNXg/1jvlDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/api": "^8.11.22", + "@thi.ng/arrays": "^2.10.19", + "@thi.ng/checks": "^3.7.2", + "@thi.ng/compare": "^2.4.14", + "@thi.ng/compose": "^3.0.25", + "@thi.ng/errors": "^2.5.28", + "@thi.ng/math": "^5.11.22", + "@thi.ng/random": "^4.1.13", + "@thi.ng/timestamp": "^1.1.7" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/transducers-binary": { + "version": "2.1.157", + "resolved": "https://registry.npmjs.org/@thi.ng/transducers-binary/-/transducers-binary-2.1.157.tgz", + "integrity": "sha512-MuwYFMHZfUAOgXpYRbuRl6FhhUlJzmU3a2FAk77mhVeWCCUmSU62mTaNF4kJA7jyb9w8jeBLTl9EVBuMYFqRyQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/binary": "^3.4.45", + "@thi.ng/compose": "^3.0.25", + "@thi.ng/errors": "^2.5.28", + "@thi.ng/hex": "^2.3.66", + "@thi.ng/random": "^4.1.13", + "@thi.ng/strings": "^3.9.7", + "@thi.ng/transducers": "^9.2.22" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "18.11.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", + "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", + "license": "MIT" + }, + "node_modules/@types/node-rsa": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@types/node-rsa/-/node-rsa-1.1.4.tgz", + "integrity": "sha512-dB0ECel6JpMnq5ULvpUTunx3yNm8e/dIkv8Zu9p2c8me70xIRUUG3q+qXRwcSf9rN3oqamv4116iHy90dJGRpA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/readable-stream": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.18.tgz", + "integrity": "sha512-21jK/1j+Wg+7jVw1xnSwy/2Q1VgVjWuFssbYGTREPUBeZ+rqVFl2udq0IkxzPC0ZhOzVceUbyIACFZKLqKEBlA==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "safe-buffer": "~5.1.1" + } + }, + "node_modules/@types/semver": { + "version": "7.3.13", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.3.13.tgz", + "integrity": "sha512-21cFJr9z3g5dW8B0CVI9g2O9beqaThGQ6ZFBqHfwhzLDKUxaqTIy3vnfah/UPkfOiF2pLq+tGz+W8RyCskuslw==", + "license": "MIT" + }, + "node_modules/@types/sharp": { + "version": "0.31.1", + "resolved": "https://registry.npmjs.org/@types/sharp/-/sharp-0.31.1.tgz", + "integrity": "sha512-5nWwamN9ZFHXaYEincMSuza8nNfOof8nmO+mcI+Agx1uMUk4/pQnNIcix+9rLPXzKrm1pS34+6WRDbDV0Jn7ag==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/ws": { + "version": "8.5.4", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", + "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@xboxreplay/errors": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@xboxreplay/errors/-/errors-0.1.0.tgz", + "integrity": "sha512-Tgz1d/OIPDWPeyOvuL5+aai5VCcqObhPnlI3skQuf80GVF3k1I0lPCnGC+8Cm5PV9aLBT5m8qPcJoIUQ2U4y9g==", + "license": "MIT" + }, + "node_modules/@xboxreplay/xboxlive-auth": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@xboxreplay/xboxlive-auth/-/xboxlive-auth-3.3.3.tgz", + "integrity": "sha512-j0AU8pW10LM8O68CTZ5QHnvOjSsnPICy0oQcP7zyM7eWkDQ/InkiQiirQKsPn1XRYDl4ccNu0WM582s3UKwcBg==", + "license": "MIT", + "dependencies": { + "@xboxreplay/errors": "^0.1.0", + "axios": "^0.21.1" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/aes-js": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.1.2.tgz", + "integrity": "sha512-e5pEa2kBnBOgR4Y/p20pskXI74UEz7de8ZGVo58asOtvSVG5YAbJeELPZxOmt+Bnz3rX753YKhfIn4X4l1PPRQ==", + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "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/asn1": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", + "integrity": "sha512-6i37w/+EhlWlGUJff3T/Q8u1RGmP5wgbiwYnOnbOqvtrPxT63/sYFyP9RcpxtxGymtfA075IvmOnL7ycNOWl3w==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz", + "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "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/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "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", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-1.0.1.tgz", + "integrity": "sha512-QoV3ptgEaQpvVwbXdSO39iqPQTCxSF7A5U99AxbHYqUdCizL/lH2Z0A2y6nbZucxMEOtNyZfG2s6gsVugGpKkg==", + "license": "MIT", + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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/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/chalk": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.2.0.tgz", + "integrity": "sha512-ree3Gqw/nazQAPuJJEy+avdl7QfZMcUvmHIKgEZkGL+xOBzRvup5Hxo6LHuMceSxOabuJLJm5Yp/92R9eMmMvA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "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==", + "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==", + "license": "MIT" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "license": "MIT", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "license": "MIT" + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/discontinuous-range": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz", + "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==", + "license": "MIT" + }, + "node_modules/dotenv": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz", + "integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "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/endian-toggle": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/endian-toggle/-/endian-toggle-0.0.0.tgz", + "integrity": "sha512-ShfqhXeHRE4TmggSlHXG8CMGIcsOsqDw/GcoPcosToE59Rm9e4aXaMhEQf2kPBsBRrKem1bbOAv5gOKnkliMFQ==", + "license": "MIT" + }, + "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/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "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==", + "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==", + "license": "MIT" + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", + "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.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/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-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/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "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/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "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": "BSD-3-Clause" + }, + "node_modules/ip-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-5.0.0.tgz", + "integrity": "sha512-fOCG6lhoKKakwv+C6KdsOnGvgXnmgfmp0myi3bcNwj3qfwPAxRKWEuFhvEFF7ceYIz6+1jRZ+yguLFAmUNPEfw==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==", + "license": "MIT" + }, + "node_modules/is-ip": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-ip/-/is-ip-4.0.0.tgz", + "integrity": "sha512-4B4XA2HEIm/PY+OSpeMBXr8pGWBYbXuHgjMAqrwbLO3CPTCAd9ArEJzBUKGZtk9viY6+aSfadGnWyjY3ydYZkw==", + "license": "MIT", + "dependencies": { + "ip-regex": "^5.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "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==", + "license": "MIT" + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "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": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "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": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", + "deprecated": "This package is deprecated. Use the optional chaining (?.) operator instead.", + "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==", + "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/lodash.reduce": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.reduce/-/lodash.reduce-4.6.0.tgz", + "integrity": "sha512-6raRe2vxCYBhpBu+B+TtNGUzah+hQjVdu3E17wfusjyrXBka2nBS8OH/gjVZ5PvHOhWmIZTYri09Z6n/QfnNMw==", + "license": "MIT" + }, + "node_modules/macaddress": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/macaddress/-/macaddress-0.5.3.tgz", + "integrity": "sha512-vGBKTA+jwM4KgjGZ+S/8/Mkj9rWzePyGY6jManXPGhiWu63RYwW8dKPyk5koP+8qNVhPhHgFa1y/MJ4wrjsNrg==", + "license": "MIT" + }, + "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/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/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/minecraft-data": { + "version": "3.84.1", + "resolved": "https://registry.npmjs.org/minecraft-data/-/minecraft-data-3.84.1.tgz", + "integrity": "sha512-0yPsnu4rYjbokPgm6aMqhIm70fhsUUYFMEbbqrLG7QGLQDUy3lauuVlh3ctRxtPP6vX/ywLo1p5Uczz3Snnocg==", + "license": "MIT" + }, + "node_modules/minecraft-folder-path": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minecraft-folder-path/-/minecraft-folder-path-1.2.0.tgz", + "integrity": "sha512-qaUSbKWoOsH9brn0JQuBhxNAzTDMwrOXorwuRxdJKKKDYvZhtml+6GVCUrY5HRiEsieBEjCUnhVpDuQiKsiFaw==", + "license": "MIT" + }, + "node_modules/minecraft-protocol": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/minecraft-protocol/-/minecraft-protocol-1.54.0.tgz", + "integrity": "sha512-v8pWRVhD9kyd/X52j/XESxrNxkmz1OHzSXAJkPLOQUUTENEqisJhu1c3abS7ZI+MAXHAEA/vaCb/Eh6XFxw0lA==", + "license": "BSD-3-Clause", + "dependencies": { + "@types/node-rsa": "^1.1.4", + "@types/readable-stream": "^4.0.0", + "aes-js": "^3.1.2", + "buffer-equal": "^1.0.0", + "debug": "^4.3.2", + "endian-toggle": "^0.0.0", + "lodash.get": "^4.1.2", + "lodash.merge": "^4.3.0", + "minecraft-data": "^3.78.0", + "minecraft-folder-path": "^1.2.0", + "node-fetch": "^2.6.1", + "node-rsa": "^0.4.2", + "prismarine-auth": "^2.2.0", + "prismarine-chat": "^1.10.0", + "prismarine-nbt": "^2.5.0", + "prismarine-realms": "^1.2.0", + "protodef": "^1.17.0", + "readable-stream": "^4.1.0", + "uuid-1345": "^1.0.1", + "yggdrasil": "^1.4.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/minecraft-protocol/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/mojangson": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/mojangson/-/mojangson-2.0.4.tgz", + "integrity": "sha512-HYmhgDjr1gzF7trGgvcC/huIg2L8FsVbi/KacRe6r1AswbboGVZDS47SOZlomPuMWvZLas8m9vuHHucdZMwTmQ==", + "license": "MIT", + "dependencies": { + "nearley": "^2.19.5" + } + }, + "node_modules/moo": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz", + "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==", + "license": "BSD-3-Clause" + }, + "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/nearley": { + "version": "2.20.1", + "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz", + "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==", + "license": "MIT", + "dependencies": { + "commander": "^2.19.0", + "moo": "^0.5.0", + "railroad-diagrams": "^1.0.0", + "randexp": "0.4.6" + }, + "bin": { + "nearley-railroad": "bin/nearley-railroad.js", + "nearley-test": "bin/nearley-test.js", + "nearley-unparse": "bin/nearley-unparse.js", + "nearleyc": "bin/nearleyc.js" + }, + "funding": { + "type": "individual", + "url": "https://nearley.js.org/#give-to-nearley" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.1.tgz", + "integrity": "sha512-cRVc/kyto/7E5shrWca1Wsea4y6tL9iYJE5FBCius3JQfb/4P4I295PfhgbJQBLTx6lATE4z+wK0rPM4VS2uow==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/node-rsa": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/node-rsa/-/node-rsa-0.4.2.tgz", + "integrity": "sha512-Bvso6Zi9LY4otIZefYrscsUpo2mUpiAVIEmSZV2q41sP8tHZoert3Yu6zv4f/RXJqMNZQKCtnhDugIuCma23YA==", + "license": "MIT", + "dependencies": { + "asn1": "0.2.3" + } + }, + "node_modules/parse-domain": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/parse-domain/-/parse-domain-7.0.1.tgz", + "integrity": "sha512-HsVmJkfoZB/Rb7Ai/QYVqZa95zkemNMerP70ZzIFpvvnvWbSSp+ZmUOQsdY1wxuFrB8cdA33E9fwwAT/OjWViA==", + "license": "MIT", + "dependencies": { + "is-ip": "^4.0.0", + "node-fetch": "^3.2.0" + }, + "bin": { + "parse-domain-update": "bin/update.js" + } + }, + "node_modules/prismarine-auth": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/prismarine-auth/-/prismarine-auth-2.7.0.tgz", + "integrity": "sha512-L8wTF6sdtnN6hViPNy+Nx39a8iQBwR5iO92AWCiym5cSXp/92pmnuwnTdcmNDWyqq6zY4hbibVGYhgLA1Ox8sQ==", + "license": "MIT", + "dependencies": { + "@azure/msal-node": "^2.0.2", + "@xboxreplay/xboxlive-auth": "^3.3.3", + "debug": "^4.3.3", + "smart-buffer": "^4.1.0", + "uuid-1345": "^1.0.2" + } + }, + "node_modules/prismarine-biome": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/prismarine-biome/-/prismarine-biome-1.3.0.tgz", + "integrity": "sha512-GY6nZxq93mTErT7jD7jt8YS1aPrOakbJHh39seYsJFXvueIOdHAmW16kYQVrTVMW5MlWLQVxV/EquRwOgr4MnQ==", + "license": "MIT", + "peerDependencies": { + "minecraft-data": "^3.0.0", + "prismarine-registry": "^1.1.0" + } + }, + "node_modules/prismarine-block": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/prismarine-block/-/prismarine-block-1.16.3.tgz", + "integrity": "sha512-E9OazjIqnEgcXM6me6EIeQFMcNRWZzsaftWtetRSIKVoW+4UKWleb6lTNKh9kq7wNxciKavcYBmKL3sF7HfSaA==", + "license": "MIT", + "dependencies": { + "minecraft-data": "^3.0.0", + "prismarine-biome": "^1.1.0", + "prismarine-chat": "^1.5.0", + "prismarine-item": "^1.10.1", + "prismarine-nbt": "^2.0.0", + "prismarine-registry": "^1.1.0" + } + }, + "node_modules/prismarine-chat": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/prismarine-chat/-/prismarine-chat-1.11.0.tgz", + "integrity": "sha512-VJT/MWYB3qoiznUhrgvSQh76YFpzpCZpY85kJKxHLbd3UVoM0wsfs43Eg8dOltiZG92wc5/DTMLlT07TEeoa9w==", + "license": "MIT", + "dependencies": { + "mojangson": "^2.0.1", + "prismarine-nbt": "^2.0.0", + "prismarine-registry": "^1.4.0" + } + }, + "node_modules/prismarine-chunk": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/prismarine-chunk/-/prismarine-chunk-1.33.0.tgz", + "integrity": "sha512-oTkhyE8EWV5mMOaUyCACiUUtx1270Mo18Ryj+t5Y8dglT4QfVwBsYeph+O40kNL9TK5cTW1lFYg5vr2rWuFGnw==", + "license": "MIT", + "dependencies": { + "prismarine-biome": "^1.2.0", + "prismarine-block": "^1.14.1", + "prismarine-nbt": "^2.2.1", + "prismarine-registry": "^1.1.0", + "smart-buffer": "^4.1.0", + "uint4": "^0.1.2", + "vec3": "^0.1.3", + "xxhash-wasm": "^0.4.2" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/prismarine-item": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/prismarine-item/-/prismarine-item-1.16.0.tgz", + "integrity": "sha512-88Tz+/6HquYIsDuseae5G3IbqLeMews2L+ba2gX+p6K6soU9nuFhCfbwN56QuB7d/jZFcWrCYAPE5+UhwWh67w==", + "license": "MIT", + "dependencies": { + "prismarine-nbt": "^2.0.0", + "prismarine-registry": "^1.4.0" + } + }, + "node_modules/prismarine-nbt": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/prismarine-nbt/-/prismarine-nbt-2.7.0.tgz", + "integrity": "sha512-Du9OLQAcCj3y29YtewOJbbV4ARaSUEJiTguw0PPQbPBy83f+eCyDRkyBpnXTi/KPyEpgYCzsjGzElevLpFoYGQ==", + "license": "MIT", + "dependencies": { + "protodef": "^1.18.0" + } + }, + "node_modules/prismarine-realms": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/prismarine-realms/-/prismarine-realms-1.3.2.tgz", + "integrity": "sha512-5apl9Ru8veTj5q2OozRc4GZOuSIcs3yY4UEtALiLKHstBe8bRw8vNlaz4Zla3jsQ8yP/ul1b1IJINTRbocuA6g==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.3", + "node-fetch": "^2.6.1" + } + }, + "node_modules/prismarine-realms/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/prismarine-registry": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/prismarine-registry/-/prismarine-registry-1.6.0.tgz", + "integrity": "sha512-oduDRuwa5rXT8CkPeMSlBsuBzxZF9oRsDpFK0oBStpIoNwSuTqqGGGgLlyL20OS2O9pmqYpOMlmG80CW4uuKJw==", + "license": "MIT", + "dependencies": { + "minecraft-data": "^3.0.0", + "prismarine-nbt": "^2.0.0" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/protodef": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/protodef/-/protodef-1.18.0.tgz", + "integrity": "sha512-jO64lkzkh0dYc0AVWCU/GzCKwqhFFIz1kfEz0NBf0RUuRNcmvgKbopabJdfZ6W8NvALdySUXgEhvKDZPhdBwrg==", + "license": "MIT", + "dependencies": { + "lodash.get": "^4.4.2", + "lodash.reduce": "^4.6.0", + "protodef-validator": "^1.3.0", + "readable-stream": "^4.4.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/protodef-validator": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/protodef-validator/-/protodef-validator-1.4.0.tgz", + "integrity": "sha512-2y2coBolqCEuk5Kc3QwO7ThR+/7TZiOit4FrpAgl+vFMvq8w76nDhh09z08e2NQOdrgPLsN2yzXsvRvtADgUZQ==", + "license": "MIT", + "dependencies": { + "ajv": "^6.5.4" + }, + "bin": { + "protodef-validator": "cli.js" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "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==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/railroad-diagrams": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz", + "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==", + "license": "CC0-1.0" + }, + "node_modules/randexp": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz", + "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==", + "license": "MIT", + "dependencies": { + "discontinuous-range": "1.0.0", + "ret": "~0.1.10" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "license": "MIT", + "engines": { + "node": ">=0.12" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", + "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.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/string_decoder/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/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/uint4": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/uint4/-/uint4-0.1.2.tgz", + "integrity": "sha512-lhEx78gdTwFWG+mt6cWAZD/R6qrIj0TTBeH5xwyuDJyswLNlGe+KVlUPQ6+mx5Ld332pS0AMUTo9hIly7YsWxQ==", + "license": "MIT" + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/uuid-1345": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uuid-1345/-/uuid-1345-1.0.2.tgz", + "integrity": "sha512-bA5zYZui+3nwAc0s3VdGQGBfbVsJLVX7Np7ch2aqcEWFi5lsAEcmO3+lx3djM1npgpZI8KY2FITZ2uYTnYUYyw==", + "license": "MIT", + "dependencies": { + "macaddress": "^0.5.1" + } + }, + "node_modules/vec3": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/vec3/-/vec3-0.1.10.tgz", + "integrity": "sha512-Sr1U3mYtMqCOonGd3LAN9iqy0qF6C+Gjil92awyK/i2OwiUo9bm7PnLgFpafymun50mOjnDcg4ToTgRssrlTcw==", + "license": "BSD" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xxhash-wasm": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-0.4.2.tgz", + "integrity": "sha512-/eyHVRJQCirEkSZ1agRSCwriMhwlyUcFkXD5TPVSLP+IPzjsqMVzZwdoczLp1SoQU0R3dxz1RpIK+4YNQbCVOA==", + "license": "MIT" + }, + "node_modules/yggdrasil": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/yggdrasil/-/yggdrasil-1.7.0.tgz", + "integrity": "sha512-QBIo5fiNd7688G3FqXXYGr36uyrYzczlNuzpWFy2zL3+R+3KT2lF+wFxm51synfA3l3z6IBiGOc1/EVXWCYY1Q==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.1", + "uuid": "^8.2.0" + } + }, + "node_modules/yggdrasil/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + } + } +} diff --git a/eaglerproxy/files/package.json b/eaglerproxy/files/package.json new file mode 100644 index 0000000..a7d1fe6 --- /dev/null +++ b/eaglerproxy/files/package.json @@ -0,0 +1,34 @@ +{ + "name": "eaglerproxy", + "version": "1.0.0", + "description": "A flexible, easy expandable EaglercraftX 1.8.9 proxy written in TypeScript.", + "main": "launcher.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "WorldEditAxe, q13x", + "license": "MIT", + "dependencies": { + "@thi.ng/leb128": "3.0.5", + "@types/node": "18.11.18", + "@types/semver": "7.3.13", + "@types/sharp": "0.31.1", + "@types/ws": "8.5.4", + "chalk": "5.2.0", + "dotenv": "16.0.3", + "minecraft-protocol": "^1.26.5", + "node-fetch": "3.3.1", + "parse-domain": "7.0.1", + "prismarine-auth": "^2.7.0", + "prismarine-block": "1.16.3", + "prismarine-chunk": "1.33.0", + "prismarine-registry": "1.6.0", + "semver": "^7.6.3", + "sharp": "^0.33.5", + "ws": "^8.18.1" + }, + "overrides": { + "axios": "^1.8.2" + }, + "type": "module" +} diff --git a/eaglerproxy/files/replit.nix b/eaglerproxy/files/replit.nix new file mode 100644 index 0000000..d297a9d --- /dev/null +++ b/eaglerproxy/files/replit.nix @@ -0,0 +1,10 @@ +{ pkgs }: { + deps = [ + pkgs.yarn + pkgs.esbuild + pkgs.nodejs-18_x + + pkgs.nodePackages.typescript + pkgs.nodePackages.typescript-language-server + ]; +} diff --git a/eaglerproxy/files/replit_launch.sh b/eaglerproxy/files/replit_launch.sh new file mode 100644 index 0000000..eda0cdc --- /dev/null +++ b/eaglerproxy/files/replit_launch.sh @@ -0,0 +1,2 @@ +cd ~/$REPL_SLUG/build +node index.js diff --git a/eaglerproxy/files/replit_runtime/config.js b/eaglerproxy/files/replit_runtime/config.js new file mode 100644 index 0000000..c588a77 --- /dev/null +++ b/eaglerproxy/files/replit_runtime/config.js @@ -0,0 +1,9 @@ +const path = require("path"); +const os = require("os"); + +module.exports = { + sourceDir: path.resolve( + os.homedir(), + path.join(process.env.REPL_SLUG, "src") + ), +}; diff --git a/eaglerproxy/files/replit_runtime/index.js b/eaglerproxy/files/replit_runtime/index.js new file mode 100644 index 0000000..b162f19 --- /dev/null +++ b/eaglerproxy/files/replit_runtime/index.js @@ -0,0 +1,147 @@ +// libraries +const fs = require("fs/promises"); +const path = require("path"); +const crypto = require("crypto"); +const { sourceDir } = require("./config.js"); + +class Logger { + constructor({ name, logDebug }) { + this.name = name; + this.debug = logDebug; + } + + _log(logType, data, method) { + console[method]( + `[${this.name}] [${logType}] ${ + typeof data == "string" ? data : data.toString() + }` + ); + } + + info(data) { + this._log("info", data, "log"); + } + + warn(data) { + this._log("warn", data, "error"); + } + + error(data) { + this._log("error", data, "error"); + } + + debug(data) { + if (this.debug) { + this._log("debug", data, "error"); + } + } +} + +async function recursiveFileSearch(dir) { + const fileList = []; + for (const file of await fs.readdir(dir, { withFileTypes: true })) { + let pathDir = path.resolve(dir, file.name); + if (file.isFile()) { + fileList.push(pathDir); + } else if (file.isDirectory()) { + fileList.push(...(await recursiveFileSearch(pathDir))); + } else { + logger.warn( + `Found directory entry that is neither a file or directory (${pathDir}), ignoring!` + ); + } + } + return fileList; +} + +const logger = new Logger({ + name: "launcher", + logDebug: process.env.DEBUG == "true", + }), + LINE_SEPERATOR = "-----------------------------------"; + +if (!process.env.REPL_SLUG) { + logger.error(LINE_SEPERATOR); + logger.error("Repl not detected!"); + logger.error(""); + logger.error("This file is meant to be ran in a Repl"); + logger.error(LINE_SEPERATOR); +} + +logger.info(LINE_SEPERATOR); +logger.info("Checking if the proxy needs to be recompiled..."); +logger.info(LINE_SEPERATOR); + +fs.readFile(path.join(__dirname, ".sourcehash")) + .then((data) => { + let oldHash = data.toString(); + logger.info("Found old hash, calculating hash of source files..."); + recursiveFileSearch(sourceDir) + .then((files) => { + Promise.all(files.map((f) => fs.readFile(f))).then((data) => { + const hash = crypto.createHash("sha256"); + data.forEach((d) => hash.update(d)); + let sourceHash = hash.digest().toString(); + + if (sourceHash === oldHash) { + logger.info("Source hasn't been changed, skipping compilation..."); + process.exit(0); + } else { + logger.info("Source has been changed, recompiling..."); + fs.writeFile(path.join(__dirname, ".sourcehash"), sourceHash) + .then(() => { + process.exit(2); + }) + .catch((err) => { + logger.error(`Could not write new hash to disk!\n${err.stack}`); + process.exit(1); + }); + } + }); + }) + .catch((err) => { + logger.error( + `Could not calculate file hashes for files in directory ${sourceDir}!\n${err.stack}` + ); + process.exit(1); + }); + }) + .catch((err) => { + if (err.code == "ENOENT") { + logger.warn( + "Previous source hash not found! Assuming a clean install is being used." + ); + logger.info("Calculating hash..."); + recursiveFileSearch(sourceDir) + .then((files) => { + Promise.all(files.map((f) => fs.readFile(f))).then((data) => { + const hash = crypto.createHash("sha256"); + data.forEach((d) => hash.update(d)); + let sourceHash = hash.digest().toString(); + fs.writeFile(path.join(__dirname, ".sourcehash"), sourceHash) + .then(() => { + logger.info("Saved hash to disk."); + process.exit(2); + }) + .catch((err) => { + logger.error(`Could not write new hash to disk!\n${err.stack}`); + process.exit(1); + }); + }); + }) + .catch((err) => { + logger.error( + `Could not calculate file hashes for files in directory ${sourceDir}!\n${err.stack}` + ); + process.exit(1); + }); + } else { + logger.error( + `Could not read .sourcehash file in ${path.join( + __dirname, + ".sourcehash" + )} due to an unknown error! Try again with a clean repl?\n${err.stack}` + ); + process.exit(1); + } + }); diff --git a/eaglerproxy/files/replit_runtime/package.json b/eaglerproxy/files/replit_runtime/package.json new file mode 100644 index 0000000..401c9a7 --- /dev/null +++ b/eaglerproxy/files/replit_runtime/package.json @@ -0,0 +1,5 @@ +{ + "name": "replit_runtime", + "description": "Runtime preparation utility for Repls. Determines whether or not a recompilation is necessary.", + "type": "commonjs" +} diff --git a/eaglerproxy/files/src/config.ts b/eaglerproxy/files/src/config.ts new file mode 100644 index 0000000..236772b --- /dev/null +++ b/eaglerproxy/files/src/config.ts @@ -0,0 +1,54 @@ +// This folder contains options for both the bridge and networking adapter. +// Environment files and .env files are available here. Set the value of any config option to process.env. + +import { Config } from "./launcher_types.js"; + +export const config: Config = { + adapter: { + name: "EaglerProxy", + bindHost: "0.0.0.0", + bindPort: 8080, + maxConcurrentClients: 20, + // set this to false if you are unable to install sharp due to either the use of a platform that does not support native modules + // or if you are unable to install the required dependencies. this will cause the proxy to use jimp instead of sharp, which may + // degrade your proxy's performance. + useNatives: true, + skinServer: { + skinUrlWhitelist: undefined, + cache: { + useCache: true, + folderName: "skinCache", + skinCacheLifetime: 60 * 60 * 1000, + skinCachePruneInterval: 10 * 60 * 1000, + }, + }, + motd: true + ? "FORWARD" // "FORWARD" regularly polls the server for the MOTD + : { + iconURL: "motd.png", // must be a valid file path + l1: "yes", + l2: "no", + }, // providing an object as such will allow you to supply your own MOTD + ratelimits: { + lockout: 10, + limits: { + http: 100, + ws: 100, + motd: 100, + skins: 1000, // adjust as necessary + skinsIp: 10000, + connect: 100, + }, + }, + origins: { + allowOfflineDownloads: true, + originWhitelist: null, + originBlacklist: null, + }, + server: { + host: "127.0.0.1", + port: 1111, + }, + tls: undefined, + }, +}; diff --git a/eaglerproxy/files/src/globals.d.ts b/eaglerproxy/files/src/globals.d.ts new file mode 100644 index 0000000..e7deaf4 --- /dev/null +++ b/eaglerproxy/files/src/globals.d.ts @@ -0,0 +1,16 @@ +import { Proxy } from "./proxy/Proxy.js"; +import Packet from "./proxy/Packet.js"; +import { Config } from "./launcher_types.js"; +import { PluginManager } from "./proxy/pluginLoader/PluginManager.js"; + +declare global { + var CONFIG: Config; + var PROXY: Proxy; + var PLUGIN_MANAGER: PluginManager; + var PACKET_REGISTRY: Map< + number, + Packet & { + class: any; + } + >; +} diff --git a/eaglerproxy/files/src/index.ts b/eaglerproxy/files/src/index.ts new file mode 100644 index 0000000..1978fa2 --- /dev/null +++ b/eaglerproxy/files/src/index.ts @@ -0,0 +1,32 @@ +import * as dotenv from "dotenv"; +import process from "process"; +import { Proxy } from "./proxy/Proxy.js"; +import { config } from "./config.js"; +dotenv.config(); +import { Logger } from "./logger.js"; +import { PROXY_BRANDING } from "./meta.js"; +import { PluginManager } from "./proxy/pluginLoader/PluginManager.js"; +import { dirname, join } from "path"; +import { fileURLToPath } from "url"; +import { ImageEditor } from "./proxy/skins/ImageEditor.js"; + +const logger = new Logger("Launcher"); +let proxy: Proxy; + +global.CONFIG = config; +config.adapter.useNatives = config.adapter.useNatives ?? true; + +logger.info("Loading libraries..."); +await ImageEditor.loadLibraries(config.adapter.useNatives); + +logger.info("Loading plugins..."); +const pluginManager = new PluginManager(join(dirname(fileURLToPath(import.meta.url)), "plugins")); +global.PLUGIN_MANAGER = pluginManager; +await pluginManager.loadPlugins(); + +proxy = new Proxy(config.adapter, pluginManager); +pluginManager.proxy = proxy; + +logger.info(`Launching ${PROXY_BRANDING}...`); +await proxy.init(); +global.PROXY = proxy; diff --git a/eaglerproxy/files/src/launcher_types.ts b/eaglerproxy/files/src/launcher_types.ts new file mode 100644 index 0000000..fe808e5 --- /dev/null +++ b/eaglerproxy/files/src/launcher_types.ts @@ -0,0 +1,65 @@ +export type Config = { + adapter: AdapterOptions; +}; + +export type BridgeOptions = { + enabled: boolean; + motd: + | "FORWARD" + | "REALTIME" + | { + iconURL?: string; + l1: string; + l2?: string; + }; +}; + +export type AdapterOptions = { + name: string; + bindHost: string; + bindPort: number; + maxConcurrentClients: number; + useNatives?: boolean; + skinServer: { + skinUrlWhitelist?: string[]; + cache: { + useCache: boolean; + folderName?: string; + skinCacheLifetime?: number; + skinCachePruneInterval?: number; + }; + }; + origins: { + allowOfflineDownloads: boolean; + originWhitelist: string[]; + originBlacklist: string[]; + }; + motd: + | "FORWARD" + | "REALTIME" + | { + iconURL?: string; + l1: string; + l2?: string; + }; + ratelimits: { + lockout: number; + limits: { + http: number; + ws: number; + motd: number; + connect: number; + skins: number; + skinsIp: number; + }; + }; + server: { + host: string; + port: number; + }; + tls?: { + enabled: boolean; + key: null; + cert: null; + }; +}; diff --git a/eaglerproxy/files/src/logger.ts b/eaglerproxy/files/src/logger.ts new file mode 100644 index 0000000..91a5049 --- /dev/null +++ b/eaglerproxy/files/src/logger.ts @@ -0,0 +1,95 @@ +import { Chalk } from "chalk"; + +const color = new Chalk({ level: 2 }); + +let global_verbose: boolean = false; + +type JsonLogType = "info" | "warn" | "error" | "fatal" | "debug"; +type JsonOutput = { + type: JsonLogType; + message: string; +}; + +export function verboseLogging(newVal?: boolean) { + global_verbose = newVal ?? global_verbose ? false : true; +} + +function jsonLog(type: JsonLogType, message: string): string { + return ( + JSON.stringify({ + type: type, + message: message, + }) + "\n" + ); +} + +export class Logger { + loggerName: string; + verbose: boolean; + private jsonLog: boolean = + process.argv.includes("--json") || process.argv.includes("-j"); + + constructor(name: string, verbose?: boolean) { + this.loggerName = name; + if (verbose) this.verbose = verbose; + else this.verbose = global_verbose; + } + + info(s: string) { + if (!this.jsonLog) + process.stdout.write( + `${color.green("I")} ${color.gray( + new Date().toISOString() + )} ${color.reset(`${color.yellow(`${this.loggerName}:`)} ${s}`)}\n` + ); + else process.stdout.write(jsonLog("info", s)); + } + + warn(s: string) { + if (!this.jsonLog) + process.stdout.write( + `${color.yellow("W")} ${color.gray( + new Date().toISOString() + )} ${color.yellow(`${color.yellow(`${this.loggerName}:`)} ${s}`)}\n` + ); + else process.stderr.write(jsonLog("warn", s)); + } + + error(s: string) { + if (!this.jsonLog) + process.stderr.write( + `* ${color.red("E")} ${color.gray( + new Date().toISOString() + )} ${color.redBright(`${color.red(`${this.loggerName}:`)} ${s}`)}\n` + ); + else process.stderr.write(jsonLog("error", s)); + } + + fatal(s: string) { + if (!this.jsonLog) + process.stderr.write( + `** ${color.red("F!")} ${color.gray( + new Date().toISOString() + )} ${color.bgRedBright( + color.redBright(`${color.red(`${this.loggerName}:`)} ${s}`) + )}\n` + ); + else process.stderr.write(jsonLog("fatal", s)); + } + + debug(s: string) { + if (this.verbose || global_verbose) { + if (!this.jsonLog) + process.stderr.write( + `${color.gray("D")} ${color.gray( + new Date().toISOString() + )} ${color.gray(`${color.gray(`${this.loggerName}:`)} ${s}`)}\n` + ); + else process.stderr.write(jsonLog("debug", s)); + } + } +} + +verboseLogging( + process.env.DEBUG != null && process.env.DEBUG != "false" ? true : false +); diff --git a/eaglerproxy/files/src/meta.ts b/eaglerproxy/files/src/meta.ts new file mode 100644 index 0000000..9d25b7d --- /dev/null +++ b/eaglerproxy/files/src/meta.ts @@ -0,0 +1,11 @@ +const f = Object.freeze; + +// bridge meta +export const BRIDGE_VERSION: Readonly = f(1); + +// adapter meta +export const PROXY_BRANDING: Readonly = f("EaglerProxy"); +export const PROXY_VERSION: Readonly = f("1.1.0"); + +export const NETWORK_VERSION: Readonly = f(0x03); +export const VANILLA_PROTOCOL_VERSION: Readonly = f(47); diff --git a/eaglerproxy/files/src/plugins/DummyFile.ts b/eaglerproxy/files/src/plugins/DummyFile.ts new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/eaglerproxy/files/src/plugins/DummyFile.ts @@ -0,0 +1 @@ + diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/CustomAuthflow.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/CustomAuthflow.ts new file mode 100644 index 0000000..82287c5 --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/CustomAuthflow.ts @@ -0,0 +1,206 @@ +import fs from "fs"; +import path from "path"; +import crypto from "crypto"; + +import Constants from "prismarine-auth/src/common/Constants.js"; +const { Endpoints, msalConfig } = Constants; + +import LiveTokenManager from "prismarine-auth/src/TokenManagers/LiveTokenManager.js"; +import JavaTokenManager from "prismarine-auth/src/TokenManagers/MinecraftJavaTokenManager.js"; +import XboxTokenManager from "prismarine-auth/src/TokenManagers/XboxTokenManager.js"; +import MsaTokenManager from "prismarine-auth/src/TokenManagers/MsaTokenManager.js"; +import BedrockTokenManager from "prismarine-auth/src/TokenManagers/MinecraftBedrockTokenManager.js"; + +async function retry(methodFn, beforeRetry, times) { + while (times--) { + if (times !== 0) { + try { + return await methodFn(); + } catch (e) { + if (e instanceof URIError) { + throw e; + } else { + // debug(e); + } + } + await new Promise((resolve) => setTimeout(resolve, 2000)); + await beforeRetry(); + } else { + return await methodFn(); + } + } +} + +export class CustomAuthflow { + username: string; + options: any; + codeCallback: any; + msa: any; + doTitleAuth: boolean; + xbl: any; + mba: any; + mca: any; + + constructor(username = "", cache, options, codeCallback) { + this.username = username; + if (options && !options.flow) { + throw new Error("Missing 'flow' argument in options. See docs for more information."); + } + this.options = options || { flow: "msal" }; + this.initTokenManagers(username, cache); + this.codeCallback = codeCallback; + } + + initTokenManagers(username, cache) { + if (this.options.flow === "live" || this.options.flow === "sisu") { + if (!this.options.authTitle) throw new Error(`Please specify an "authTitle" in Authflow constructor when using ${this.options.flow} flow`); + this.msa = new LiveTokenManager(this.options.authTitle, ["service::user.auth.xboxlive.com::MBI_SSL"], cache({ cacheName: this.options.flow, username })); + this.doTitleAuth = true; + } else if (this.options.flow === "msal") { + const config = Object.assign({ ...msalConfig }, this.options.authTitle ? { auth: { ...msalConfig.auth, clientId: this.options.authTitle } } : {}); + this.msa = new MsaTokenManager(config, ["XboxLive.signin", "offline_access"], cache({ cacheName: "msal", username })); + } else { + throw new Error(`Unknown flow: ${this.options.flow} (expected "live", "sisu", or "msal")`); + } + + const keyPair = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + this.xbl = new XboxTokenManager(keyPair, cache({ cacheName: "xbl", username })); + this.mba = new BedrockTokenManager(cache({ cacheName: "bed", username })); + this.mca = new JavaTokenManager(cache({ cacheName: "mca", username })); + } + + static resetTokenCaches(cache) { + if (!cache) throw new Error("You must provide a cache directory to reset."); + try { + if (fs.existsSync(cache)) { + fs.rmSync(cache, { recursive: true }); + return true; + } + } catch (e) { + console.log("Failed to clear cache dir", e); + return false; + } + } + + async getMsaToken() { + if (await this.msa.verifyTokens()) { + const { token } = await this.msa.getAccessToken(); + return token; + } else { + const ret = await this.msa.authDeviceCode((response) => { + if (this.codeCallback) return this.codeCallback(response); + console.info("[msa] First time signing in. Please authenticate now:"); + console.info(response.message); + }); + + if (ret.account) { + console.info(`[msa] Signed in as ${ret.account.username}`); + } else { + // We don't get extra account data here per scope + console.info("[msa] Signed in with Microsoft"); + } + + return ret.accessToken; + } + } + + async getXboxToken(relyingParty = this.options.relyingParty || Endpoints.XboxRelyingParty, forceRefresh = false) { + const options = { ...this.options, relyingParty }; + + const { xstsToken, userToken, deviceToken, titleToken } = await this.xbl.getCachedTokens(relyingParty); + + if (xstsToken.valid && !forceRefresh) { + return xstsToken.data; + } + + if (options.password) { + const xsts = await this.xbl.doReplayAuth(this.username, options.password, options); + return xsts; + } + + return await retry( + async () => { + const msaToken = await this.getMsaToken(); + + // sisu flow generates user and title tokens differently to other flows and should also be used to refresh them if they are invalid + if (options.flow === "sisu" && (!userToken.valid || !deviceToken.valid || !titleToken.valid)) { + const dt = await this.xbl.getDeviceToken(options); + const sisu = await this.xbl.doSisuAuth(msaToken, dt, options); + return sisu; + } + + const ut = userToken.token ?? (await this.xbl.getUserToken(msaToken, options.flow === "msal")); + const dt = deviceToken.token ?? (await this.xbl.getDeviceToken(options)); + const tt = titleToken.token ?? (this.doTitleAuth ? await this.xbl.getTitleToken(msaToken, dt) : undefined); + + const xsts = await this.xbl.getXSTSToken({ userToken: ut, deviceToken: dt, titleToken: tt }, options); + return xsts; + }, + () => { + this.msa.forceRefresh = true; + }, + 2 + ); + } + + async getMinecraftJavaToken(options: any = {}, quit: { quit: boolean }) { + const response: any = { token: "", entitlements: {} as any, profile: {} as any }; + if (await this.mca.verifyTokens()) { + const { token } = await this.mca.getCachedAccessToken(); + response.token = token; + } else { + await retry( + async () => { + const xsts = await this.getXboxToken(Endpoints.PCXSTSRelyingParty); + response.token = await this.mca.getAccessToken(xsts); + if (quit.quit) return; + }, + () => { + this.xbl.forceRefresh = true; + }, + 2 + ); + } + if (quit.quit) return; + + if (options.fetchEntitlements) { + response.entitlements = await this.mca.fetchEntitlements(response.token).catch((e) => {}); + } + if (options.fetchProfile) { + response.profile = await this.mca.fetchProfile(response.token).catch((e) => {}); + } + if (options.fetchCertificates) { + response.certificates = await this.mca.fetchCertificates(response.token).catch((e) => []); + } + + return response; + } + + async getMinecraftBedrockToken(publicKey) { + // TODO: Fix cache, in order to do cache we also need to cache the ECDH keys so disable it + // is this even a good idea to cache? + if ((await this.mba.verifyTokens()) && false) { + // eslint-disable-line + const { chain } = this.mba.getCachedAccessToken(); + return chain; + } else { + if (!publicKey) throw new Error("Need to specifiy a ECDH x509 URL encoded public key"); + return await retry( + async () => { + const xsts = await this.getXboxToken(Endpoints.BedrockXSTSRelyingParty); + const token = await this.mba.getAccessToken(publicKey, xsts); + // If we want to auth with a title ID, make sure there's a TitleID in the response + const body = JSON.parse(Buffer.from(token.chain[1].split(".")[1], "base64").toString()); + if (!body.extraData.titleId && this.doTitleAuth) { + throw Error("missing titleId in response"); + } + return token.chain; + }, + () => { + this.xbl.forceRefresh = true; + }, + 2 + ); + } + } +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/auth.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/auth.ts new file mode 100644 index 0000000..4682340 --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/auth.ts @@ -0,0 +1,69 @@ +import { randomUUID } from "crypto"; +import EventEmitter from "events"; +import pauth from "prismarine-auth"; +import { CustomAuthflow } from "./CustomAuthflow.js"; + +const { Authflow, Titles } = pauth; +const Enums = PLUGIN_MANAGER.Enums; + +export type ServerDeviceCodeResponse = { + user_code: string; + device_code: string; + verification_uri: string; + expires_in: number; + interval: number; + message: string; +}; + +class InMemoryCache { + private cache = {}; + async getCached() { + return this.cache; + } + async setCached(value) { + this.cache = value; + } + async setCachedPartial(value) { + this.cache = { + ...this.cache, + ...value, + }; + } +} + +export function auth(quit: { quit: boolean }): EventEmitter { + const emitter = new EventEmitter(); + const userIdentifier = randomUUID(); + const flow = new CustomAuthflow( + userIdentifier, + ({ username, cacheName }) => new InMemoryCache(), + { + authTitle: Titles.MinecraftJava, + flow: "sisu", + deviceType: "Win32", + }, + (code) => { + console.log = () => {}; + emitter.emit("code", code); + } + ); + flow + .getMinecraftJavaToken({ fetchProfile: true }, quit) + .then(async (data) => { + if (!data || quit.quit) return; + + const _data = (await (flow as any).mca.cache.getCached()).mca; + if (data.profile == null || (data.profile as any).error) return emitter.emit("error", new Error(Enums.ChatColor.RED + "Couldn't fetch profile data, does the account own Minecraft: Java Edition?")); + emitter.emit("done", { + accessToken: data.token, + expiresOn: _data.obtainedOn + _data.expires_in * 1000, + selectedProfile: data.profile, + availableProfiles: [data.profile], + }); + }) + .catch((err) => { + if (err.toString().includes("Not Found")) emitter.emit("error", new Error(Enums.ChatColor.RED + "The provided account doesn't own Minecraft: Java Edition!")); + else emitter.emit("error", new Error(Enums.ChatColor.YELLOW + err.toString())); + }); + return emitter; +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/auth_thealtening.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/auth_thealtening.ts new file mode 100644 index 0000000..b745d40 --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/auth_thealtening.ts @@ -0,0 +1,26 @@ +import mc from "minecraft-protocol"; +import { Enums } from "../../proxy/Enums.js"; + +export async function getTokenProfileTheAltening(token: string): Promise { + const fetchOptions = { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + username: token, + password: "anything", + }), + }; + const res = await fetch("http://authserver.thealtening.com/authenticate", fetchOptions); + const resJson = await res.json(); + + if (resJson.error) throw new Error(Enums.ChatColor.RED + `${resJson.error}`); + if (!resJson) throw new Error(Enums.ChatColor.RED + "TheAltening replied with an empty response!?"); + if (resJson.selectedProfile?.name?.length < 3) throw new Error(Enums.ChatColor.RED + "Invalid response from TheAltening received!"); + return { + auth: "mojang", + sessionServer: "http://sessionserver.thealtening.com", + username: resJson.selectedProfile.name, + haveCredentials: true, + session: resJson, + }; +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/commands.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/commands.ts new file mode 100644 index 0000000..1a98038 --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/commands.ts @@ -0,0 +1,302 @@ +import { dirname, join } from "path"; +import { Enums } from "../../proxy/Enums.js"; +import { Player } from "../../proxy/Player.js"; +import { config } from "./config.js"; +import { ConnectType } from "./types.js"; +import fs from "fs/promises"; +import { fileURLToPath } from "url"; +import { isValidIp } from "./utils.js"; + +const SEPARATOR = "======================================"; +const METADATA: { + name: string; + id: string; + version: string; + entry_point: string; + requirements: any[]; + load_after: any[]; + incompatibilities: any[]; +} = JSON.parse((await fs.readFile(join(dirname(fileURLToPath(import.meta.url)), "metadata.json"))).toString()); + +export function sendPluginChatMessage(client: Player, ...components: { text: string; color: string; [otherFields: string]: any }[]) { + if (components.length == 0) throw new Error("There must be one or more passed components!"); + else { + client.ws.send( + client.serverSerializer.createPacketBuffer({ + name: "chat", + params: { + message: JSON.stringify({ + text: "[EagPAAS] ", + color: "gold", + extra: components, + }), + }, + }) + ); + } +} + +export function handleCommand(sender: Player, cmd: string): void { + switch (cmd.toLowerCase().split(/ /gim)[0]) { + default: + sendPluginChatMessage(sender, { + text: `"${cmd.split(/ /gim, 1)[0]}" is not a valid command!`, + color: "red", + }); + break; + case "/eag-help": + helpCommand(sender); + break; + case "/eag-toggleparticles": + toggleParticles(sender); + break; + case "/eag-switchservers": + switchServer(cmd, sender); + break; + } +} + +export function helpCommand(sender: Player) { + sendPluginChatMessage(sender, { + text: SEPARATOR, + color: "yellow", + }); + sendPluginChatMessage(sender, { + text: "Available Commands:", + color: "aqua", + }); + sendPluginChatMessage(sender, { + text: "/eag-help", + color: "light_green", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to run this command!", + }, + clickEvent: { + action: "run_command", + value: "/eag-help", + }, + extra: [ + { + text: " - Prints out a list of commmands", + color: "aqua", + }, + ], + }); + sendPluginChatMessage(sender, { + text: "/eag-toggleparticles", + color: "light_green", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to run this command!", + }, + clickEvent: { + action: "run_command", + value: "/eag-toggleparticles", + }, + extra: [ + { + text: " - Toggles whether or not particles should be rendered/shown on the client. Turning this on can potentially boost FPS.", + color: "aqua", + }, + ], + }); + sendPluginChatMessage(sender, { + text: `/eag-switchservers ${config.allowCustomPorts ? " [port]" : ""}`, + color: "light_green", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to paste this command to chat!", + }, + clickEvent: { + action: "suggest_command", + value: `/eag-switchservers ${config.allowCustomPorts ? " [port]" : ""}`, + }, + extra: [ + { + text: " - Switch between servers on-the-fly. Switching to servers in online mode requires logging in via online mode or TheAltening!", + color: "aqua", + }, + ], + }); + sendPluginChatMessage(sender, { + text: `Running ${METADATA.name} on version v${METADATA.version}.`, + color: "gray", + }); + sendPluginChatMessage(sender, { + text: SEPARATOR, + color: "yellow", + }); +} + +export function toggleParticles(sender: Player) { + const listener = (sender as any)._particleListener; + if (listener != null) { + sender.removeListener("vanillaPacket", listener); + (sender as any)._particleListener = undefined; + sendPluginChatMessage(sender, { + text: "Disabled particle hider!", + color: "red", + }); + } else { + (sender as any)._particleListener = (packet: { name: string; params: any; cancel: boolean }, origin: "SERVER" | "CLIENT") => { + if (origin == "SERVER") { + if (packet.name == "world_particles") { + packet.cancel = true; + } else if (packet.name == "world_event") { + if (packet.params.effectId >= 2000) { + packet.cancel = true; + } + } + } + }; + sender.on("vanillaPacket", (sender as any)._particleListener); + sendPluginChatMessage(sender, { + text: "Enabled particle hider!", + color: "green", + }); + } +} + +export async function switchServer(cmd: string, sender: Player) { + if ((sender as any)._serverSwitchLock) { + return sendPluginChatMessage(sender, { + text: `There is already a pending server switch - please wait, and be patient!`, + color: "red", + }); + } + let split = cmd.split(/ /gim).slice(1), + mode = split[0]?.toLowerCase(), + ip = split[1], + port = split[2]; + if (mode != "online" && mode != "offline") { + return sendPluginChatMessage(sender, { + text: `Invalid command usage - please provide a valid mode! `, + color: "red", + extra: [ + { + text: `/eag-switchservers ${config.allowCustomPorts ? " [port]" : ""}.`, + color: "gold", + }, + ], + }); + } + if (ip == null) { + return sendPluginChatMessage(sender, { + text: `Invalid command usage - please provide a valid IP or hostname (like example.com, 1.2.3.4, etc.)! `, + color: "red", + extra: [ + { + text: `/eag-switchservers ${config.allowCustomPorts ? " [port]" : ""}.`, + color: "gold", + }, + ], + }); + } + if (port != null && (isNaN(Number(port)) || Number(port) < 1 || Number(port) > 65535)) { + return sendPluginChatMessage(sender, { + text: `Invalid command usage - a port must be a number above 0 and below 65536! `, + color: "red", + extra: [ + { + text: `/eag-switchservers ${config.allowCustomPorts ? " [port]" : ""}.`, + color: "gold", + }, + ], + }); + } + if (port != null && !config.allowCustomPorts) { + return sendPluginChatMessage(sender, { + text: `Invalid command usage - custom server ports are disabled on this proxy instance! `, + color: "red", + extra: [ + { + text: `/eag-switchservers ${config.allowCustomPorts ? " [port]" : ""}.`, + color: "gold", + }, + ], + }); + } + + let connectionType = mode == "offline" ? ConnectType.OFFLINE : ConnectType.ONLINE, + addr = ip, + addrPort = Number(port); + if (connectionType == ConnectType.ONLINE) { + if ((sender as any)._onlineSession == null) { + sendPluginChatMessage(sender, { + text: `You either connected to this proxy under offline mode, or your online/TheAltening session has timed out and has become invalid.`, + color: "red", + }); + return sendPluginChatMessage(sender, { + text: `To switch to online servers, please reconnect and log-in through online/TheAltening mode.`, + color: "red", + }); + } else { + if (!(await isValidIp(addr))) { + return sendPluginChatMessage(sender, { + text: "This IP is invalid!", + color: "red", + }); + } + const savedAuth = (sender as any)._onlineSession; + sendPluginChatMessage(sender, { + text: `(joining server under ${savedAuth.username}/your ${savedAuth.isTheAltening ? "TheAltening" : "Minecraft"} account's username)`, + color: "aqua", + }); + sendPluginChatMessage(sender, { + text: "Attempting to switch servers, please wait... (if you don't get connected to the target server after a while, the server might not be a Minecraft server at all. Reconnect and try again.)", + color: "gray", + }); + (sender as any)._serverSwitchLock = true; + try { + await sender.switchServers({ + host: addr, + port: addrPort, + version: "1.8.8", + keepAlive: false, + skipValidation: true, + hideErrors: true, + ...savedAuth, + }); + (sender as any)._serverSwitchLock = false; + } catch (err) { + if (sender.state! != Enums.ClientState.DISCONNECTED) { + sender.disconnect( + Enums.ChatColor.RED + + `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (addr.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}` + ); + } + } + } + } else { + sendPluginChatMessage(sender, { + text: `(joining server under ${sender.username}/Eaglercraft username)`, + color: "aqua", + }); + sendPluginChatMessage(sender, { + text: "Attempting to switch servers, please wait... (if you don't get connected to the target server for a while, the server might be online only)", + color: "gray", + }); + try { + (sender as any)._serverSwitchLock = true; + await sender.switchServers({ + host: addr, + port: addrPort, + version: "1.8.8", + username: sender.username, + auth: "offline", + keepAlive: false, + skipValidation: true, + hideErrors: true, + }); + (sender as any)._serverSwitchLock = false; + } catch (err) { + if (sender.state! != Enums.ClientState.DISCONNECTED) { + sender.disconnect( + Enums.ChatColor.RED + + `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (addr.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}` + ); + } + } + } +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/config.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/config.ts new file mode 100644 index 0000000..68f40fb --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/config.ts @@ -0,0 +1,12 @@ +export const config = { + bindInternalServerPort: 25569, + bindInternalServerIp: "127.0.0.1", + allowCustomPorts: true, + allowDirectConnectEndpoints: true, + disallowHypixel: false, + showDisclaimers: false, + authentication: { + enabled: false, + password: "nope", + }, +}; diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/index.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/index.ts new file mode 100644 index 0000000..737d796 --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/index.ts @@ -0,0 +1,143 @@ +import { config } from "./config.js"; +import { createServer } from "minecraft-protocol"; +import { ClientState, ConnectionState, ConnectType, ServerGlobals } from "./types.js"; +import { handleConnect, hushConsole, isValidIp, sendChatComponent, setSG } from "./utils.js"; +import path from "path"; +import { readFileSync } from "fs"; +import { handleCommand } from "./commands.js"; +import { registerEndpoints } from "./service/endpoints.js"; + +const PluginManager = PLUGIN_MANAGER; +const metadata = JSON.parse( + readFileSync(process.platform == "win32" ? path.join(path.dirname(new URL(import.meta.url).pathname), "metadata.json").slice(1) : path.join(path.dirname(new URL(import.meta.url).pathname), "metadata.json")).toString() +); + +const Logger = PluginManager.Logger; +const Enums = PluginManager.Enums; +const Chat = PluginManager.Chat; +const Constants = PluginManager.Constants; +const Motd = PluginManager.Motd; +const Player = PluginManager.Player; +const MineProtocol = PluginManager.MineProtocol; +const EaglerSkins = PluginManager.EaglerSkins; +const Util = PluginManager.Util; +hushConsole(); + +const logger = new Logger("EaglerProxyAAS"); +logger.info(`Starting ${metadata.name} v${metadata.version}...`); +logger.info(`(internal server port: ${config.bindInternalServerPort}, internal server IP: ${config.bindInternalServerIp})`); + +logger.info("Starting internal server..."); +let server = createServer({ + host: config.bindInternalServerIp, + port: config.bindInternalServerPort, + motdMsg: `${Enums.ChatColor.GOLD}EaglerProxy as a Service`, + "online-mode": false, + version: "1.8.9", + }), + sGlobals: ServerGlobals = { + server: server, + players: new Map(), + }; +setSG(sGlobals); + +server.on("login", async (client) => { + const proxyPlayer = PluginManager.proxy.players.get(client.username); + if (proxyPlayer != null) { + const url = new URL(proxyPlayer.ws.httpRequest.url, `http${PluginManager.proxy.config.tls?.enabled ? "s" : ""}://${proxyPlayer.ws.httpRequest.headers.host}`); + let host = url.searchParams.get("ip"), + port = url.searchParams.get("port"), + type = url.searchParams.get("authType") as any; + let params: { + ip: string; + port: number; + mode: ConnectType; + session: any | null; + } = undefined; + if (host != undefined && url.searchParams.size > 0) { + if (!config.allowDirectConnectEndpoints) { + return proxyPlayer.disconnect(Enums.ChatColor.RED + "Direct connect endpoints are disabled"); + } + if (config.disallowHypixel && /^(?:[\w-]+\.)?hypixel\.net$/.test(host)) { + return proxyPlayer.disconnect(Enums.ChatColor.RED + "Hypixel is disabled for this proxy"); + } + if (isNaN(Number(port)) && port != null) return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad port number"); + else if (port == null) port = "25565"; + if (!(await isValidIp(host))) { + return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad host"); + } + if (type != "OFFLINE" && type != "ONLINE" && type != "THEALTENING" && type != null) { + return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad authType provided"); + } else if (type == null) type = undefined; + type = type == undefined ? undefined : type == "OFFLINE" ? ConnectType.OFFLINE : type == "ONLINE" ? ConnectType.ONLINE : ConnectType.THEALTENING; + let sess = undefined; + // try { + // sess = JSON.parse(url.searchParams.get("session")); + // } catch (e) { + // console.log(e); + // return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad session data provided (get a new URL?)"); + // } + // if (sess && sess.expires_on != null && sess.expires_on < Date.now()) { + // return proxyPlayer.disconnect(Enums.ChatColor.RED + "Session expired (get a new URL/try reloggging?)"); + // } + + params = { + ip: host, + port: Number(port), + mode: type, + session: sess, + }; + } + + logger.info(`Client ${client.username} has connected to the authentication server.`); + client.on("end", () => { + sGlobals.players.delete(client.username); + logger.info(`Client ${client.username} has disconnected from the authentication server.`); + }); + const cs: ClientState = { + state: ConnectionState.AUTH, + gameClient: client, + token: null, + lastStatusUpdate: null, + }; + sGlobals.players.set(client.username, cs); + handleConnect(cs, params); + } else { + logger.warn(`Proxy player object is null for ${client.username}?!`); + client.end("Indirect connection to internal authentication server detected!"); + } +}); + +logger.info("Redirecting backend server IP... (this is required for the plugin to function)"); +CONFIG.adapter.server = { + host: config.bindInternalServerIp, + port: config.bindInternalServerPort, +}; +CONFIG.adapter.motd = { + l1: Enums.ChatColor.GOLD + "EaglerProxy as a Service", +}; + +if (config.allowDirectConnectEndpoints) { + PLUGIN_MANAGER.addListener("proxyFinishLoading", () => { + registerEndpoints(); + if (config.allowDirectConnectEndpoints) { + PluginManager.proxy.config.motd = "REALTIME"; + PluginManager.proxy.on("fetchMotd", (ws, req, result) => { + let url = new URL(req.url, "https://bogus.lol"), + ip = url.searchParams.get("ip"), + port = url.searchParams.get("port"); + port = port || "25565"; + if (!config.allowCustomPorts && port != "25565") return; + if (ip != null && !isNaN(Number(port))) { + // check if ip is public + result.motd = new Promise(async (res) => { + if (await isValidIp(ip)) { + res(await Motd.MOTD.generateMOTDFromPing(ip, Number(port), PluginManager.proxy.config.useNatives || true)); + } + res(null); + }); + } + }); + } + }); +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json b/eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json new file mode 100644 index 0000000..2be802c --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json @@ -0,0 +1,34 @@ +{ + "name": "EaglerProxy as a Service", + "id": "eagpaas", + "version": "2.0.0", + "entry_point": "index.js", + "requirements": [ + { + "id": "eaglerproxy", + "version": "any" + }, + { + "id": "module:vec3", + "version": "^0.1.0" + }, + { + "id": "module:prismarine-chunk", + "version": "^1.33.0" + }, + { + "id": "module:prismarine-block", + "version": "^1.16.0" + }, + { + "id": "module:prismarine-registry", + "version": "^1.6.0" + }, + { + "id": "module:minecraft-protocol", + "version": "^1.40.0" + } + ], + "load_after": [], + "incompatibilities": [] +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts new file mode 100644 index 0000000..2e8fcbe --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts @@ -0,0 +1,173 @@ +import { ServerDeviceCodeResponse, auth } from "../auth.js"; +import { config } from "../config.js"; + +const LINK_STR = ` + + + + EagPAAS - Connect + + + + +

EagPAAS - Connect to Server

+

+ Hello there! To connect to this Minecraft server through a server list entry, + use this URL: (connect from any recent + EaglercraftX client via Multiplayer > Direct Connect) +

loading...

+ + If your Eaglercraft client supports vanilla:// URLs, this will also work: +

loading...

+ + Note that your session will eventually expire, and you will need to log back in again. +

+ + + +`; + +export async function registerEndpoints() { + const proxy = PLUGIN_MANAGER.proxy; + proxy.on("httpConnection", (req, res, ctx) => { + if (req.url.startsWith("/eagpaas/link")) { + ctx.handled = true; + res.setHeader("Content-Type", "text/html").writeHead(200).end(LINK_STR); + } else if (req.url.startsWith("/eagpaas/metadata")) { + ctx.handled = true; + res.writeHead(200).end( + JSON.stringify({ + branding: "EagProxyAAS", + version: "1", + }) + ); + } else if (req.url.startsWith("/eagpaas/validate")) { + ctx.handled = true; + if (config.authentication.enabled) { + if (req.headers["authorization"] !== `Basic ${config.authentication.password}`) { + return res.writeHead(403).end( + JSON.stringify({ + success: false, + reason: "Access Denied", + }) + ); + } + } + res.writeHead(200).end( + JSON.stringify({ + success: true, + }) + ); + } + }); + + proxy.on("wsConnection", (ws, req, ctx) => { + try { + if (req.url.startsWith("/eagpaas/token")) { + ctx.handled = true; + if (config.authentication.enabled) { + if (req.headers.authorization !== `Basic ${config.authentication.password}`) { + ws.send( + JSON.stringify({ + type: "ERROR", + error: "Access Denied", + }) + ); + ws.close(); + return; + } + } + + const quit = { quit: false }, + authHandler = auth(quit), + codeCallback = (code: ServerDeviceCodeResponse) => { + ws.send( + JSON.stringify({ + type: "CODE", + data: code, + }) + ); + }; + ws.once("close", () => { + quit.quit = true; + }); + authHandler + .on("code", codeCallback) + .on("error", (err) => { + ws.send( + JSON.stringify({ + type: "ERROR", + reason: err, + }) + ); + ws.close(); + }) + .on("done", (result) => { + ws.send( + JSON.stringify({ + type: "COMPLETE", + data: result, + }) + ); + ws.close(); + }); + } else if (req.url.startsWith("/eagpaas/ping")) { + ctx.handled = true; + if (config.authentication.enabled) { + if (req.headers.authorization !== `Basic ${config.authentication.password}`) { + ws.send( + JSON.stringify({ + type: "ERROR", + error: "Access Denied", + }) + ); + ws.close(); + return; + } + } + + ws.once("message", (_) => { + ws.send(_); + ws.close(); + }); + } + } catch (err) {} + }); +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/types.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/types.ts new file mode 100644 index 0000000..10e952d --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/types.ts @@ -0,0 +1,51 @@ +import { Client, Server } from "minecraft-protocol"; + +export type ServerGlobals = { + server: Server; + players: Map; +}; + +export type ClientState = { + state: ConnectionState; + gameClient: Client; + token?: string; + lastStatusUpdate: number; +}; + +export enum ConnectionState { + AUTH, + SUCCESS, + DISCONNECTED, +} + +export enum ChatColor { + BLACK = "§0", + DARK_BLUE = "§1", + DARK_GREEN = "§2", + DARK_CYAN = "§3", + DARK_RED = "§4", + PURPLE = "§5", + GOLD = "§6", + GRAY = "§7", + DARK_GRAY = "§8", + BLUE = "§9", + BRIGHT_GREEN = "§a", + CYAN = "§b", + RED = "§c", + PINK = "§d", + YELLOW = "§e", + WHITE = "§f", + // text styling + OBFUSCATED = "§k", + BOLD = "§l", + STRIKETHROUGH = "§m", + UNDERLINED = "§n", + ITALIC = "§o", + RESET = "§r", +} + +export enum ConnectType { + ONLINE = "ONLINE", + OFFLINE = "OFFLINE", + THEALTENING = "THEALTENING", +} diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts new file mode 100644 index 0000000..7cee224 --- /dev/null +++ b/eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts @@ -0,0 +1,1021 @@ +import { ConnectType, ServerGlobals } from "./types.js"; +import * as Chunk from "prismarine-chunk"; +import * as Block from "prismarine-block"; +import * as Registry from "prismarine-registry"; +import vec3 from "vec3"; +import { Client } from "minecraft-protocol"; +import { ClientState, ConnectionState } from "./types.js"; +import { auth, ServerDeviceCodeResponse } from "./auth.js"; +import { config } from "./config.js"; +import { handleCommand } from "./commands.js"; +import { getTokenProfileTheAltening } from "./auth_thealtening.js"; +import { resolve4, resolveSrv } from "dns/promises"; + +const { Vec3 } = vec3 as any; +const Enums = PLUGIN_MANAGER.Enums; +const Util = PLUGIN_MANAGER.Util; +const MAX_LIFETIME_CONNECTED = 10 * 60 * 1000, + MAX_LIFETIME_AUTH = 5 * 60 * 1000, + MAX_LIFETIME_LOGIN = 1 * 60 * 1000; +const REGISTRY = Registry.default("1.8"), + McBlock = (Block as any).default("1.8"), + LOGIN_CHUNK = generateSpawnChunk().dump(); +const logger = new PLUGIN_MANAGER.Logger("PlayerHandler"); + +let SERVER: ServerGlobals = null; + +export function hushConsole() { + const ignoredMethod = () => {}; + global.console.info = ignoredMethod; + global.console.warn = ignoredMethod; + global.console.error = ignoredMethod; + global.console.debug = ignoredMethod; +} + +export async function isValidIp(ip: string): Promise { + const hostPart = ip.split(":")[0]; + const ipFormat = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; + const match = hostPart.match(ipFormat); + + if (match) { + const octets = match.slice(1).map(Number); + if (octets.some((octet) => isNaN(octet) || octet < 0 || octet > 255)) return false; + + const [a, b, c, d] = octets; + if ( + a === 10 || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 169 && b === 254) || + a === 127 || + a === 0 || + (a === 100 && b >= 64 && b <= 127) || + (a === 192 && b === 0 && c === 0) || + (a === 192 && b === 0 && c === 2) || + (a === 198 && b === 51 && c === 100) || + (a === 203 && b === 0 && c === 113) || + a >= 224 || + (a === 192 && b === 88 && c === 99) || + (a === 198 && b >= 18 && b <= 19) || + (a === 192 && b === 52 && c === 193) + ) + return false; + + return true; + } + + const hostnameRegex = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; + if (!hostnameRegex.test(hostPart)) return false; + + const lowerHost = hostPart.toLowerCase(); + if ( + ["localhost", "local", "0.0.0.0", "127.0.0.1", "::1"].includes(lowerHost) || + lowerHost.endsWith(".local") || + lowerHost.endsWith(".localhost") || + lowerHost.endsWith(".internal") || + lowerHost.endsWith(".intranet") || + lowerHost.endsWith(".localdomain") || + lowerHost.endsWith(".lan") + ) + return false; + + try { + if (lowerHost.startsWith("_minecraft._tcp.")) { + const srvRecords = await resolveSrv(hostPart); + return srvRecords && srvRecords.length > 0; + } + + const addresses = await resolve4(hostPart); + if (addresses && addresses.length > 0) { + return addresses.some((addr) => { + const ipMatch = addr.match(ipFormat); + if (ipMatch) { + const [a, b, c, d] = ipMatch.slice(1).map(Number); + return !(a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || a === 127 || a === 0); + } + return false; + }); + } + } catch (e) { + if (!lowerHost.startsWith("_minecraft._tcp.")) { + try { + const srvRecords = await resolveSrv(`_minecraft._tcp.${hostPart}`); + return srvRecords && srvRecords.length > 0; + } catch (e) { + return false; + } + } + return false; + } + + return true; +} + +function validateSessionObject(session: any) { + if (typeof session !== "object" || session === null) return false; + + const hasValidAuth = typeof session.auth === "string"; + const hasValidUsername = typeof session.username === "string"; + const hasValidExpiresOn = typeof session.expires_on === "number" || session.expires_on instanceof Date; + + if (!hasValidAuth || !hasValidUsername || !hasValidExpiresOn) return false; + + if (typeof session.session !== "object" || session.session === null) return false; + + const { session: sessionData } = session; + + const hasValidAccessToken = typeof sessionData.accessToken === "string"; + const hasValidClientToken = typeof sessionData.clientToken === "string"; + + if (!hasValidAccessToken || !hasValidClientToken) return false; + + if (typeof sessionData.selectedProfile !== "object" || sessionData.selectedProfile === null) return false; + + const hasValidProfileId = typeof sessionData.selectedProfile.id === "string"; + const hasValidProfileName = typeof sessionData.selectedProfile.name === "string"; + + if (!hasValidProfileId || !hasValidProfileName) return false; + + // Ensure no extra properties exist + const validSessionKeys = ["auth", "username", "expires_on", "session"]; + const validSessionDataKeys = ["accessToken", "clientToken", "selectedProfile"]; + const validSelectedProfileKeys = ["id", "name"]; + + if (Object.keys(session).some((key) => !validSessionKeys.includes(key))) return false; + if (Object.keys(sessionData).some((key) => !validSessionDataKeys.includes(key))) return false; + if (Object.keys(sessionData.selectedProfile).some((key) => !validSelectedProfileKeys.includes(key))) return false; + + return true; +} + +export function setSG(svr: ServerGlobals) { + SERVER = svr; +} + +export function disconectIdle() { + SERVER.players.forEach((client) => { + if (client.state == ConnectionState.AUTH && Date.now() - client.lastStatusUpdate > MAX_LIFETIME_AUTH) { + client.gameClient.end("Timed out waiting for user to login via Microsoft!"); + } else if (client.state == ConnectionState.SUCCESS && Date.now() - client.lastStatusUpdate > MAX_LIFETIME_CONNECTED) { + client.gameClient.end(Enums.ChatColor.RED + "Please enter the IP of the server you'd like to connect to in chat."); + } + }); +} + +export function handleConnect(client: ClientState, additionalParams: { ip: string; port: number; mode: ConnectType; session: any }) { + client.gameClient.write("login", { + entityId: 1, + gameMode: 2, + dimension: 1, + difficulty: 1, + maxPlayers: 1, + levelType: "flat", + reducedDebugInfo: false, + }); + client.gameClient.write("map_chunk", { + x: 0, + z: 0, + groundUp: true, + bitMap: 0xffff, + chunkData: LOGIN_CHUNK, + }); + client.gameClient.write("position", { + x: 0, + y: 65, + z: 8.5, + yaw: -90, + pitch: 0, + flags: 0x01, + }); + + client.gameClient.write("playerlist_header", { + header: JSON.stringify({ + text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `, + }), + footer: JSON.stringify({ + text: `${Enums.ChatColor.GOLD}Please wait for instructions.`, + }), + }); + + if (additionalParams != null && additionalParams.ip != null && additionalParams.port != null) { + sendMessage(client.gameClient, `${Enums.ChatColor.GREEN}Automatically connecting to server ${Enums.ChatColor.GOLD}${additionalParams.ip}:${additionalParams.port}${Enums.ChatColor.GREEN}.`); + } + if (additionalParams && additionalParams.session && additionalParams.session.expires_on - Date.now() > 24 * 60 * 60 * 1000) { + sendMessage( + client.gameClient, + `${Enums.ChatColor.RED}Your session token is valid for ${Math.floor((additionalParams.session.expires_on - Date.now()) / 1000 / 60)} more minutes, and will expire in less than 24 hours! Please obtain a new session URL.` + ); + } + onConnect(client, additionalParams); +} + +export function awaitCommand(client: Client, filter: (msg: string) => boolean): Promise { + return new Promise((res, rej) => { + const onMsg = (packet) => { + if (filter(packet.message)) { + client.removeListener("chat", onMsg); + client.removeListener("end", onEnd); + res(packet.message); + } + }; + const onEnd = () => rej("Client disconnected before promise could be resolved"); + client.on("chat", onMsg); + client.on("end", onEnd); + }); +} + +export function sendMessage(client: Client, msg: string) { + client.write("chat", { + message: JSON.stringify({ text: msg }), + position: 1, + }); +} + +export function sendCustomMessage(client: Client, msg: string, color: string, ...components: { text: string; color: string }[]) { + client.write("chat", { + message: JSON.stringify( + components.length > 0 + ? { + text: msg, + color, + extra: components, + } + : { text: msg, color } + ), + position: 1, + }); +} + +export function sendChatComponent(client: Client, component: any) { + client.write("chat", { + message: JSON.stringify(component), + position: 1, + }); +} + +export function sendMessageWarning(client: Client, msg: string) { + client.write("chat", { + message: JSON.stringify({ + text: msg, + color: "yellow", + }), + position: 1, + }); +} + +export function sendMessageLogin(client: Client, url: string, token: string) { + client.write("chat", { + message: JSON.stringify({ + text: "Please open ", + color: Enums.ChatColor.RESET, + extra: [ + { + text: "this link", + color: "gold", + clickEvent: { + action: "open_url", + value: `${url}/?otc=${token}`, + }, + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click to open me in a new window!", + }, + }, + { + text: " to authenticate via Microsoft.", + }, + ], + }), + position: 1, + }); +} + +export function updateState(client: Client, newState: "CONNECTION_TYPE" | "AUTH_THEALTENING" | "AUTH" | "SERVER", uri?: string, code?: string) { + switch (newState) { + case "CONNECTION_TYPE": + client.write("playerlist_header", { + header: JSON.stringify({ + text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `, + }), + footer: JSON.stringify({ + text: `${Enums.ChatColor.RED}Choose the connection type: 1 = online, 2 = offline, 3 = TheAltening.`, + }), + }); + break; + case "AUTH_THEALTENING": + client.write("playerlist_header", { + header: JSON.stringify({ + text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `, + }), + footer: JSON.stringify({ + text: `${Enums.ChatColor.RED}panel.thealtening.com/#generator${Enums.ChatColor.GOLD} | ${Enums.ChatColor.RED}/login `, + }), + }); + break; + case "AUTH": + if (code == null || uri == null) throw new Error("Missing code/uri required for title message type AUTH"); + client.write("playerlist_header", { + header: JSON.stringify({ + text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `, + }), + footer: JSON.stringify({ + text: `${Enums.ChatColor.RED}${uri}${Enums.ChatColor.GOLD} | Code: ${Enums.ChatColor.RED}${code}`, + }), + }); + break; + case "SERVER": + client.write("playerlist_header", { + header: JSON.stringify({ + text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `, + }), + footer: JSON.stringify({ + text: `${Enums.ChatColor.RED}/join ${config.allowCustomPorts ? " [port]" : ""}`, + }), + }); + break; + } +} + +export function printSessionMessage(client: ClientState, session: any, proxySession = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username)) { + const stringifiedSession = JSON.stringify(session), + url = new URL(proxySession.ws.httpRequest.url, "wss://" + proxySession.ws.httpRequest.headers.host); + url.searchParams.set("session", stringifiedSession); + url.protocol = "wss:"; + const secureURL = new URL("/eagpaas/link", "http://" + proxySession.ws.httpRequest.headers.host); + secureURL.searchParams.set("url", url.toString()); + const http = secureURL.toString(); + secureURL.protocol = "https:"; + const https = secureURL.toString(); + + sendChatComponent(client.gameClient, { + text: "Logged in! Use this server URL to continue using this account (open the link; try each one): ", + color: "green", + extra: [ + { + text: "[https]", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click to copy!", + }, + clickEvent: { + action: "open_url", + value: https, + }, + }, + { text: " ", color: "green" }, + { + text: "[http]", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click to copy!", + }, + clickEvent: { + action: "open_url", + value: http, + }, + }, + ], + }); + sendChatComponent(client.gameClient, { + text: "Revealing/showing the URL to others (including the underling server URL) can potentially allow others to compromise your account.\n" + "Do not click or open any of the above links if others can observe you.", + color: "red", + }); +} + +// assuming that the player will always stay at the same pos +export function playSelectSound(client: Client) { + client.write("named_sound_effect", { + soundName: "note.hat", + x: 8.5, + y: 65, + z: 8.5, + volume: 100, + pitch: 63, + }); +} + +export async function onConnect(client: ClientState, metadata?: { ip: string; port: number; mode?: ConnectType; session?: object }) { + try { + client.state = ConnectionState.AUTH; + client.lastStatusUpdate = Date.now(); + + client.gameClient.on("packet", (packet, meta) => { + if (meta.name == "client_command" && packet.payload == 1) { + client.gameClient.write("statistics", { + entries: [], + }); + } + }); + + if (config.showDisclaimers) { + sendMessageWarning(client.gameClient, `WARNING: This proxy allows you to connect to any 1.8.9 server. Gameplay has shown no major issues, but please note that EaglercraftX may flag some anticheats while playing.`); + await new Promise((res) => setTimeout(res, 2000)); + + sendMessageWarning( + client.gameClient, + `ADVISORY FOR HYPIXEL PLAYERS: THIS PROXY FALLS UNDER HYPIXEL'S "DISALLOWED MODIFICATIONS" MOD CATEGORY. JOINING THE SERVER WILL RESULT IN AN IRREPEALABLE PUNISHMENT BEING APPLIED TO YOUR ACCOUNT. YOU HAVE BEEN WARNED - PLAY AT YOUR OWN RISK!` + ); + await new Promise((res) => setTimeout(res, 2000)); + } + + if (config.authentication.enabled) { + sendCustomMessage(client.gameClient, "This instance is password-protected. Sign in with /password ", "gold"); + const password = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/password ")); + if (password === `/password ${config.authentication.password}`) { + sendCustomMessage(client.gameClient, "Successfully signed into instance!", "green"); + } else { + client.gameClient.end(Enums.ChatColor.RED + "Bad password!"); + return; + } + } + + let chosenOption: ConnectType | null = null; + if (!metadata || metadata.mode == null) { + sendCustomMessage(client.gameClient, "What would you like to do?", "gray"); + sendChatComponent(client.gameClient, { + text: "1) ", + color: "gold", + extra: [ + { + text: "Connect to an online server (Minecraft account needed)", + color: "white", + }, + ], + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to select!", + }, + + clickEvent: { + action: "run_command", + value: "$1", + }, + }); + sendChatComponent(client.gameClient, { + text: "2) ", + color: "gold", + extra: [ + { + text: "Connect to an offline server (no Minecraft account needed)", + color: "white", + }, + ], + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to select!", + }, + clickEvent: { + action: "run_command", + value: "$2", + }, + }); + sendChatComponent(client.gameClient, { + text: "3) ", + color: "gold", + extra: [ + { + text: "Connect to an online server via TheAltening account pool (no Minecraft account needed)", + color: "white", + }, + ], + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to select!", + }, + clickEvent: { + action: "run_command", + value: "$3", + }, + }); + sendCustomMessage(client.gameClient, "Select an option from the above (1 = online, 2 = offline, 3 = TheAltening), either by clicking or manually typing out the option's number on the list.", "green"); + updateState(client.gameClient, "CONNECTION_TYPE"); + + while (true) { + const option = await awaitCommand(client.gameClient, (msg) => true); + switch (option.replace(/\$/gim, "")) { + default: + sendCustomMessage(client.gameClient, `I don't understand what you meant by "${option}", please reply with a valid option!`, "red"); + break; + case "1": + chosenOption = ConnectType.ONLINE; + break; + case "2": + chosenOption = ConnectType.OFFLINE; + break; + case "3": + chosenOption = ConnectType.THEALTENING; + break; + } + if (chosenOption != null) { + if (option.startsWith("$")) playSelectSound(client.gameClient); + break; + } + } + } else chosenOption = metadata.mode; + + if (chosenOption == ConnectType.ONLINE) { + if (!metadata || !metadata.session) { + if (config.showDisclaimers) { + sendMessageWarning( + client.gameClient, + `WARNING: You will be prompted to log in via Microsoft to obtain a session token necessary to join games. Any data related to your account will not be saved and for transparency reasons this proxy's source code is available on Github.` + ); + } + await new Promise((res) => setTimeout(res, 2000)); + } + + client.lastStatusUpdate = Date.now(); + let errored = false, + savedAuth; + if (!metadata || !metadata.session) { + const quit = { quit: false }, + authHandler = auth(quit), + codeCallback = (code: ServerDeviceCodeResponse) => { + updateState(client.gameClient, "AUTH", code.verification_uri, code.user_code); + sendMessageLogin(client.gameClient, code.verification_uri, code.user_code); + }; + client.gameClient.once("end", (res) => { + quit.quit = true; + }); + + authHandler.once("error", (err) => { + if (!client.gameClient.ended) client.gameClient.end(err.message); + errored = true; + }); + if (errored) return; + authHandler.on("code", codeCallback); + await new Promise((res) => + authHandler.once("done", (result) => { + savedAuth = result; + res(result); + }) + ); + sendMessage(client.gameClient, Enums.ChatColor.BRIGHT_GREEN + "Successfully logged into Minecraft!"); + } + + client.state = ConnectionState.SUCCESS; + client.lastStatusUpdate = Date.now(); + let host: string, port: number; + if (metadata && metadata.ip != null && metadata.port != null) { + host = metadata.ip; + port = metadata.port; + } else { + updateState(client.gameClient, "SERVER"); + sendMessage(client.gameClient, `Provide a server to join. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + while (true) { + const msg = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/join")), + parsed = msg.split(/ /gi, 3); + if (parsed.length < 2) sendMessage(client.gameClient, `Please provide a server to connect to. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + else if (parsed.length > 2 && isNaN(parseInt(parsed[2]))) + sendMessage(client.gameClient, `A valid port number has to be passed! ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + else { + host = parsed[1]; + if (parsed.length > 2) port = parseInt(parsed[2]); + if (port != null && !config.allowCustomPorts) { + sendCustomMessage(client.gameClient, "You are not allowed to use custom server ports! /join " + (config.allowCustomPorts ? " [port]" : ""), "red"); + host = null; + port = null; + } else { + if (host.match(/^(?:\*\.)?((?!hypixel\.net$)[^.]+\.)*hypixel\.net$/) && config.disallowHypixel) { + sendCustomMessage( + client.gameClient, + "Disallowed server, refusing to connect! Hypixel has been known to falsely flag Eaglercraft clients, and thus we do not allow connecting to their server. /join " + (config.allowCustomPorts ? " [port]" : ""), + "red" + ); + } else if (!(await isValidIp(host))) { + sendCustomMessage(client.gameClient, "Invalid server address! /join " + (config.allowCustomPorts ? " [port]" : ""), "red"); + host = null; + port = null; + } else { + port = port ?? 25565; + break; + } + } + } + } + } + + validateSessionObject(savedAuth); + const session = (metadata ? metadata.session : undefined) || { + auth: "mojang", + username: savedAuth.selectedProfile.name, + expires_on: savedAuth.expiresOn, + session: { + accessToken: savedAuth.accessToken, + clientToken: savedAuth.selectedProfile.id, + selectedProfile: { + id: savedAuth.selectedProfile.id, + name: savedAuth.selectedProfile.name, + }, + }, + }; + // printSessionMessage(client, session); + + try { + sendChatComponent(client.gameClient, { + text: `Joining server under ${savedAuth.selectedProfile.name}/your Minecraft account's username! Run `, + color: "aqua", + extra: [ + { + text: "/eag-help", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to run this command!", + }, + clickEvent: { + action: "run_command", + value: "/eag-help", + }, + }, + { + text: " for a list of proxy commands.", + color: "aqua", + }, + ], + }); + logger.info(`Player ${client.gameClient.username} is attempting to connect to ${host}:${port} under their Minecraft account's username (${savedAuth.selectedProfile.name}) using online mode!`); + const player = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username); + player.on("vanillaPacket", (packet, origin) => { + if (origin == "CLIENT" && packet.name == "chat" && (packet.params.message as string).toLowerCase().startsWith("/eag-") && !packet.cancel) { + packet.cancel = true; + handleCommand(player, packet.params.message as string); + } + }); + + (player as any)._onlineSession = session; + + await player.switchServers({ + host: host, + port: port, + version: "1.8.8", + username: savedAuth.selectedProfile.name, + auth: "mojang", + keepAlive: false, + session: { + accessToken: savedAuth.accessToken, + clientToken: savedAuth.selectedProfile.id, + selectedProfile: { + id: savedAuth.selectedProfile.id, + name: savedAuth.selectedProfile.name, + }, + }, + skipValidation: true, + hideErrors: true, + }); + } catch (err) { + if (!client.gameClient.ended) { + client.gameClient.end( + Enums.ChatColor.RED + + `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (host.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}` + ); + } + } + } else if (chosenOption == ConnectType.THEALTENING) { + const THEALTENING_GET_TOKEN_URL = "panel.thealtening.com/#generator"; + client.state = ConnectionState.AUTH; + client.lastStatusUpdate = Date.now(); + updateState(client.gameClient, "AUTH_THEALTENING"); + + if (config.showDisclaimers) { + sendMessageWarning(client.gameClient, `WARNING: You've chosen to use an account from TheAltening's account pool. Please note that accounts and shared, and may be banned from whatever server you are attempting to join.`); + } + sendChatComponent(client.gameClient, { + text: "Please log in and generate an alt token at ", + color: "white", + extra: [ + { + text: THEALTENING_GET_TOKEN_URL, + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to open in a new window!", + }, + clickEvent: { + action: "open_url", + value: `https://${THEALTENING_GET_TOKEN_URL}`, + }, + }, + { + text: ", and then run ", + color: "white", + }, + { + text: "/login ", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Copy me to chat!", + }, + clickEvent: { + action: "suggest_command", + value: `/login `, + }, + }, + { + text: " to log in.", + color: "white", + }, + ], + }); + + let appendOptions: any; + while (true) { + const tokenResponse = await awaitCommand(client.gameClient, (msg) => msg.toLowerCase().startsWith("/login")), + splitResponse = tokenResponse.split(/ /gim, 2).slice(1); + if (splitResponse.length != 1) { + sendChatComponent(client.gameClient, { + text: "Invalid usage! Please use the command as follows: ", + color: "red", + extra: [ + { + text: "/login ", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Copy me to chat!", + }, + clickEvent: { + action: "suggest_command", + value: `/login `, + }, + }, + { + text: ".", + color: "red", + }, + ], + }); + } else { + const token = splitResponse[0]; + if (!token.endsWith("@alt.com")) { + sendChatComponent(client.gameClient, { + text: "Please provide a valid token (you can get one ", + color: "red", + extra: [ + { + text: "here", + color: "white", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to open in a new window!", + }, + clickEvent: { + action: "open_url", + value: `https://${THEALTENING_GET_TOKEN_URL}`, + }, + }, + { + text: "). ", + color: "red", + }, + { + text: "/login ", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Copy me to chat!", + }, + clickEvent: { + action: "suggest_command", + value: `/login `, + }, + }, + { + text: ".", + color: "red", + }, + ], + }); + } else { + sendCustomMessage(client.gameClient, "Validating alt token...", "gray"); + try { + appendOptions = await getTokenProfileTheAltening(token); + sendCustomMessage(client.gameClient, `Successfully validated your alt token and retrieved your session profile! You'll be joining to your preferred server as ${appendOptions.username}.`, "green"); + break; + } catch (err) { + sendChatComponent(client.gameClient, { + text: `TheAltening's servers replied with an error (${err.message}), please try again! `, + color: "red", + extra: [ + { + text: "/login ", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Copy me to chat!", + }, + clickEvent: { + action: "suggest_command", + value: `/login `, + }, + }, + { + text: ".", + color: "red", + }, + ], + }); + } + } + } + } + + client.state = ConnectionState.SUCCESS; + client.lastStatusUpdate = Date.now(); + let host: string, port: number; + if (metadata && metadata.ip != null && metadata.port != null) { + host = metadata.ip; + port = metadata.port; + } else { + updateState(client.gameClient, "SERVER"); + sendMessage(client.gameClient, `Provide a server to join. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + while (true) { + const msg = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/join")), + parsed = msg.split(/ /gi, 3); + if (parsed.length < 2) sendMessage(client.gameClient, `Please provide a server to connect to. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + else if (parsed.length > 2 && isNaN(parseInt(parsed[2]))) + sendMessage(client.gameClient, `A valid port number has to be passed! ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + else { + host = parsed[1]; + if (parsed.length > 2) port = parseInt(parsed[2]); + if (port != null && !config.allowCustomPorts) { + sendCustomMessage(client.gameClient, "You are not allowed to use custom server ports! /join ", "red"); + host = null; + port = null; + } else if (!(await isValidIp(host))) { + sendCustomMessage(client.gameClient, "Invalid server address! /join " + (config.allowCustomPorts ? " [port]" : ""), "red"); + host = null; + port = null; + } else { + port = port ?? 25565; + break; + } + } + } + } + try { + sendChatComponent(client.gameClient, { + text: `Joining server under ${appendOptions.username}/TheAltening account username! Run `, + color: "aqua", + extra: [ + { + text: "/eag-help", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to run this command!", + }, + clickEvent: { + action: "run_command", + value: "/eag-help", + }, + }, + { + text: " for a list of proxy commands.", + color: "aqua", + }, + ], + }); + logger.info(`Player ${client.gameClient.username} is attempting to connect to ${host}:${port} under their TheAltening alt token's username (${appendOptions.username}) using TheAltening mode!`); + const player = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username); + player.on("vanillaPacket", (packet, origin) => { + if (origin == "CLIENT" && packet.name == "chat" && (packet.params.message as string).toLowerCase().startsWith("/eag-") && !packet.cancel) { + packet.cancel = true; + handleCommand(player, packet.params.message as string); + } + }); + (player as any)._onlineSession = { + ...appendOptions, + isTheAltening: true, + }; + + await player.switchServers({ + host: host, + port: port, + version: "1.8.8", + keepAlive: false, + skipValidation: true, + hideErrors: true, + ...appendOptions, + }); + } catch (err) { + if (!client.gameClient.ended) { + client.gameClient.end( + Enums.ChatColor.RED + + `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (host.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}` + ); + } + } + } else { + client.state = ConnectionState.SUCCESS; + client.lastStatusUpdate = Date.now(); + let host: string, port: number; + if (metadata && metadata.ip != null && metadata.port != null) { + host = metadata.ip; + port = metadata.port; + } else { + updateState(client.gameClient, "SERVER"); + sendMessage(client.gameClient, `Provide a server to join. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + while (true) { + const msg = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/join")), + parsed = msg.split(/ /gi, 3); + if (parsed.length < 2) sendMessage(client.gameClient, `Please provide a server to connect to. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + else if (parsed.length > 2 && isNaN(parseInt(parsed[2]))) + sendMessage(client.gameClient, `A valid port number has to be passed! ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`); + else { + host = parsed[1]; + if (parsed.length > 2) port = parseInt(parsed[2]); + if (port != null && !config.allowCustomPorts) { + sendCustomMessage(client.gameClient, "You are not allowed to use custom server ports! /join ", "red"); + host = null; + port = null; + } else if (!(await isValidIp(host))) { + sendCustomMessage(client.gameClient, "Invalid server address! /join " + (config.allowCustomPorts ? " [port]" : ""), "red"); + host = null; + port = null; + } else { + port = port ?? 25565; + break; + } + } + } + } + try { + sendChatComponent(client.gameClient, { + text: `Joining server under ${client.gameClient.username}/Eaglercraft username! Run `, + color: "aqua", + extra: [ + { + text: "/eag-help", + color: "gold", + hoverEvent: { + action: "show_text", + value: Enums.ChatColor.GOLD + "Click me to run this command!", + }, + clickEvent: { + action: "run_command", + value: "/eag-help", + }, + }, + { + text: " for a list of proxy commands.", + color: "aqua", + }, + ], + }); + logger.info(`Player ${client.gameClient.username} is attempting to connect to ${host}:${port} under their Eaglercraft username (${client.gameClient.username}) using offline mode!`); + const player = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username); + player.on("vanillaPacket", (packet, origin) => { + if (origin == "CLIENT" && packet.name == "chat" && (packet.params.message as string).toLowerCase().startsWith("/eag-") && !packet.cancel) { + packet.cancel = true; + handleCommand(player, packet.params.message as string); + } + }); + + await player.switchServers({ + host: host, + port: port, + auth: "offline", + username: client.gameClient.username, + version: "1.8.8", + keepAlive: false, + skipValidation: true, + hideErrors: true, + }); + } catch (err) { + if (!client.gameClient.ended) { + client.gameClient.end( + Enums.ChatColor.RED + + `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (host.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}` + ); + } + } + } + } catch (err) { + if (!client.gameClient.ended) { + logger.error(`Error whilst processing user ${client.gameClient.username}: ${err.stack || err}`); + client.gameClient.end(Enums.ChatColor.YELLOW + "Something went wrong whilst processing your request. Please reconnect."); + } + } +} + +export function generateSpawnChunk(): Chunk.PCChunk { + const chunk = new (Chunk.default(REGISTRY))(null) as Chunk.PCChunk; + chunk.initialize(() => new McBlock(REGISTRY.blocksByName.air.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(8, 64, 8), new McBlock(REGISTRY.blocksByName.sea_lantern.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(8, 67, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(7, 65, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(7, 66, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(9, 65, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(9, 66, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(8, 65, 7), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(8, 66, 7), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(8, 65, 9), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + chunk.setBlock(new Vec3(8, 66, 9), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0)); + // chunk.setBlockLight(new Vec3(8, 65, 8), 15); + chunk.setBlockLight(new Vec3(8, 66, 8), 15); + return chunk; +} diff --git a/eaglerproxy/files/src/proxy/BungeeUtil.ts b/eaglerproxy/files/src/proxy/BungeeUtil.ts new file mode 100644 index 0000000..06303a3 --- /dev/null +++ b/eaglerproxy/files/src/proxy/BungeeUtil.ts @@ -0,0 +1,101 @@ +import { Logger } from "../logger.js"; +import mcp, { states } from "minecraft-protocol"; + +const { createSerializer, createDeserializer } = mcp; + +export namespace BungeeUtil { + export class PacketUUIDTranslator { + public serverSidePlayerUUID: string; + public clientSidePlayerUUID: string; + + static readonly CAST_UUID_SERVER: string[] = [ + "update_attributes", + "named_entity_spawn", + // drop this packet (twitch.tv integration not available anymore) + "player_info", + ]; + static readonly CAST_UUID_CLIENT: string[] = ["spectate"]; + + private _logger: Logger; + + constructor(ssPlayerUUID: string, csPlayerUUID: string) { + this.serverSidePlayerUUID = ssPlayerUUID; + this.clientSidePlayerUUID = csPlayerUUID; + this._logger = new Logger("PacketTranslator"); + } + + public translatePacketClient(packet: any, meta: any): [string, object] { + if (meta.name == "spectate") { + if (packet.target == this.clientSidePlayerUUID) { + packet.target = this.serverSidePlayerUUID; + } else if (packet.target == this.serverSidePlayerUUID) { + packet.target = this.clientSidePlayerUUID; + } + } + return [meta.name, packet]; + } + + public translatePacketServer(packet: any, meta: any): [string, object] { + if (meta.name == "update_attributes") { + for (const prop of packet.properties) { + for (const modifier of prop.modifiers) { + if (modifier.uuid == this.serverSidePlayerUUID) { + modifier.uuid = this.clientSidePlayerUUID; + } else if (modifier.uuid == this.clientSidePlayerUUID) { + modifier.uuid = this.serverSidePlayerUUID; + } + } + } + } else if (meta.name == "named_entity_spawn") { + if (packet.playerUUID == this.serverSidePlayerUUID) { + packet.playerUUID = this.clientSidePlayerUUID; + } else if (packet.playerUUID == this.clientSidePlayerUUID) { + packet.playerUUID = this.serverSidePlayerUUID; + } + } else if (meta.name == "player_info") { + for (const player of packet.data) { + if (player.UUID == this.serverSidePlayerUUID) { + player.UUID = this.clientSidePlayerUUID; + } else if (player.UUID == this.clientSidePlayerUUID) { + player.UUID = this.serverSidePlayerUUID; + } + } + } + return [meta.name, packet]; + } + } + + export function getRespawnSequence( + login: any, + serializer: any + ): [Buffer, Buffer] { + const dimset = getDimSets(login.dimension); + return [ + serializer.createPacketBuffer({ + name: "respawn", + params: { + dimension: dimset[0], + difficulty: login.difficulty, + gamemode: login.gameMode, + levelType: login.levelType, + }, + }), + serializer.createPacketBuffer({ + name: "respawn", + params: { + dimension: dimset[1], + difficulty: login.difficulty, + gamemode: login.gameMode, + levelType: login.levelType, + }, + }), + ]; + } + + function getDimSets(loginDim: number): [number, number] { + return [ + loginDim == -1 ? 0 : loginDim == 0 ? -1 : loginDim == 1 ? 0 : 0, + loginDim, + ]; + } +} diff --git a/eaglerproxy/files/src/proxy/Chat.ts b/eaglerproxy/files/src/proxy/Chat.ts new file mode 100644 index 0000000..1c333ec --- /dev/null +++ b/eaglerproxy/files/src/proxy/Chat.ts @@ -0,0 +1,57 @@ +import { Enums } from "./Enums.js"; + +export namespace Chat { + export type ChatExtra = { + text: string; + bold?: boolean; + italic?: boolean; + underlined?: boolean; + strikethrough?: boolean; + obfuscated?: boolean; + color?: Enums.ChatColor | "reset"; + }; + + export type Chat = { + text?: string; + bold?: boolean; + italic?: boolean; + underlined?: boolean; + strikethrough?: boolean; + obfuscated?: boolean; + color?: Enums.ChatColor | "reset"; + extra?: ChatExtra[]; + }; + + export function chatToPlainString(chat: Chat): string { + let ret = ""; + if (chat.text != null) ret += chat.text; + if (chat.extra != null) { + chat.extra.forEach((extra) => { + let append = ""; + if (extra.bold) append += Enums.ChatColor.BOLD; + if (extra.italic) append += Enums.ChatColor.ITALIC; + if (extra.underlined) append += Enums.ChatColor.UNDERLINED; + if (extra.strikethrough) append += Enums.ChatColor.STRIKETHROUGH; + if (extra.obfuscated) append += Enums.ChatColor.OBFUSCATED; + if (extra.color) + append += + extra.color == "reset" + ? Enums.ChatColor.RESET + : resolveColor(extra.color); + append += extra.text; + ret += append; + }); + } + return ret; + } + + const ccValues = Object.values(Enums.ChatColor); + const ccKeys = Object.keys(Enums.ChatColor).map((str) => str.toLowerCase()); + + function resolveColor(colorStr: string) { + return ( + Object.values(Enums.ChatColor)[ccKeys.indexOf(colorStr.toLowerCase())] ?? + colorStr + ); + } +} diff --git a/eaglerproxy/files/src/proxy/Constants.ts b/eaglerproxy/files/src/proxy/Constants.ts new file mode 100644 index 0000000..4859663 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Constants.ts @@ -0,0 +1,17 @@ +import * as meta from "../meta.js"; + +export namespace Constants { + export const EAGLERCRAFT_SKIN_CHANNEL_NAME: string = "EAG|Skins-1.8"; + export const MAGIC_ENDING_SERVER_SKIN_DOWNLOAD_BUILTIN: number[] = [0x00, 0x00, 0x00]; + export const MAGIC_ENDING_CLIENT_UPLOAD_SKIN_BUILTIN: number[] = [0x00, 0x05, 0x01, 0x00, 0x00, 0x00]; + export const EAGLERCRAFT_SKIN_CUSTOM_LENGTH = 64 ** 2 * 4; + + export const JOIN_SERVER_PACKET = 0x01; + export const PLAYER_LOOK_PACKET = 0x08; + + export const ICON_SQRT = 64; + export const END_BUFFER_LENGTH = ICON_SQRT ** 8; + export const IMAGE_DATA_PREPEND = "data:image/png;base64,"; +} + +export const UPGRADE_REQUIRED_RESPONSE = ` EaglerProxy landing page

426 - Upgrade Required

Hello there! It appears as if you've reached the landing page for this EaglerProxy instance. Unfortunately, you cannot connect to the proxy server from here. To connect, use this server IP/URL: loading... (connect from any recent EaglercraftX client via Multiplayer > Direct Connect)

`; diff --git a/eaglerproxy/files/src/proxy/Enums.ts b/eaglerproxy/files/src/proxy/Enums.ts new file mode 100644 index 0000000..277ddf8 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Enums.ts @@ -0,0 +1,71 @@ +export namespace Enums { + export enum PacketId { + CSLoginPacket = 0x01, + SCIdentifyPacket = 0x02, + SCDisconnectPacket = 0xff, + SCChannelMessagePacket = 0x3f, + CSChannelMessagePacket = 0x17, + CSUsernamePacket = 0x04, + SCSyncUuidPacket = 0x05, + CSSetSkinPacket = 0x07, + CSReadyPacket = 0x08, + SCReadyPacket = 0x09, + } + + export enum ChannelMessageType { + CLIENT = 0x17, + SERVER = 0x3f, + } + + export enum EaglerSkinPacketId { + CFetchSkinEaglerPlayerReq = 0x03, + SFetchSkinBuiltInRes = 0x04, + SFetchSkinRes = 0x05, + CFetchSkinReq = 0x06, + } + + export enum ClientState { + PRE_HANDSHAKE = "PRE_HANDSHAKE", + POST_HANDSHAKE = "POST_HANDSHAKE", + DISCONNECTED = "DISCONNECTED", + } + + export enum PacketBounds { + C = "C", + S = "S", + } + + export enum SkinType { + BUILTIN, + CUSTOM, + } + + export enum ChatColor { + AQUA = "§b", + BLACK = "§0", + DARK_BLUE = "§1", + DARK_GREEN = "§2", + DARK_CYAN = "§3", + DARK_RED = "§4", + PURPLE = "§5", + GOLD = "§6", + GRAY = "§7", + GREEN = "§a", + DARK_GRAY = "§8", + BLUE = "§9", + BRIGHT_GREEN = "§a", + LIGHT_PURPLE = "§d", + CYAN = "§b", + RED = "§c", + PINK = "§d", + YELLOW = "§e", + WHITE = "§f", + // text styling + OBFUSCATED = "§k", + BOLD = "§l", + STRIKETHROUGH = "§m", + UNDERLINED = "§n", + ITALIC = "§o", + RESET = "§r", + } +} diff --git a/eaglerproxy/files/src/proxy/Motd.ts b/eaglerproxy/files/src/proxy/Motd.ts new file mode 100644 index 0000000..ceed0b1 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Motd.ts @@ -0,0 +1,114 @@ +import { randomUUID } from "crypto"; +import pkg, { NewPingResult } from "minecraft-protocol"; +import { PROXY_BRANDING, PROXY_VERSION } from "../meta.js"; +import { Config } from "../launcher_types.js"; +import { Chat } from "./Chat.js"; +import { Constants } from "./Constants.js"; +import { ImageEditor } from "./skins/ImageEditor.js"; +const { ping } = pkg; + +export namespace Motd { + export class MOTD { + public jsonMotd: JSONMotd; + public image?: Buffer; + public usingNatives: boolean; + + constructor(motd: JSONMotd, native: boolean, image?: Buffer) { + this.jsonMotd = motd; + this.image = image; + this.usingNatives = native; + } + + public static async generateMOTDFromPing(host: string, port: number, useNatives: boolean): Promise { + const pingRes = await ping({ host: host, port: port }); + if (typeof pingRes.version == "string") throw new Error("Non-1.8 server detected!"); + else { + const newPingRes = pingRes as NewPingResult; + let image: Buffer; + + if (newPingRes.favicon != null) { + if (!newPingRes.favicon.startsWith(Constants.IMAGE_DATA_PREPEND)) throw new Error("Invalid MOTD image!"); + image = useNatives + ? await ImageEditor.generateEaglerMOTDImage(Buffer.from(newPingRes.favicon.substring(Constants.IMAGE_DATA_PREPEND.length), "base64")) + : await ImageEditor.generateEaglerMOTDImageJS(Buffer.from(newPingRes.favicon.substring(Constants.IMAGE_DATA_PREPEND.length), "base64")); + } + + return new MOTD( + { + brand: PROXY_BRANDING, + cracked: true, + data: { + cache: true, + icon: newPingRes.favicon != null ? true : false, + max: newPingRes.players.max, + motd: [typeof newPingRes.description == "string" ? newPingRes.description : Chat.chatToPlainString(newPingRes.description), ""], + online: newPingRes.players.online, + players: newPingRes.players.sample != null ? newPingRes.players.sample.map((v) => v.name) : [], + }, + name: "placeholder name", + secure: false, + time: Date.now(), + type: "motd", + uuid: randomUUID(), // replace placeholder with global. cached UUID + vers: `${PROXY_BRANDING}/${PROXY_VERSION}`, + }, + useNatives, + image + ); + } + } + + public static async generateMOTDFromConfig(config: Config["adapter"], useNatives: boolean): Promise { + if (typeof config.motd != "string") { + const motd = new MOTD( + { + brand: PROXY_BRANDING, + cracked: true, + data: { + cache: true, + icon: config.motd.iconURL != null ? true : false, + max: config.maxConcurrentClients, + motd: [config.motd.l1, config.motd.l2 ?? ""], + online: 0, + players: [], + }, + name: config.name, + secure: false, + time: Date.now(), + type: "motd", + uuid: randomUUID(), + vers: `${PROXY_BRANDING}/${PROXY_VERSION}`, + }, + useNatives + ); + if (config.motd.iconURL != null) { + motd.image = useNatives ? await ImageEditor.generateEaglerMOTDImage(config.motd.iconURL) : await ImageEditor.generateEaglerMOTDImageJS(config.motd.iconURL); // TODO: swap between native and pure JS + } + return motd; + } else throw new Error("MOTD is set to be forwarded in the config!"); + } + + public toBuffer(): [string, Buffer] { + return [JSON.stringify(this.jsonMotd), this.image]; + } + } + + export type JSONMotd = { + brand: string; + cracked: true; + data: { + cache: true; + icon: boolean; + max: number; + motd: [string, string]; + online: number; + players: string[]; + }; + name: string; + secure: false; + time: ReturnType; + type: "motd"; + uuid: ReturnType; + vers: string; + }; +} diff --git a/eaglerproxy/files/src/proxy/Packet.ts b/eaglerproxy/files/src/proxy/Packet.ts new file mode 100644 index 0000000..db5fd43 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Packet.ts @@ -0,0 +1,44 @@ +import { readdir } from "fs/promises"; +import { dirname, join, resolve } from "path"; +import { fileURLToPath, pathToFileURL } from "url"; +import { Enums } from "./Enums.js"; +import { Util } from "./Util.js"; + +export default interface Packet { + packetId: Enums.PacketId; + type: "packet"; + boundTo: Enums.PacketBounds; + sentAfterHandshake: boolean; + + serialize: () => Buffer; + deserialize: (packet: Buffer) => this; +} + +export async function loadPackets( + dir?: string +): Promise> { + const files = ( + await Util.recursiveFileSearch( + dir ?? join(dirname(fileURLToPath(import.meta.url)), "packets") + ) + ).filter((f) => f.endsWith(".js") && !f.endsWith(".disabled.js")); + const packetRegistry = new Map(); + for (const file of files) { + const imp = await import( + process.platform == "win32" ? pathToFileURL(file).toString() : file + ); + for (const val of Object.values(imp)) { + if (val != null) { + let e: Packet; + try { + e = new (val as any)(); + } catch {} + if (e != null && e.type == "packet") { + (e as any).class = val; + packetRegistry.set(e.packetId, e); + } + } + } + } + return packetRegistry; +} diff --git a/eaglerproxy/files/src/proxy/Player.ts b/eaglerproxy/files/src/proxy/Player.ts new file mode 100644 index 0000000..56bb541 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Player.ts @@ -0,0 +1,372 @@ +import EventEmitter from "events"; +import pkg, { Client, ClientOptions, createClient, states } from "minecraft-protocol"; +import { WebSocket } from "ws"; +import { Logger } from "../logger.js"; +import { Chat } from "./Chat.js"; +import { Enums } from "./Enums.js"; +import Packet from "./Packet.js"; +import SCDisconnectPacket from "./packets/SCDisconnectPacket.js"; +import { MineProtocol } from "./Protocol.js"; +import { EaglerSkins } from "./skins/EaglerSkins.js"; +import { Util } from "./Util.js"; +import { BungeeUtil } from "./BungeeUtil.js"; +import { IncomingMessage } from "http"; +import { Socket } from "net"; + +const { createSerializer, createDeserializer } = pkg; + +export class Player extends EventEmitter { + public ws: WebSocket & { httpRequest: IncomingMessage; _socket: Socket }; + public username?: string; + public skin?: EaglerSkins.EaglerSkin; + public uuid?: string; + public state?: Enums.ClientState = Enums.ClientState.PRE_HANDSHAKE; + public serverConnection?: Client; + + private _switchingServers: boolean = false; + private _logger: Logger; + private _alreadyConnected: boolean = false; + + public translator?: BungeeUtil.PacketUUIDTranslator; + public serverSerializer: any; + public clientSerializer: any; + public serverDeserializer: any; + public clientDeserializer: any; + private _kickMessage: string; + + constructor(ws: WebSocket & { httpRequest: IncomingMessage }, playerName?: string, serverConnection?: Client) { + super(); + this._logger = new Logger(`PlayerHandler-${playerName}`); + this.ws = ws as any; + this.username = playerName; + this.serverConnection = serverConnection; + if (this.username != null) this.uuid = Util.generateUUIDFromPlayer(this.username); + this.serverSerializer = createSerializer({ + state: states.PLAY, + isServer: true, + version: "1.8.9", + customPackets: null, + }); + this.clientSerializer = createSerializer({ + state: states.PLAY, + isServer: false, + version: "1.8.9", + customPackets: null, + }); + this.serverDeserializer = createDeserializer({ + state: states.PLAY, + isServer: true, + version: "1.8.9", + customPackets: null, + }); + this.clientDeserializer = createSerializer({ + state: states.PLAY, + isServer: true, + version: "1.8.9", + customPackets: null, + }); + } + + public initListeners() { + this.ws.on("close", () => { + this.state = Enums.ClientState.DISCONNECTED; + if (this.serverConnection) this.serverConnection.end(); + this.emit("disconnect", this); + }); + this.ws.on("message", (msg: Buffer) => { + if (msg instanceof Buffer == false) return; + const decoder = PACKET_REGISTRY.get(msg[0]); + if (decoder && decoder.sentAfterHandshake) { + if (!decoder && this.state != Enums.ClientState.POST_HANDSHAKE && msg.length >= 1) { + this._logger.warn(`Packet with ID 0x${Buffer.from([msg[0]]).toString("hex")} is missing a corresponding packet handler! Processing for this packet will be skipped.`); + } else { + let parsed: Packet, err: boolean; + try { + parsed = new decoder.class(); + parsed.deserialize(msg); + } catch (err) { + if (this.state != Enums.ClientState.POST_HANDSHAKE) this._logger.warn(`Packet ID 0x${Buffer.from([msg[0]]).toString("hex")} failed to parse! The packet will be skipped.`); + err = true; + } + if (!err) { + this.emit("proxyPacket", parsed, this); + return; + } + } + } else { + try { + const parsed = this.serverDeserializer.parsePacketBuffer(msg)?.data, + translated = this.translator.translatePacketClient(parsed.params, parsed), + packetData = { + name: translated[0], + params: translated[1], + cancel: false, + }; + this.emit("vanillaPacket", packetData, "CLIENT", this); + if (!packetData.cancel) { + (this as any)._sendPacketToServer( + this.clientSerializer.createPacketBuffer({ + name: packetData.name, + params: packetData.params, + }) + ); + } + } catch (err) { + this._logger.debug(`Client ${this.username!} sent an unrecognized packet that could not be parsed!\n${err.stack ?? err}`); + } + } + }); + } + + public write(packet: Packet) { + this.ws.send(packet.serialize()); + } + + public async read(packetId?: Enums.PacketId, filter?: (packet: Packet) => boolean): Promise { + let res; + await Util.awaitPacket(this.ws, (packet) => { + if ((packetId != null && packetId == packet[0]) || packetId == null) { + const decoder = PACKET_REGISTRY.get(packet[0]); + if (decoder != null && decoder.packetId == packet[0] && (this.state == Enums.ClientState.PRE_HANDSHAKE || decoder.sentAfterHandshake) && decoder.boundTo == Enums.PacketBounds.S) { + let parsed: Packet, + err = false; + try { + parsed = new decoder.class(); + parsed.deserialize(packet); + } catch (_err) { + err = true; + } + if (!err) { + if (filter && filter(parsed)) { + res = parsed; + return true; + } else if (filter == null) { + res = parsed; + return true; + } + } + } + } + return false; + }); + return res; + } + + public disconnect(message: Chat.Chat | string) { + if (this.state == Enums.ClientState.POST_HANDSHAKE) { + this.ws.send(Buffer.concat([[0x40], MineProtocol.writeString(typeof message == "string" ? message : JSON.stringify(message))].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))))); + this.ws.close(); + } else { + const packet = new SCDisconnectPacket(); + packet.reason = message; + this.ws.send(packet.serialize()); + this.ws.close(); + } + } + + public async connect(options: ClientOptions) { + if (this._alreadyConnected) throw new Error(`Invalid state: Player has already been connected to a server, and .connect() was just called. Please use switchServers() instead.`); + this._alreadyConnected = true; + this.serverConnection = createClient( + Object.assign( + { + version: "1.8.9", + keepAlive: false, + hideErrors: false, + }, + options + ) + ); + await this._bindListenersMineClient(this.serverConnection); + } + + public switchServers(options: ClientOptions) { + if (!this._alreadyConnected) + throw new Error( + `Invalid state: Player hasn't already been connected to a server, and .switchServers() has been called. Please use .connect() when initially connecting to a server, and only use .switchServers() if you want to switch servers.` + ); + return new Promise(async (res, rej) => { + const oldConnection = this.serverConnection; + this._switchingServers = true; + + this.ws.send( + this.serverSerializer.createPacketBuffer({ + name: "chat", + params: { + message: `${Enums.ChatColor.GRAY}Switching servers...`, + position: 1, + }, + }) + ); + this.ws.send( + this.serverSerializer.createPacketBuffer({ + name: "playerlist_header", + params: { + header: JSON.stringify({ + text: "", + }), + footer: JSON.stringify({ + text: "", + }), + }, + }) + ); + + this.serverConnection = createClient( + Object.assign( + { + version: "1.8.9", + keepAlive: false, + hideErrors: false, + }, + options + ) + ); + + await this._bindListenersMineClient(this.serverConnection, true, () => oldConnection.end()) + .then(() => { + this.emit("switchServer", this.serverConnection, this); + res(); + }) + .catch((err) => { + this.serverConnection = oldConnection; + rej(err); + }); + }); + } + + private async _bindListenersMineClient(client: Client, switchingServers?: boolean, onSwitch?: Function) { + return new Promise((res, rej) => { + let stream = false, + uuid; + const listener = (msg) => { + if (stream) { + client.writeRaw(msg); + } + }, + errListener = (err) => { + if (!stream) { + rej(err); + } else { + this.disconnect(`${Enums.ChatColor.RED}Something went wrong: ${err.stack ?? err}`); + } + }; + setTimeout(() => { + if (!stream && this.state != Enums.ClientState.DISCONNECTED) { + client.end("Timed out waiting for server connection."); + this.disconnect(Enums.ChatColor.RED + "Timed out waiting for server connection!"); + throw new Error("Timed out waiting for server connection!"); + } + }, 30000); + client.on("error", errListener); + client.on("end", (reason) => { + if (!this._switchingServers && !switchingServers) { + this.disconnect(this._kickMessage ?? reason); + } + this.ws.removeListener("message", listener); + }); + client.once("connect", () => { + this.emit("joinServer", client, this); + }); + client.on("packet", (packet, meta) => { + if (meta.name == "kick_disconnect") { + let json; + try { + json = JSON.parse(packet.reason); + } catch {} + if (json != null) { + this._kickMessage = Chat.chatToPlainString(json); + } else this._kickMessage = packet.reason; + this._switchingServers = false; + this.disconnect(this._kickMessage); + } else if (meta.name == "disconnect") { + let json; + try { + json = JSON.parse(packet.reason); + } catch {} + if (json != null) { + this._kickMessage = Chat.chatToPlainString(json); + } else this._kickMessage = packet.reason; + this._switchingServers = false; + this.disconnect(this._kickMessage); + } + if (!stream) { + if (switchingServers) { + if (meta.name == "login" && meta.state == states.PLAY && uuid) { + this.translator = new BungeeUtil.PacketUUIDTranslator(client.uuid, this.uuid); + const pckSeq = BungeeUtil.getRespawnSequence(packet, this.serverSerializer); + this.ws.send( + this.serverSerializer.createPacketBuffer({ + name: "login", + params: packet, + }) + ); + pckSeq.forEach((p) => this.ws.send(p)); + stream = true; + if (onSwitch) onSwitch(); + res(null); + } else if (meta.name == "success" && meta.state == states.LOGIN && !uuid) { + uuid = packet.uuid; + } + } else { + if (meta.name == "login" && meta.state == states.PLAY && uuid) { + this.translator = new BungeeUtil.PacketUUIDTranslator(client.uuid, this.uuid); + this.ws.send( + this.serverSerializer.createPacketBuffer({ + name: "login", + params: packet, + }) + ); + stream = true; + if (onSwitch) onSwitch(); + res(null); + } else if (meta.name == "success" && meta.state == states.LOGIN && !uuid) { + uuid = packet.uuid; + } + } + } else { + const translated = this.translator!.translatePacketServer(packet, meta), + eventData = { + name: translated[0], + params: translated[1], + cancel: false, + }; + this.emit("vanillaPacket", eventData, "SERVER", this); + if (!eventData.cancel) { + this.ws.send( + this.serverSerializer.createPacketBuffer({ + name: eventData.name, + params: eventData.params, + }) + ); + } + } + }); + (this as any)._sendPacketToServer = listener; + }); + } +} + +interface PlayerEvents { + switchServer: (connection: Client, player: Player) => void; + joinServer: (connection: Client, player: Player) => void; + // for vanilla game packets, bind to connection object instead + proxyPacket: (packet: Packet, player: Player) => void; + vanillaPacket: ( + packet: { + name: string; + params: any; + cancel: boolean; + }, + origin: "CLIENT" | "SERVER", + player: Player + ) => void; + disconnect: (player: Player) => void; +} + +export declare interface Player { + on(event: U, listener: PlayerEvents[U]): this; + once(event: U, listener: PlayerEvents[U]): this; + + emit(event: U, ...args: Parameters): boolean; +} diff --git a/eaglerproxy/files/src/proxy/Protocol.ts b/eaglerproxy/files/src/proxy/Protocol.ts new file mode 100644 index 0000000..0064aa9 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Protocol.ts @@ -0,0 +1,100 @@ +import { encodeULEB128 as _encodeVarInt, decodeULEB128 as _decodeVarInt } from "@thi.ng/leb128"; +import { Enums } from "./Enums.js"; +import { Util } from "./Util.js"; + +// reference: https://wiki.vg/index.php?title=Protocol&oldid=7368 (id: 73) +// use https://hexed.it/ for hex analysis, dumps.ts for example dumps +// this simple wrapper only contains utilities for reading & writing VarInts and strings, which are the +// datatypes being used thus far. There may be more, but however, they will be added here as needed. + +export namespace MineProtocol { + export type ReadResult = { + value: T; + // the new buffer, but with the bytes being read being completely removed + // very useful when it comes to chaining + newBuffer: Buffer; + }; + + export type UUID = string; + + export function writeVarInt(int: number): Buffer { + return Buffer.from(_encodeVarInt(int)); + } + + export function readVarInt(buff: Buffer, offset?: number): ReadResult { + buff = offset ? buff.subarray(offset) : buff; + const read = _decodeVarInt(buff), + len = read[1]; + return { + // potential oversight? + value: Number(read[0]), + newBuffer: buff.subarray(len), + }; + } + + export function writeVarLong(long: number): Buffer { + return writeVarInt(long); + } + + export function readVarLong(buff: Buffer, offset?: number): ReadResult { + return readVarInt(buff, offset); + } + + export function writeBinary(data: Buffer): Buffer { + return Buffer.concat([writeVarInt(data.length), data]); + } + + export function readBinary(buff: Buffer, offset?: number): ReadResult { + buff = offset ? buff.subarray(offset) : buff; + const len = readVarInt(buff), + data = len.newBuffer.subarray(0, len.value); + return { + value: data, + newBuffer: len.newBuffer.subarray(len.value), + }; + } + + export function writeString(str: string): Buffer { + const bufferized = Buffer.from(str, "utf8"), + len = writeVarInt(bufferized.length); + return Buffer.concat([len, bufferized]); + } + + export function readString(buff: Buffer, offset?: number): ReadResult { + buff = offset ? buff.subarray(offset) : buff; + const len = readVarInt(buff), + str = len.newBuffer.subarray(0, len.value).toString("utf8"); + return { + value: str, + newBuffer: len.newBuffer.subarray(len.value), + }; + } + + const _readShort = (a: number, b: number) => (a << 8) | (b << 0); + + export function readShort(buff: Buffer, offset?: number): ReadResult { + buff = offset ? buff.subarray(offset) : buff; + return { + value: _readShort(buff[0], buff[1]), + newBuffer: buff.subarray(2), + }; + } + + export function writeShort(num: number): Buffer { + const alloc = Buffer.alloc(2); + alloc.writeInt16BE(num); + return alloc; + } + + export function readUUID(buff: Buffer, offset?: number): ReadResult { + buff = offset ? buff.subarray(offset) : buff; + return { + value: Util.uuidBufferToString(buff.subarray(0, 16)), + newBuffer: buff.subarray(16), + }; + } + + export function writeUUID(uuid: string | Buffer): Buffer { + return typeof uuid == "string" ? Util.uuidStringToBuffer(uuid) : uuid; + } +} diff --git a/eaglerproxy/files/src/proxy/Proxy.ts b/eaglerproxy/files/src/proxy/Proxy.ts new file mode 100644 index 0000000..a58cc10 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Proxy.ts @@ -0,0 +1,412 @@ +import { WebSocket, WebSocketServer } from "ws"; +import { Config } from "../launcher_types.js"; +import { Logger } from "../logger.js"; +import Packet, { loadPackets } from "./Packet.js"; +import * as http from "http"; +import * as https from "https"; +import { readFile } from "fs/promises"; +import { Duplex } from "stream"; +import { parseDomain, ParseResultType } from "parse-domain"; +import { Util } from "./Util.js"; +import CSLoginPacket from "./packets/CSLoginPacket.js"; +import SCIdentifyPacket from "./packets/SCIdentifyPacket.js"; +import { Motd } from "./Motd.js"; +import { Player } from "./Player.js"; +import { Enums } from "./Enums.js"; +import { NETWORK_VERSION, PROXY_BRANDING, PROXY_VERSION, VANILLA_PROTOCOL_VERSION } from "../meta.js"; +import { CSUsernamePacket } from "./packets/CSUsernamePacket.js"; +import { SCSyncUuidPacket } from "./packets/SCSyncUuidPacket.js"; +import { SCReadyPacket } from "./packets/SCReadyPacket.js"; +import { Chalk } from "chalk"; +import EventEmitter from "events"; +import { MineProtocol } from "./Protocol.js"; +import { EaglerSkins } from "./skins/EaglerSkins.js"; +import { CSSetSkinPacket } from "./packets/CSSetSkinPacket.js"; +import { CSChannelMessagePacket } from "./packets/channel/CSChannelMessage.js"; +import { Constants, UPGRADE_REQUIRED_RESPONSE } from "./Constants.js"; +import { PluginManager } from "./pluginLoader/PluginManager.js"; +import ProxyRatelimitManager from "./ratelimit/ProxyRatelimitManager.js"; +import { SkinServer } from "./skins/SkinServer.js"; + +let instanceCount = 0; +const chalk = new Chalk({ level: 2 }); +const motdMatcher = /^accept: motd/i; + +export class Proxy extends EventEmitter { + public packetRegistry: Map< + number, + Packet & { + class: any; + } + >; + public players = new Map(); + public pluginManager: PluginManager; + public config: Config["adapter"]; + public wsServer: WebSocketServer; + public httpServer: http.Server; + public skinServer: SkinServer; + public broadcastMotd?: Motd.MOTD; + public ratelimit: ProxyRatelimitManager; + + private _logger: Logger; + private initalHandlerLogger: Logger; + + private loaded: boolean; + + constructor(config: Config["adapter"], pluginManager: PluginManager) { + super(); + this._logger = new Logger(`EaglerProxy-${instanceCount}`); + this.initalHandlerLogger = new Logger(`EaglerProxy-InitialHandler`); + // hijack the initial handler logger to append [InitialHandler] to the beginning + (this.initalHandlerLogger as any)._info = this.initalHandlerLogger.info; + this.initalHandlerLogger.info = (msg: string) => { + (this.initalHandlerLogger as any)._info(`${chalk.blue("[InitialHandler]")} ${msg}`); + }; + (this.initalHandlerLogger as any)._warn = this.initalHandlerLogger.warn; + this.initalHandlerLogger.warn = (msg: string) => { + (this.initalHandlerLogger as any)._warn(`${chalk.blue("[InitialHandler]")} ${msg}`); + }; + (this.initalHandlerLogger as any)._error = this.initalHandlerLogger.error; + this.initalHandlerLogger.error = (msg: string) => { + (this.initalHandlerLogger as any)._error(`${chalk.blue("[InitialHandler]")} ${msg}`); + }; + (this.initalHandlerLogger as any)._fatal = this.initalHandlerLogger.fatal; + this.initalHandlerLogger.fatal = (msg: string) => { + (this.initalHandlerLogger as any)._fatal(`${chalk.blue("[InitialHandler]")} ${msg}`); + }; + (this.initalHandlerLogger as any)._debug = this.initalHandlerLogger.debug; + this.initalHandlerLogger.debug = (msg: string) => { + (this.initalHandlerLogger as any)._debug(`${chalk.blue("[InitialHandler]")} ${msg}`); + }; + this.config = config; + this.pluginManager = pluginManager; + instanceCount++; + + process.on("uncaughtException", (err) => { + this._logger.warn(`An uncaught exception was caught! Error: ${err.stack}`); + }); + + process.on("unhandledRejection", (err) => { + this._logger.warn(`An unhandled rejection was caught! Rejection: ${(err as Error).stack || err}`); + }); + } + + public async init() { + this._logger.info(`Starting ${PROXY_BRANDING} v${PROXY_VERSION}...`); + global.PROXY = this; + if (this.loaded) throw new Error("Can't initiate if proxy instance is already initialized or is being initialized!"); + this.loaded = true; + this.packetRegistry = await loadPackets(); + this.skinServer = new SkinServer( + this, + this.config.useNatives, + this.config.skinServer.cache.skinCachePruneInterval, + this.config.skinServer.cache.skinCacheLifetime, + this.config.skinServer.cache.folderName, + this.config.skinServer.cache.useCache, + this.config.skinServer.skinUrlWhitelist + ); + global.PACKET_REGISTRY = this.packetRegistry; + if (this.config.motd == "FORWARD") { + this._pollServer(this.config.server.host, this.config.server.port); + } else { + const broadcastMOTD = await Motd.MOTD.generateMOTDFromConfig(this.config, this.config.useNatives); + (broadcastMOTD as any)._static = true; + this.broadcastMotd = broadcastMOTD; + // playercount will be dynamically updated + } + if (this.config.tls && this.config.tls.enabled) { + this.httpServer = https + .createServer( + { + key: await readFile(this.config.tls.key), + cert: await readFile(this.config.tls.cert), + }, + (req, res) => this._handleNonWSRequest(req, res, this.config) + ) + .listen(this.config.bindPort || 8080, this.config.bindHost || "127.0.0.1"); + this.wsServer = new WebSocketServer({ + noServer: true, + }); + } else { + this.httpServer = http.createServer((req, res) => this._handleNonWSRequest(req, res, this.config)).listen(this.config.bindPort || 8080, this.config.bindHost || "127.0.0.1"); + this.wsServer = new WebSocketServer({ + noServer: true, + }); + } + this.wsServer.on("error", (err) => { + this._logger.warn(`WebSocket server threw an error: ${err.stack}`); + }); + this.httpServer.on("upgrade", async (r, s, h) => { + try { + await this._handleWSConnectionReq(r, s, h); + } catch (err) { + this._logger.error(`Error was caught whilst trying to handle WebSocket upgrade! Error: ${err.stack ?? err}`); + } + }); + await new Promise((res, rej) => { + this.httpServer.once("listening", res); + this.httpServer.once("error", (err) => { + this._logger.error(`Error was caught whilst trying to bind HTTP server! Error: ${err.stack ?? err}`); + rej(err); + }); + }); + this.httpServer.on("error", (err) => { + this._logger.warn(`HTTP server threw an error: ${err.stack}`); + }); + process.on("beforeExit", () => { + this._logger.info("Cleaning up before exiting..."); + this.players.forEach((plr) => plr.disconnect(Enums.ChatColor.YELLOW + "Proxy is shutting down.")); + }); + this.ratelimit = new ProxyRatelimitManager(this.config.ratelimits); + this.pluginManager.emit("proxyFinishLoading", this, this.pluginManager); + this._logger.info(`Started WebSocket server and binded to ${this.config.bindHost} on port ${this.config.bindPort}.`); + } + + private _handleNonWSRequest(req: http.IncomingMessage, res: http.ServerResponse, config: Config["adapter"]) { + const inc = this.ratelimit.http.consume(req.socket.remoteAddress); + if (inc.success) { + const ctx: Util.Handlable = { handled: false }; + this.emit("httpConnection", req, res, ctx); + if (!ctx.handled) res.setHeader("Content-Type", "text/html").writeHead(426).end(UPGRADE_REQUIRED_RESPONSE); + } + } + + readonly LOGIN_TIMEOUT = 30000; + + private async _handleWSConnection(ws: WebSocket, req: http.IncomingMessage) { + const rl = this.ratelimit.ws.consume(req.socket.remoteAddress); + if (!rl.success) { + return ws.close(); + } + + const ctx: Util.Handlable = { handled: false }; + await this.emit("wsConnection", ws, req, ctx); + if (ctx.handled) return; + + const firstPacket = await Util.awaitPacket(ws); + let player: Player, handled: boolean; + setTimeout(() => { + if (!handled) { + this.initalHandlerLogger.warn( + `Disconnecting client ${ + player ? player.username ?? `[/${(ws as any)._socket.remoteAddress}:${(ws as any)._socket.remotePort}` : `[/${(ws as any)._socket.remoteAddress}:${(ws as any)._socket.remotePort}` + } due to connection timing out.` + ); + if (player) player.disconnect(`${Enums.ChatColor.YELLOW} Your connection timed out whilst processing handshake, please try again.`); + else ws.close(); + } + }, this.LOGIN_TIMEOUT); + try { + if (motdMatcher.test(firstPacket.toString())) { + if (!this.ratelimit.motd.consume(req.socket.remoteAddress).success) { + return ws.close(); + } + if (this.broadcastMotd) { + const eventDetail = { motd: null }; + this.emit("fetchMotd", ws, req, eventDetail); + eventDetail.motd = await eventDetail.motd; + if (eventDetail.motd != null) { + const bufferized = eventDetail.motd.toBuffer(); + ws.send(bufferized[0]); + if (bufferized[1] != null) ws.send(bufferized[1]); + } else { + if (this.config.motd == "REALTIME") { + const motd = await Motd.MOTD.generateMOTDFromPing(this.config.server.host, this.config.server.port, this.config.useNatives).catch((err) => { + this._logger.warn(`Error polling ${this.config.server.host}:${this.config.server.port} for MOTD: ${err.stack ?? err}`); + }); + if (motd) { + const bufferized = this.broadcastMotd.toBuffer(); + ws.send(bufferized[0]); + if (bufferized[1] != null) ws.send(bufferized[1]); + } + } else if ((this.broadcastMotd as any)._static) { + this.broadcastMotd.jsonMotd.data.online = this.players.size; + // sample for players + this.broadcastMotd.jsonMotd.data.players = []; + const playerSample = [...this.players.keys()].filter((sample) => !sample.startsWith("!phs_")).slice(0, 5); + this.broadcastMotd.jsonMotd.data.players = playerSample; + if (this.players.size - playerSample.length > 0) this.broadcastMotd.jsonMotd.data.players.push(`${Enums.ChatColor.GRAY}${Enums.ChatColor.ITALIC}(and ${this.players.size - playerSample.length} more)`); + + const bufferized = this.broadcastMotd.toBuffer(); + ws.send(bufferized[0]); + if (bufferized[1] != null) ws.send(bufferized[1]); + } else { + const motd = this.broadcastMotd.toBuffer(); + ws.send(motd[0]); + if (motd[1] != null) ws.send(motd[1]); + } + } + } + handled = true; + ws.close(); + } else { + (ws as any).httpRequest = req; + player = new Player(ws as any); + const rl = this.ratelimit.connect.consume(req.socket.remoteAddress); + if (!rl.success) { + handled = true; + player.disconnect(`${Enums.ChatColor.RED}You have been ratelimited!\nTry again in ${Enums.ChatColor.WHITE}${rl.retryIn / 1000}${Enums.ChatColor.RED} seconds`); + return; + } + + const loginPacket = new CSLoginPacket().deserialize(firstPacket); + player.state = Enums.ClientState.PRE_HANDSHAKE; + if (loginPacket.gameVersion != VANILLA_PROTOCOL_VERSION) { + player.disconnect(`${Enums.ChatColor.RED}Please connect to this proxy on EaglercraftX 1.8.9.`); + return; + } else if (loginPacket.networkVersion != NETWORK_VERSION) { + player.disconnect(`${Enums.ChatColor.RED}Your EaglercraftX version is too ${loginPacket.networkVersion > NETWORK_VERSION ? "new" : "old"}! Please ${loginPacket.networkVersion > NETWORK_VERSION ? "downgrade" : "update"}.`); + return; + } + try { + Util.validateUsername(loginPacket.username); + } catch (err) { + player.disconnect(`${Enums.ChatColor.RED}${err.reason || err}`); + return; + } + player.username = loginPacket.username; + player.uuid = Util.generateUUIDFromPlayer(player.username); + if (this.players.size > this.config.maxConcurrentClients) { + player.disconnect(`${Enums.ChatColor.YELLOW}Proxy is full! Please try again later.`); + return; + } else if (this.players.get(player.username) != null || this.players.get(`!phs.${player.uuid}`) != null) { + player.disconnect(`${Enums.ChatColor.YELLOW}Someone under your username (${player.username}) is already connected to the proxy!`); + return; + } + this.players.set(`!phs.${player.uuid}`, player); + this._logger.info( + `Player ${loginPacket.username} (${Util.generateUUIDFromPlayer(loginPacket.username)}) running ${loginPacket.brand}/${loginPacket.version} (net ver: ${loginPacket.networkVersion}, game ver: ${ + loginPacket.gameVersion + }) is attempting to connect!` + ); + player.write(new SCIdentifyPacket()); + const usernamePacket: CSUsernamePacket = (await player.read(Enums.PacketId.CSUsernamePacket)) as any; + if (usernamePacket.username !== player.username) { + player.disconnect(`${Enums.ChatColor.YELLOW}Failed to complete handshake. Your game version may be too old or too new.`); + return; + } + const syncUuid = new SCSyncUuidPacket(); + syncUuid.username = player.username; + syncUuid.uuid = player.uuid; + player.write(syncUuid); + + const prom = await Promise.all([player.read(Enums.PacketId.CSReadyPacket), (await player.read(Enums.PacketId.CSSetSkinPacket)) as CSSetSkinPacket]), + skin = prom[1], + obj = new EaglerSkins.EaglerSkin(); + obj.owner = player; + obj.type = skin.skinType as any; + if (skin.skinType == Enums.SkinType.CUSTOM) obj.skin = skin.skin; + else obj.builtInSkin = skin.skinId; + player.skin = obj; + + player.write(new SCReadyPacket()); + this.players.delete(`!phs.${player.uuid}`); + this.players.set(player.username, player); + player.initListeners(); + this._bindListenersToPlayer(player); + player.state = Enums.ClientState.POST_HANDSHAKE; + this._logger.info(`Handshake Success! Connecting player ${player.username} to server...`); + handled = true; + + await player.connect({ + host: this.config.server.host, + port: this.config.server.port, + username: player.username, + }); + this._logger.info(`Player ${player.username} successfully connected to server.`); + this.emit("playerConnect", player); + } + } catch (err) { + this.initalHandlerLogger.warn(`Error occurred whilst handling handshake: ${err.stack ?? err}`); + handled = true; + ws.close(); + if (player && player.uuid && this.players.has(`!phs.${player.uuid}`)) this.players.delete(`!phs.${player.uuid}`); + if (player && player.uuid && this.players.has(player.username)) this.players.delete(player.username); + } + } + + private _bindListenersToPlayer(player: Player) { + let sentDisconnectMsg = false; + player.on("disconnect", () => { + if (this.players.has(player.username)) this.players.delete(player.username); + this.initalHandlerLogger.info(`DISCONNECT ${player.username} <=> DISCONNECTED`); + if (!sentDisconnectMsg) this._logger.info(`Player ${player.username} (${player.uuid}) disconnected from the proxy server.`); + }); + player.on("proxyPacket", async (packet) => { + if (packet.packetId == Enums.PacketId.CSChannelMessagePacket) { + try { + const msg: CSChannelMessagePacket = packet as any; + if (msg.channel == Constants.EAGLERCRAFT_SKIN_CHANNEL_NAME) { + await this.skinServer.handleRequest(msg, player, this); + } + } catch (err) { + this._logger.error(`Failed to process channel message packet! Error: ${err.stack || err}`); + } + } + }); + player.on("switchServer", (client) => { + this.initalHandlerLogger.info(`SWITCH_SERVER ${player.username} <=> ${client.socket.remoteAddress}:${client.socket.remotePort}`); + }); + player.on("joinServer", (client) => { + this.initalHandlerLogger.info(`SERVER_CONNECTED ${player.username} <=> ${client.socket.remoteAddress}:${client.socket.remotePort}`); + }); + } + + static readonly POLL_INTERVAL: number = 10000; + + private _pollServer(host: string, port: number, interval?: number) { + (async () => { + while (true) { + const motd = await Motd.MOTD.generateMOTDFromPing(host, port, this.config.useNatives).catch((err) => { + this._logger.warn(`Error polling ${host}:${port} for MOTD: ${err.stack ?? err}`); + }); + if (motd) this.broadcastMotd = motd; + await new Promise((res) => setTimeout(res, interval ?? Proxy.POLL_INTERVAL)); + } + })(); + } + + private async _handleWSConnectionReq(req: http.IncomingMessage, socket: Duplex, head: Buffer) { + const origin = req.headers.origin == null || req.headers.origin == "null" ? null : req.headers.origin; + if (!this.config.origins.allowOfflineDownloads && origin == null) { + socket.destroy(); + return; + } + if (this.config.origins.originBlacklist != null && this.config.origins.originBlacklist.some((host) => Util.areDomainsEqual(host, origin))) { + socket.destroy(); + return; + } + if (this.config.origins.originWhitelist != null && !this.config.origins.originWhitelist.some((host) => Util.areDomainsEqual(host, origin))) { + socket.destroy(); + return; + } + try { + await this.wsServer.handleUpgrade(req, socket, head, (ws) => this._handleWSConnection(ws, req)); + } catch (err) { + this._logger.error(`Error was caught whilst trying to handle WebSocket connection request! Error: ${err.stack ?? err}`); + socket.destroy(); + } + } + + public fetchUserByUUID(uuid: MineProtocol.UUID): Player | null { + for (const [username, player] of this.players) { + if (player.uuid == uuid) return player; + } + return null; + } +} + +interface ProxyEvents { + playerConnect: (player: Player) => void; + playerDisconnect: (player: Player) => void; + fetchMotd: (ws: WebSocket, erq: http.IncomingMessage, result: { motd: Promise }) => void; + + httpConnection: (req: http.IncomingMessage, res: http.ServerResponse, ctx: Util.Handlable) => void; + wsConnection: (ws: WebSocket, req: http.IncomingMessage, ctx: Util.Handlable) => void; +} + +export declare interface Proxy { + on(event: U, listener: ProxyEvents[U]): this; + emit(event: U, ...args: Parameters): boolean; +} diff --git a/eaglerproxy/files/src/proxy/Util.ts b/eaglerproxy/files/src/proxy/Util.ts new file mode 100644 index 0000000..5e487b1 --- /dev/null +++ b/eaglerproxy/files/src/proxy/Util.ts @@ -0,0 +1,196 @@ +import { createHash } from "crypto"; +import { encodeULEB128, decodeULEB128 } from "@thi.ng/leb128"; +import { Chat } from "./Chat.js"; +import { WebSocket } from "ws"; +import { Enums } from "./Enums.js"; +import { Player } from "./Player.js"; +import * as http from "http"; +import { Config } from "../launcher_types.js"; +import { parseDomain, ParseResultType } from "parse-domain"; +import { access, readdir } from "fs/promises"; +import { resolve } from "path"; + +export namespace Util { + export const encodeVarInt: typeof encodeULEB128 = encodeULEB128; + export const decodeVarInt: typeof decodeULEB128 = decodeULEB128; + + // annotation for range + // b = beginning, e = end + export type Range = number; + + export type BoundedBuffer = Buffer; + + const USERNAME_REGEX = /[^0-9^a-z^A-Z^_]/gi; + + export function generateUUIDFromPlayer(user: string): string { + const str = `OfflinePlayer:${user}`; + let md5Bytes = createHash("md5").update(str).digest(); + md5Bytes[6] &= 0x0f; /* clear version */ + md5Bytes[6] |= 0x30; /* set to version 3 */ + md5Bytes[8] &= 0x3f; /* clear variant */ + md5Bytes[8] |= 0x80; /* set to IETF variant */ + return uuidBufferToString(md5Bytes); + } + + // excerpt from uuid-buffer + + export function uuidStringToBuffer(uuid: string): Buffer { + if (!uuid) return Buffer.alloc(16); // Return empty buffer + const hexStr = uuid.replace(/-/g, ""); + if (uuid.length != 36 || hexStr.length != 32) throw new Error(`Invalid UUID string: ${uuid}`); + return Buffer.from(hexStr, "hex"); + } + + export function uuidBufferToString(buffer: Buffer): string { + if (buffer.length != 16) throw new Error(`Invalid buffer length for uuid: ${buffer.length}`); + if (buffer.equals(Buffer.alloc(16))) return null; // If buffer is all zeros, return null + const str = buffer.toString("hex"); + return `${str.slice(0, 8)}-${str.slice(8, 12)}-${str.slice(12, 16)}-${str.slice(16, 20)}-${str.slice(20)}`; + } + + export function awaitPacket(ws: WebSocket, filter?: (msg: Buffer) => boolean): Promise { + return new Promise((res, rej) => { + let resolved = false; + const msgCb = (msg: any) => { + if (filter != null && filter(msg)) { + resolved = true; + ws.removeListener("message", msgCb); + ws.removeListener("close", discon); + ws.setMaxListeners(ws.getMaxListeners() - 2 < 0 ? 5 : ws.getMaxListeners() - 2); + res(msg); + } else if (filter == null) { + resolved = true; + ws.removeListener("message", msgCb); + ws.removeListener("close", discon); + ws.setMaxListeners(ws.getMaxListeners() - 2 < 0 ? 5 : ws.getMaxListeners() - 2); + res(msg); + } + }; + const discon = () => { + resolved = true; + ws.removeListener("message", msgCb); + ws.removeListener("close", discon); + ws.setMaxListeners(ws.getMaxListeners() - 2 < 0 ? 5 : ws.getMaxListeners() - 2); + rej("Connection closed"); + }; + ws.setMaxListeners(ws.getMaxListeners() + 2); + ws.on("message", msgCb); + ws.on("close", discon); + setTimeout(() => { + ws.removeListener("message", msgCb); + ws.removeListener("close", discon); + ws.setMaxListeners(ws.getMaxListeners() - 2 < 0 ? 5 : ws.getMaxListeners() - 2); + rej("Timed out"); + }, 10000); + }); + } + + export function validateUsername(user: string): void | never { + if (user.length > 20) throw new Error("Username is too long!"); + if (user.length < 3) throw new Error("Username is too short!"); + if (!!user.match(USERNAME_REGEX)) throw new Error("Invalid username. Username can only contain alphanumeric characters, and the underscore (_) character."); + } + + export function areDomainsEqual(d1: string, d2: string): boolean { + if (d1.endsWith("*.")) d1 = d1.replace("*.", "WILDCARD-LOL-EXTRA-LONG-SUBDOMAIN-TO-LOWER-CHANCES-OF-COLLISION."); + const parseResult1 = parseDomain(d1), + parseResult2 = parseDomain(d2); + if (parseResult1.type != ParseResultType.Invalid && parseResult2.type != ParseResultType.Invalid) { + if (parseResult1.type == ParseResultType.Ip && parseResult2.type == ParseResultType.Ip) { + return parseResult1.hostname == parseResult2.hostname ? true : false; + } else if (parseResult1.type == ParseResultType.Listed && parseResult2.type == ParseResultType.Listed) { + if (parseResult1.subDomains[0] == "WILDCARD-LOL-EXTRA-LONG-SUBDOMAIN-TO-LOWER-CHANCES-OF-COLLISION") { + // wildcard + const domainPlusTld1 = parseResult1.domain + ("." + parseResult1.topLevelDomains.join(".")); + const domainPlusTld2 = parseResult2.domain + ("." + parseResult2.topLevelDomains.join(".")); + return domainPlusTld1 == domainPlusTld2 ? true : false; + } else { + // no wildcard + return d1 == d2 ? true : false; + } + } else if (parseResult1.type == ParseResultType.NotListed && parseResult2.type == ParseResultType.NotListed) { + if (parseResult1.labels[0] == "WILDCARD-LOL-EXTRA-LONG-SUBDOMAIN-TO-LOWER-CHANCES-OF-COLLISION") { + // wildcard + const domainPlusTld1 = parseResult1.labels.slice(2).join("."); + const domainPlusTld2 = parseResult1.labels.slice(2).join("."); + return domainPlusTld1 == domainPlusTld2 ? true : false; + } else { + // no wildcard + return d1 == d2 ? true : false; + } + } else if (parseResult1.type == ParseResultType.Reserved && parseResult2.type == ParseResultType.Reserved) { + if (parseResult1.hostname == "" && parseResult1.hostname === parseResult2.hostname) return true; + else { + // uncertain, fallback to exact hostname matching + return d1 == d2 ? true : false; + } + } + } else { + return false; + } + } + + async function* _getFiles(dir: string) { + const dirents = await readdir(dir, { withFileTypes: true }); + for (const dirent of dirents) { + const res = resolve(dir, dirent.name); + if (dirent.isDirectory()) { + yield* _getFiles(res); + } else { + yield res; + } + } + } + + export async function recursiveFileSearch(dir: string): Promise { + const ents = []; + for await (const f of _getFiles(dir)) { + ents.push(f); + } + return ents; + } + + export async function fsExists(path: string): Promise { + try { + await access(path); + } catch (err) { + if (err.code == "ENOENT") return false; + else return true; + } + return true; + } + + export type PlayerPosition = { + x: number; + y: number; + z: number; + yaw: number; + pitch: number; + }; + + export type PositionPacket = { + x: number; + y: number; + z: number; + yaw: number; + pitch: number; + flags: number; + }; + + export function generatePositionPacket(currentPos: PlayerPosition, newPos: PositionPacket): PositionPacket { + const DEFAULT_RELATIVITY = 0x01; // relative to X-axis + const newPosPacket = { + x: newPos.x - currentPos.x * 2, + y: newPos.y, + z: newPos.z, + yaw: newPos.yaw, + pitch: newPos.pitch, + flags: DEFAULT_RELATIVITY, + }; + return newPosPacket; + } + + export type Handlable = { + handled: boolean; + }; +} diff --git a/eaglerproxy/files/src/proxy/databases/DiskDB.ts b/eaglerproxy/files/src/proxy/databases/DiskDB.ts new file mode 100644 index 0000000..89430dc --- /dev/null +++ b/eaglerproxy/files/src/proxy/databases/DiskDB.ts @@ -0,0 +1,53 @@ +import path from "path"; +import fs from "fs/promises"; +import fss from "fs"; + +export default class DiskDB { + public folder: string; + static VALIDATION_REGEX = /^[0-9a-zA-Z_]+$/; + + nameGenerator: (k: string) => string; + encoder: (key: T) => Buffer; + decoder: (enc: Buffer) => T; + + constructor(folder: string, encoder: (key: T) => Buffer, decoder: (enc: Buffer) => T, nameGenerator: (k: string) => string) { + this.folder = path.isAbsolute(folder) ? folder : path.resolve(folder); + this.encoder = encoder; + this.decoder = decoder; + this.nameGenerator = nameGenerator; + if (!fss.existsSync(this.folder)) fss.mkdirSync(this.folder); + } + + public async filter(f: (v: T) => boolean) { + for (const file of await fs.readdir(this.folder)) { + const fp = path.join(this.folder, file); + if (!f(this.decoder(await fs.readFile(fp)))) await fs.rm(fp); + } + } + + public async get(k: string): Promise { + k = this.nameGenerator(k); + if (!DiskDB.VALIDATION_REGEX.test(k)) throw new InvalidKeyError("Invalid key, key can only consist of alphanumeric characters and _"); + const pth = path.join(this.folder, `${k}.data`); + try { + return this.decoder(await fs.readFile(pth)); + } catch (err) { + return null; + } + } + + public async set(k: string, v: T) { + k = this.nameGenerator(k); + if (!DiskDB.VALIDATION_REGEX.test(k)) throw new InvalidKeyError("Invalid key, key can only consist of alphanumeric characters and _"); + const pth = path.join(this.folder, `${k}.data`); + await fs.writeFile(pth, this.encoder(v)); + } +} + +class InvalidKeyError extends Error { + constructor(msg: string) { + super(`[InvalidKeyError] : ${msg}`); + this.name = "InvalidKeyError"; + Object.setPrototypeOf(this, InvalidKeyError); + } +} diff --git a/eaglerproxy/files/src/proxy/packets/CSLoginPacket.ts b/eaglerproxy/files/src/proxy/packets/CSLoginPacket.ts new file mode 100644 index 0000000..1f71f34 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/CSLoginPacket.ts @@ -0,0 +1,57 @@ +import { NETWORK_VERSION, VANILLA_PROTOCOL_VERSION } from "../../meta.js"; +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; +import { MineProtocol } from "../Protocol.js"; + +export default class CSLoginPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.CSLoginPacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.S; + sentAfterHandshake = false; + + networkVersion = NETWORK_VERSION; + gameVersion = VANILLA_PROTOCOL_VERSION; + brand: string; + version: string; + username: string; + + public serialize() { + return Buffer.concat( + [ + [Enums.PacketId.CSLoginPacket], + [0x02], + MineProtocol.writeShort(0x01), + MineProtocol.writeShort(this.networkVersion), + MineProtocol.writeShort(0x01), + MineProtocol.writeShort(this.gameVersion), + MineProtocol.writeString(this.brand), + MineProtocol.writeString(this.version), + [0x00], + MineProtocol.writeString(this.username), + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + public deserialize(packet: Buffer) { + if (packet[0] != this.packetId) + throw TypeError("Invalid packet ID detected!"); + packet = packet.subarray(2); + let fard = MineProtocol.readShort(packet); + // Math.min used in feeble attempt at anti DoS + let fv = Math.min(8, fard.value); + for (let i = 0; i < fv; i++) { + fard = MineProtocol.readShort(fard.newBuffer); + } + fard = MineProtocol.readShort(fard.newBuffer); + fv = Math.min(8, fard.value); + for (let i = 0; i < fv; i++) { + fard = MineProtocol.readShort(fard.newBuffer); + } + const brand = MineProtocol.readString(fard.newBuffer), + version = MineProtocol.readString(brand.newBuffer), + username = MineProtocol.readString(version.newBuffer, 1); + this.brand = brand.value; + this.version = version.value; + this.username = username.value; + return this; + } +} \ No newline at end of file diff --git a/eaglerproxy/files/src/proxy/packets/CSReadyPacket.ts b/eaglerproxy/files/src/proxy/packets/CSReadyPacket.ts new file mode 100644 index 0000000..a33ee74 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/CSReadyPacket.ts @@ -0,0 +1,17 @@ +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; + +export class CSReadyPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.CSReadyPacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.S; + sentAfterHandshake = false; + + public serialize() { + return Buffer.from([this.packetId]); + } + + public deserialize(packet: Buffer) { + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/CSSetSkinPacket.ts b/eaglerproxy/files/src/proxy/packets/CSSetSkinPacket.ts new file mode 100644 index 0000000..8670cf8 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/CSSetSkinPacket.ts @@ -0,0 +1,70 @@ +import { Constants } from "../Constants.js"; +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; +import { MineProtocol } from "../Protocol.js"; + +export class CSSetSkinPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.CSSetSkinPacket; + type: "packet" = "packet"; + boundTo: Enums.PacketBounds = Enums.PacketBounds.S; + sentAfterHandshake: boolean = false; + + version: string | "skin_v1" = "skin_v1"; + skinType: Omit; + skinDimensions?: number; + skin?: Buffer; + skinId?: number; + + public serialize() { + if (this.skinType == Enums.SkinType.BUILTIN) { + return Buffer.concat([ + Buffer.from([this.packetId]), + MineProtocol.writeString(this.version), + MineProtocol.writeVarInt(this.skinDimensions), + this.skin, + ]); + } else { + return Buffer.concat( + [ + [this.packetId], + MineProtocol.writeString(this.version), + Constants.MAGIC_ENDING_CLIENT_UPLOAD_SKIN_BUILTIN, + [this.skinId], + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + } + + public deserialize(packet: Buffer) { + packet = packet.subarray(1); + const version = MineProtocol.readString(packet); + let skinType: Enums.SkinType; + if ( + !Constants.MAGIC_ENDING_CLIENT_UPLOAD_SKIN_BUILTIN.some( + (byte, index) => byte !== version.newBuffer[index] + ) + ) { + // built in + skinType = Enums.SkinType.BUILTIN; + const id = MineProtocol.readVarInt( + version.newBuffer.subarray( + Constants.MAGIC_ENDING_CLIENT_UPLOAD_SKIN_BUILTIN.length + ) + ); + this.version = version.value; + this.skinType = skinType; + this.skinId = id.value; + return this; + } else { + // custom + skinType = Enums.SkinType.CUSTOM; + const dimensions = MineProtocol.readVarInt(version.newBuffer), + skin = dimensions.newBuffer.subarray(3).subarray(0, 16384); + this.version = version.value; + this.skinType = skinType; + this.skinDimensions = dimensions.value; + this.skin = skin; + return this; + } + } +} diff --git a/eaglerproxy/files/src/proxy/packets/CSUsernamePacket.ts b/eaglerproxy/files/src/proxy/packets/CSUsernamePacket.ts new file mode 100644 index 0000000..9458be5 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/CSUsernamePacket.ts @@ -0,0 +1,31 @@ +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; +import { MineProtocol } from "../Protocol.js"; + +export class CSUsernamePacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.CSUsernamePacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.S; + sentAfterHandshake = false; + + username: string; + static readonly DEFAULT = "default"; + + public serialize() { + return Buffer.concat( + [ + [this.packetId], + MineProtocol.writeString(this.username), + MineProtocol.writeString(CSUsernamePacket.DEFAULT), + [0x0], + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + + public deserialize(packet: Buffer) { + packet = packet.subarray(1); + const username = MineProtocol.readString(packet); + this.username = username.value; + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/SCDisconnectPacket.ts b/eaglerproxy/files/src/proxy/packets/SCDisconnectPacket.ts new file mode 100644 index 0000000..7f5f1d6 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/SCDisconnectPacket.ts @@ -0,0 +1,37 @@ +import { Chat } from "../Chat.js"; +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; +import { MineProtocol } from "../Protocol.js"; + +export default class SCDisconnectPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.SCDisconnectPacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.C; + sentAfterHandshake = false; + static readonly REASON = 0x8; + + reason: string | Chat.Chat; + + public serialize() { + const msg = + typeof this.reason == "string" + ? this.reason + : Chat.chatToPlainString(this.reason); + return Buffer.concat( + [ + [0xff], + MineProtocol.writeVarInt(SCDisconnectPacket.REASON), + MineProtocol.writeString(" " + msg + " "), + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + public deserialize(packet: Buffer) { + if (packet[0] != this.packetId) throw new Error("Invalid packet ID!"); + packet = packet.subarray( + 1 + MineProtocol.writeVarInt(SCDisconnectPacket.REASON).length + ); + const reason = MineProtocol.readString(packet); + this.reason = reason.value; + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/SCIdentifyPacket.ts b/eaglerproxy/files/src/proxy/packets/SCIdentifyPacket.ts new file mode 100644 index 0000000..af68019 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/SCIdentifyPacket.ts @@ -0,0 +1,48 @@ +import { + NETWORK_VERSION, + PROXY_BRANDING, + PROXY_VERSION, + VANILLA_PROTOCOL_VERSION, +} from "../../meta.js"; +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; +import { MineProtocol } from "../Protocol.js"; + +export default class SCIdentifyPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.SCIdentifyPacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.C; + sentAfterHandshake = false; + + protocolVer = NETWORK_VERSION; + gameVersion = VANILLA_PROTOCOL_VERSION; + branding = PROXY_BRANDING; + version = PROXY_VERSION; + + public serialize() { + return Buffer.concat( + [ + [0x02], + MineProtocol.writeShort(this.protocolVer), + MineProtocol.writeShort(this.gameVersion), + MineProtocol.writeString(this.branding), + MineProtocol.writeString(this.version), + [0x00, 0x00, 0x00], + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + + public deserialize(packet: Buffer) { + if (packet[0] != this.packetId) + throw TypeError("Invalid packet ID detected!"); + packet = packet.subarray(1); + const protoVer = MineProtocol.readShort(packet), + gameVer = MineProtocol.readShort(protoVer.newBuffer), + branding = MineProtocol.readString(gameVer.newBuffer), + version = MineProtocol.readString(branding.newBuffer); + this.gameVersion = gameVer.value; + this.branding = branding.value; + this.version = version.value; + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/SCReadyPacket.ts b/eaglerproxy/files/src/proxy/packets/SCReadyPacket.ts new file mode 100644 index 0000000..970b94b --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/SCReadyPacket.ts @@ -0,0 +1,17 @@ +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; + +export class SCReadyPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.SCReadyPacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.C; + sentAfterHandshake = false; + + public serialize() { + return Buffer.from([this.packetId]); + } + + public deserialize(packet: Buffer) { + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/SCSyncUuidPacket.ts b/eaglerproxy/files/src/proxy/packets/SCSyncUuidPacket.ts new file mode 100644 index 0000000..34d34c4 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/SCSyncUuidPacket.ts @@ -0,0 +1,33 @@ +import { Enums } from "../Enums.js"; +import Packet from "../Packet.js"; +import { MineProtocol } from "../Protocol.js"; +import { Util } from "../Util.js"; + +export class SCSyncUuidPacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.SCSyncUuidPacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.C; + sentAfterHandshake = false; + + username: string; + uuid: string; + + public serialize() { + return Buffer.concat( + [ + [this.packetId], + MineProtocol.writeString(this.username), + Util.uuidStringToBuffer(this.uuid), + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + + public deserialize(packet: Buffer) { + packet = packet.subarray(1); + const username = MineProtocol.readString(packet), + uuid = username.newBuffer.subarray(0, 15); + this.username = username.value; + this.uuid = Util.uuidBufferToString(uuid); + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/channel/CSChannelMessage.ts b/eaglerproxy/files/src/proxy/packets/channel/CSChannelMessage.ts new file mode 100644 index 0000000..e553669 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/channel/CSChannelMessage.ts @@ -0,0 +1,32 @@ +import { Enums } from "../../Enums.js"; +import Packet from "../../Packet.js"; +import { MineProtocol } from "../../Protocol.js"; + +export class CSChannelMessagePacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.CSChannelMessagePacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.S; + sentAfterHandshake = true; + + readonly messageType: Enums.ChannelMessageType = + Enums.ChannelMessageType.CLIENT; + channel: string; + data: Buffer; + + public serialize() { + return Buffer.concat( + [[this.packetId], MineProtocol.writeString(this.channel), this.data].map( + (arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr)) + ) + ); + } + + public deserialize(packet: Buffer) { + packet = packet.subarray(1); + const channel = MineProtocol.readString(packet), + data = channel.newBuffer; + this.channel = channel.value; + this.data = data; + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/packets/channel/SCChannelMessage.ts b/eaglerproxy/files/src/proxy/packets/channel/SCChannelMessage.ts new file mode 100644 index 0000000..58e3475 --- /dev/null +++ b/eaglerproxy/files/src/proxy/packets/channel/SCChannelMessage.ts @@ -0,0 +1,32 @@ +import { Enums } from "../../Enums.js"; +import Packet from "../../Packet.js"; +import { MineProtocol } from "../../Protocol.js"; + +export class SCChannelMessagePacket implements Packet { + packetId: Enums.PacketId = Enums.PacketId.SCChannelMessagePacket; + type: "packet" = "packet"; + boundTo = Enums.PacketBounds.C; + sentAfterHandshake = true; + + readonly messageType: Enums.ChannelMessageType = + Enums.ChannelMessageType.SERVER; + channel: string; + data: Buffer; + + public serialize() { + return Buffer.concat( + [[this.packetId], MineProtocol.writeString(this.channel), this.data].map( + (arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr)) + ) + ); + } + + public deserialize(packet: Buffer) { + packet = packet.subarray(1); + const channel = MineProtocol.readString(packet), + data = channel.newBuffer; + this.channel = channel.value; + this.data = data; + return this; + } +} diff --git a/eaglerproxy/files/src/proxy/pluginLoader/PluginLoaderTypes.ts b/eaglerproxy/files/src/proxy/pluginLoader/PluginLoaderTypes.ts new file mode 100644 index 0000000..a289102 --- /dev/null +++ b/eaglerproxy/files/src/proxy/pluginLoader/PluginLoaderTypes.ts @@ -0,0 +1,68 @@ +export namespace PluginLoaderTypes { + /** + * ## SemVer + * Abstract typing to define a semantic version string. Refer to https://semver.org/ for more details. + */ + export type SemVer = string; + + /** + * ## SemVerReq + * Abstract typing to define a semantic version requirement. Refer to https://semver.org/ for more details. + */ + export type SemVerReq = string; + + /** + * ## PluginMetadata + * Data structure of the JSON plugin metadata stored in `metadata.json`. Below is an example plugin metadata object. + * @example + * { + * name: "ExamplePlugin", + * version: "1.0.0" + * } + * + * @property {string} name - The name of the plugin. Spaces are allowed, and this will be shown to the end user. + * @property {string} id - The internal ID of the plugin. Spaces are not allowed, and any ID conflicts will cause the proxy to not load. + * @property {PluginLoaderTypes.SemVer} version - The version of the plugin. Must follow SemVer guidelines. + * @property {string} entry_point - Reference to the entry point JS file of the plugin. Is relative to the file of the `metadata.json`. + * @property {PluginLoaderTypes.PluginRequirement[]} requirements - The plugin requirement(s) of the plugin. Proxy will not load if any requirement cannot be satisfied. + * @property {string[]} load_after - Defines what plugin(s) to be loaded first before this plugin is loaded. + */ + export type PluginMetadata = { + name: string; + id: string; + version: SemVer; + entry_point: string; + requirements: PluginRequirement[]; + incompatibilities: PluginRequirement[]; + load_after: string[]; + }; + + /** + * ## PluginMetadataPathed + * Internal typing. Provides a path to the plugin metadata file. + */ + export type PluginMetadataPathed = PluginMetadata & { path: string }; + + /** + * ## PluginLoadOrder + * Internal typing. Provides a loading order for plugin loading. + */ + export type PluginLoadOrder = string[]; + + /** + * ## PluginRequirement + * A plugin requirement used to define dependencies for a specific plugin. + * Semantic versions may be used for the attribute `version`, and you can + * use `eaglerproxy` to define a requirement for the proxy version. + * @example + * { + * id: "eaglerproxy" + * } + * @property {string} id - The ID of the plugin to be used as a requirement. + * @property {PluginLoaderTypes.SemVerReq} version - The SemVer requirement for the requirement. + */ + export type PluginRequirement = { + id: string; + version: SemVerReq | "any"; + }; +} diff --git a/eaglerproxy/files/src/proxy/pluginLoader/PluginManager.ts b/eaglerproxy/files/src/proxy/pluginLoader/PluginManager.ts new file mode 100644 index 0000000..28162e8 --- /dev/null +++ b/eaglerproxy/files/src/proxy/pluginLoader/PluginManager.ts @@ -0,0 +1,251 @@ +import { Stats } from "fs"; +import * as fs from "fs/promises"; +import * as pathUtil from "path"; +import * as semver from "semver"; +import { EventEmitter } from "events"; +import { pathToFileURL } from "url"; +import { Logger } from "../../logger.js"; +import { PROXY_VERSION } from "../../meta.js"; +import { Proxy } from "../Proxy.js"; +import { Util } from "../Util.js"; +import { PluginLoaderTypes } from "./PluginLoaderTypes.js"; +import { Enums } from "../Enums.js"; +import { Chat } from "../Chat.js"; +import { Constants } from "../Constants.js"; +import { Motd } from "../Motd.js"; +import { Player } from "../Player.js"; +import { MineProtocol } from "../Protocol.js"; +import { EaglerSkins } from "../skins/EaglerSkins.js"; +import { BungeeUtil } from "../BungeeUtil.js"; + +export class PluginManager extends EventEmitter { + public plugins: Map; + public proxy: Proxy; + + public Logger: typeof Logger = Logger; + public Enums: typeof Enums = Enums; + public Chat: typeof Chat = Chat; + public Constants: typeof Constants = Constants; + public Motd: typeof Motd = Motd; + public Player: typeof Player = Player; + public MineProtocol: typeof MineProtocol = MineProtocol; + public EaglerSkins: typeof EaglerSkins = EaglerSkins; + public Util: typeof Util = Util; + public BungeeUtil: typeof BungeeUtil = BungeeUtil; + + private _loadDir: string; + private _logger: Logger; + + constructor(loadDir: string) { + super(); + this.setMaxListeners(0); + this._loadDir = loadDir; + this.plugins = new Map(); + this.Logger = Logger; + this._logger = new this.Logger("PluginManager"); + } + + public async loadPlugins() { + this._logger.info("Loading plugin metadata files..."); + const pluginMeta = await this._findPlugins(this._loadDir); + await this._validatePluginList(pluginMeta); + + let pluginsString = ""; + for (const [id, plugin] of pluginMeta) { + pluginsString += `${id}@${plugin.version}`; + } + pluginsString = pluginsString.substring(0, pluginsString.length - 1); + this._logger.info(`Found ${pluginMeta.size} plugin(s): ${pluginsString}`); + if (pluginMeta.size !== 0) { + this._logger.info(`Loading ${pluginMeta.size} plugin(s)...`); + const successLoadCount = await this._loadPlugins(pluginMeta, this._getLoadOrder(pluginMeta)); + this._logger.info(`Successfully loaded ${successLoadCount} plugin(s).`); + } + this.emit("pluginsFinishLoading", this); + } + + private async _findPlugins(dir: string): Promise> { + const ret: Map = new Map(); + const lsRes = (await Promise.all((await fs.readdir(dir)).filter((ent) => !ent.endsWith(".disabled")).map(async (res) => [pathUtil.join(dir, res), await fs.stat(pathUtil.join(dir, res))]))) as [string, Stats][]; + for (const [path, details] of lsRes) { + if (details.isFile()) { + if (path.endsWith(".jar")) { + this._logger.warn(`Non-EaglerProxy plugin found! (${path})`); + this._logger.warn(`BungeeCord plugins are NOT supported! Only custom EaglerProxy plugins are allowed.`); + } else if (path.endsWith(".zip")) { + this._logger.warn(`.zip file found in plugin directory! (${path})`); + this._logger.warn(`A .zip file was found in the plugins directory! Perhaps you forgot to unzip it?`); + } else this._logger.debug(`Skipping file found in plugin folder: ${path}`); + } else { + const metadataPath = pathUtil.resolve(pathUtil.join(path, "metadata.json")); + let metadata: PluginLoaderTypes.PluginMetadata; + try { + const file = await fs.readFile(metadataPath); + metadata = JSON.parse(file.toString()); + // do some type checking + if (typeof metadata.name != "string") throw new TypeError(".name is either null or not of a string type!"); + if (typeof metadata.id != "string") throw new TypeError(".id is either null or not of a string type!"); + if (/ /gm.test(metadata.id)) throw new Error(`.id contains whitespace!`); + if (!semver.valid(metadata.version)) throw new Error(".version is either null, not a string, or is not a valid SemVer!"); + if (typeof metadata.entry_point != "string") throw new TypeError(".entry_point is either null or not a string!"); + if (!metadata.entry_point.endsWith(".js")) throw new Error(`.entry_point (${metadata.entry_point}) references a non-JavaScript file!`); + if (!(await Util.fsExists(pathUtil.resolve(path, metadata.entry_point)))) throw new Error(`.entry_point (${metadata.entry_point}) references a non-existent file!`); + if (metadata.requirements instanceof Array == false) throw new TypeError(".requirements is either null or not an array!"); + for (const requirement of metadata.requirements as PluginLoaderTypes.PluginMetadata["requirements"]) { + if (typeof requirement != "object" || requirement == null) throw new TypeError(`.requirements[${(metadata.requirements as any).indexOf(requirement)}] is either null or not an object!`); + if (typeof requirement.id != "string") throw new TypeError(`.requirements[${(metadata.requirements as any).indexOf(requirement)}].id is either null or not a string!`); + if (/ /gm.test(requirement.id)) throw new TypeError(`.requirements[${(metadata.requirements as any).indexOf(requirement)}].id contains whitespace!`); + if (semver.validRange(requirement.version) == null && requirement.version != "any") + throw new TypeError(`.requirements[${(metadata.requirements as any).indexOf(requirement)}].version is either null or not a valid SemVer!`); + } + if (metadata.load_after instanceof Array == false) throw new TypeError(".load_after is either null or not an array!"); + for (const loadReq of metadata.load_after as string[]) { + if (typeof loadReq != "string") throw new TypeError(`.load_after[${(metadata.load_after as any).indexOf(loadReq)}] is either null, or not a valid ID!`); + if (/ /gm.test(loadReq)) throw new TypeError(`.load_after[${(metadata.load_after as any).indexOf(loadReq)}] contains whitespace!`); + } + if (metadata.incompatibilities instanceof Array == false) throw new TypeError(".incompatibilities is either null or not an array!"); + for (const incompatibility of metadata.incompatibilities as PluginLoaderTypes.PluginMetadata["requirements"]) { + if (typeof incompatibility != "object" || incompatibility == null) throw new TypeError(`.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}] is either null or not an object!`); + if (typeof incompatibility.id != "string") throw new TypeError(`.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}].id is either null or not a string!`); + if (/ /gm.test(incompatibility.id)) throw new TypeError(`.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}].id contains whitespace!`); + if (semver.validRange(incompatibility.version) == null) throw new TypeError(`.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}].version is either null or not a valid SemVer!`); + } + if (ret.has(metadata.id)) throw new Error(`Duplicate plugin ID detected: ${metadata.id}. Are there duplicate plugins in the plugin folder?`); + ret.set(metadata.id, { + path: pathUtil.resolve(path), + ...metadata, + }); + } catch (err) { + this._logger.warn(`Failed to load plugin metadata file at ${metadataPath}: ${err.stack ?? err}`); + this._logger.warn("This plugin will skip loading due to an error."); + } + } + } + return ret; + } + + private async _validatePluginList(plugins: Map) { + for (const [id, plugin] of plugins) { + for (const req of plugin.requirements) { + if (!plugins.has(req.id) && req.id != "eaglerproxy" && !req.id.startsWith("module:")) { + this._logger.fatal(`Error whilst loading plugins: Plugin ${plugin.name}@${plugin.version} requires plugin ${req.id}@${req.version}, but it is not found!`); + this._logger.fatal("Loading has halted due to missing dependencies."); + process.exit(1); + } + if (req.id == "eaglerproxy") { + if (!semver.satisfies(PROXY_VERSION, req.version) && req.version != "any") { + this._logger.fatal( + `Error whilst loading plugins: Plugin ${plugin.name}@${plugin.version} requires a proxy version that satisfies the SemVer requirement ${req.version}, but the proxy version is ${PROXY_VERSION} and does not satisfy the SemVer requirement!` + ); + this._logger.fatal("Loading has halted due to dependency issues."); + process.exit(1); + } + } else if (req.id.startsWith("module:")) { + const moduleName = req.id.replace("module:", ""); + try { + await import(moduleName); + } catch (err) { + if (err.code == "ERR_MODULE_NOT_FOUND") { + this._logger.fatal(`Plugin ${plugin.name}@${plugin.version} requires NPM module ${moduleName}${req.version == "any" ? "" : `@${req.version}`} to be installed, but it is not found!`); + this._logger.fatal( + `Please install this missing package by running "npm install ${moduleName}${req.version == "any" ? "" : `@${req.version}`}". If you're using yarn, run "yarn add ${moduleName}${ + req.version == "any" ? "" : `@${req.version}` + }" instead.` + ); + this._logger.fatal("Loading has halted due to dependency issues."); + process.exit(1); + } + } + } else { + let dep = plugins.get(req.id); + if (!semver.satisfies(dep.version, req.version) && req.version != "any") { + this._logger.fatal( + `Error whilst loading plugins: Plugin ${plugin.name}@${plugin.version} requires a version of plugin ${dep.name} that satisfies the SemVer requirement ${req.version}, but the plugin ${dep.name}'s version is ${dep.version} and does not satisfy the SemVer requirement!` + ); + this._logger.fatal("Loading has halted due to dependency issues."); + process.exit(1); + } + } + } + plugin.incompatibilities.forEach((incomp) => { + const plugin_incomp = plugins.get(incomp.id); + if (plugin_incomp) { + if (semver.satisfies(plugin_incomp.version, incomp.version)) { + this._logger.fatal( + `Error whilst loading plugins: Plugin incompatibility found! Plugin ${plugin.name}@${plugin.version} is incompatible with ${plugin_incomp.name}@${plugin_incomp.version} as it satisfies the SemVer requirement of ${incomp.version}!` + ); + this._logger.fatal("Loading has halted due to plugin incompatibility issues."); + process.exit(1); + } + } else if (incomp.id == "eaglerproxy") { + if (semver.satisfies(PROXY_VERSION, incomp.version)) { + this._logger.fatal(`Error whilst loading plugins: Plugin ${plugin.name}@${plugin.version} is incompatible with proxy version ${PROXY_VERSION} as it satisfies the SemVer requirement of ${incomp.version}!`); + this._logger.fatal("Loading has halted due to plugin incompatibility issues."); + process.exit(1); + } + } + }); + } + } + + private _getLoadOrder(plugins: Map): PluginLoaderTypes.PluginLoadOrder { + let order = [], + lastPlugin: any; + plugins.forEach((v) => order.push(v.id)); + for (const [id, plugin] of plugins) { + const load = plugin.load_after.filter((dep) => plugins.has(dep)); + if (load.length < 0) { + order.push(plugin.id); + } else { + let mostLastIndexFittingDeps = -1; + for (const loadEnt of load) { + if (loadEnt != lastPlugin) { + if (order.indexOf(loadEnt) + 1 > mostLastIndexFittingDeps) { + mostLastIndexFittingDeps = order.indexOf(loadEnt) + 1; + } + } + } + if (mostLastIndexFittingDeps != -1) { + order.splice(order.indexOf(plugin.id), 1); + order.splice(mostLastIndexFittingDeps - 1, 0, plugin.id); + lastPlugin = plugin; + } + } + } + return order; + } + + private async _loadPlugins(plugins: Map, order: PluginLoaderTypes.PluginLoadOrder): Promise { + let successCount = 0; + for (const id of order) { + let pluginMeta = plugins.get(id); + try { + const imp = await import(process.platform == "win32" ? pathToFileURL(pathUtil.join(pluginMeta.path, pluginMeta.entry_point)).toString() : pathUtil.join(pluginMeta.path, pluginMeta.entry_point)); + this.plugins.set(pluginMeta.id, { + exports: imp, + metadata: pluginMeta, + }); + successCount++; + this.emit("pluginLoad", pluginMeta.id, imp); + } catch (err) { + this._logger.warn(`Failed to load plugin entry point for plugin (${pluginMeta.name}) at ${pluginMeta.path}: ${err.stack ?? err}`); + this._logger.warn("This plugin will skip loading due to an error."); + } + return successCount; + } + } +} + +interface PluginManagerEvents { + pluginLoad: (name: string, plugin: any) => void; + pluginsFinishLoading: (manager: PluginManager) => void; + proxyFinishLoading: (proxy: Proxy, manager: PluginManager) => void; +} + +export declare interface PluginManager { + on(event: U, listener: PluginManagerEvents[U]): this; + + emit(event: U, ...args: Parameters): boolean; + + once(event: U, listener: PluginManagerEvents[U]): this; +} diff --git a/eaglerproxy/files/src/proxy/ratelimit/BucketRatelimiter.ts b/eaglerproxy/files/src/proxy/ratelimit/BucketRatelimiter.ts new file mode 100644 index 0000000..6055d64 --- /dev/null +++ b/eaglerproxy/files/src/proxy/ratelimit/BucketRatelimiter.ts @@ -0,0 +1,129 @@ +import { Logger } from "../../logger.js"; + +export default class BucketRateLimiter { + public capacity: number; + public refillsPerMin: number; + public keyMap: Map; + public static readonly GC_TOLERANCE: number = 50; + private sweeper: NodeJS.Timer; + + constructor(capacity: number, refillsPerMin: number) { + this.capacity = capacity; + this.refillsPerMin = refillsPerMin; + this.keyMap = new Map(); + this.sweeper = setInterval(() => { + this.removeFull(); + }, 5000); + } + + public cleanUp() { + clearInterval(this.sweeper); + } + + public consume(key: string, consumeTokens: number = 1): RateLimitData { + if (this.keyMap.has(key)) { + const bucket = this.keyMap.get(key); + + const now = Date.now(); + if (now - bucket.lastRefillTime > 60000 && bucket.tokens < this.capacity) { + const refillTimes = Math.floor((now - bucket.lastRefillTime) / 60000); + bucket.tokens = Math.min(this.capacity, bucket.tokens + refillTimes * this.refillsPerMin); + bucket.lastRefillTime = now - (refillTimes % 60000); + } else if (now - bucket.lastRefillTime > 60000 && bucket.tokens >= this.capacity) bucket.lastRefillTime = now; + + if (bucket.tokens >= consumeTokens) { + bucket.tokens -= consumeTokens; + return { success: true }; + } else { + const difference = consumeTokens - bucket.tokens; + return { + success: false, + missingTokens: difference, + retryIn: Math.ceil(difference / this.refillsPerMin) * 60000 - ((now - bucket.lastRefillTime) % 60000), + retryAt: Date.now() + Math.ceil(difference / this.refillsPerMin) * 60000 - ((now - bucket.lastRefillTime) % 60000), + }; + } + } else { + const bucket: KeyData = { + tokens: this.capacity, + lastRefillTime: Date.now(), + }; + if (bucket.tokens >= consumeTokens) { + bucket.tokens -= consumeTokens; + this.keyMap.set(key, bucket); + return { success: true }; + } else { + const difference = consumeTokens - bucket.tokens; + const now = Date.now(); + return { + success: false, + missingTokens: difference, + retryIn: Math.ceil(difference / this.refillsPerMin) * 60000 - ((now - bucket.lastRefillTime) % 60000), + retryAt: Date.now() + Math.ceil(difference / this.refillsPerMin) * 60000 - ((now - bucket.lastRefillTime) % 60000), + }; + } + } + } + + public addToBucket(key: string, amount: number) { + if (this.keyMap.has(key)) { + this.keyMap.get(key).tokens += amount; + } else { + this.keyMap.set(key, { + tokens: this.capacity + amount, + lastRefillTime: Date.now(), + }); + } + } + + public setBucketSize(key: string, amount: number) { + if (this.keyMap.has(key)) { + this.keyMap.get(key).tokens = amount; + } else { + this.keyMap.set(key, { + tokens: amount, + lastRefillTime: Date.now(), + }); + } + } + + public subtractFromBucket(key: string, amount: number) { + if (this.keyMap.has(key)) { + const bucket = this.keyMap.get(key); + bucket.tokens -= amount; + } else { + this.keyMap.set(key, { + tokens: this.capacity - amount, + lastRefillTime: Date.now(), + }); + } + } + + public removeFull() { + let remove: string[] = []; + const now = Date.now(); + this.keyMap.forEach((v, k) => { + if (now - v.lastRefillTime > 60000 && v.tokens < this.capacity) { + const refillTimes = Math.floor((now - v.lastRefillTime) / 60000); + v.tokens = Math.min(this.capacity, v.tokens + refillTimes * this.refillsPerMin); + v.lastRefillTime = now - (refillTimes % 60000); + } else if (now - v.lastRefillTime > 60000 && v.tokens >= this.capacity) v.lastRefillTime = now; + if (v.tokens == this.capacity) { + remove.push(k); + } + }); + remove.forEach((v) => this.keyMap.delete(v)); + } +} + +type RateLimitData = { + success: boolean; + missingTokens?: number; + retryIn?: number; + retryAt?: number; +}; + +type KeyData = { + tokens: number; + lastRefillTime: number; +}; diff --git a/eaglerproxy/files/src/proxy/ratelimit/ExponentialBackoffRequestController.ts b/eaglerproxy/files/src/proxy/ratelimit/ExponentialBackoffRequestController.ts new file mode 100644 index 0000000..6ee4d12 --- /dev/null +++ b/eaglerproxy/files/src/proxy/ratelimit/ExponentialBackoffRequestController.ts @@ -0,0 +1,63 @@ +const wait = (ms: number) => new Promise((res) => setTimeout(res, ms)); + +export default class ExponentialBackoffRequestController { + public queue: Task[]; + public flushQueueAfterTries: number; + public baseDelay: number; + ended: boolean; + aborted: boolean; + + constructor(baseDelay: number = 3000, triesBeforeFlush: number = 10) { + this.flushQueueAfterTries = triesBeforeFlush; + this.baseDelay = baseDelay; + this.queue = []; + this.ended = false; + this.aborted = false; + setTimeout(() => this.tick(), 0); + } + + private async tick() { + while (true) { + if (this.ended) break; + for (const task of this.queue) { + if (this.ended || this.aborted) break; + let times = 0, + breakOut = false; + while (true) { + try { + await task(); + break; + } catch (err) { + times++; + await wait(this.baseDelay * 2 ** times); + if (times > this.flushQueueAfterTries) { + this.queue.forEach((task) => task(new Error("Controller overload!"))); + breakOut = true; + break; + } + } + } + if (breakOut) break; + } + if (this.aborted) this.aborted = false; + this.queue = []; + await wait(1); + } + } + + public end() { + this.ended = true; + } + + public flush() { + this.aborted = false; + this.queue.forEach((task) => task(new Error("Aborted"))); + this.queue = []; + } + + public queueTask(task: Task): void { + this.queue.push(task); + } +} + +type Task = (err?: object) => void | Promise; diff --git a/eaglerproxy/files/src/proxy/ratelimit/ProxyRatelimitManager.ts b/eaglerproxy/files/src/proxy/ratelimit/ProxyRatelimitManager.ts new file mode 100644 index 0000000..8bfd772 --- /dev/null +++ b/eaglerproxy/files/src/proxy/ratelimit/ProxyRatelimitManager.ts @@ -0,0 +1,21 @@ +import { Config } from "../../launcher_types.js"; +import { Player } from "../Player.js"; +import BucketRateLimiter from "./BucketRatelimiter.js"; + +export default class ProxyRatelimitManager { + http: BucketRateLimiter; + motd: BucketRateLimiter; + ws: BucketRateLimiter; + connect: BucketRateLimiter; + skinsIP: BucketRateLimiter; + skinsConnection: BucketRateLimiter; + + constructor(config: Config["adapter"]["ratelimits"]) { + this.http = new BucketRateLimiter(config.limits.http, config.limits.http); + this.ws = new BucketRateLimiter(config.limits.ws, config.limits.ws); + this.motd = new BucketRateLimiter(config.limits.motd, config.limits.motd); + this.connect = new BucketRateLimiter(config.limits.connect, config.limits.connect); + this.skinsIP = new BucketRateLimiter(config.limits.skinsIp, config.limits.skinsIp); + this.skinsConnection = new BucketRateLimiter(config.limits.skins, config.limits.skins); + } +} diff --git a/eaglerproxy/files/src/proxy/skins/EaglerSkins.ts b/eaglerproxy/files/src/proxy/skins/EaglerSkins.ts new file mode 100644 index 0000000..366acd0 --- /dev/null +++ b/eaglerproxy/files/src/proxy/skins/EaglerSkins.ts @@ -0,0 +1,192 @@ +import { Constants } from "../Constants.js"; +import { Enums } from "../Enums.js"; +import { MineProtocol } from "../Protocol.js"; +import { Util } from "../Util.js"; +import { Player } from "../Player.js"; +import fetch from "node-fetch"; +import ExponentialBackoffRequestController from "../ratelimit/ExponentialBackoffRequestController.js"; + +// TODO: convert all functions to use MineProtocol's UUID manipulation functions + +export namespace EaglerSkins { + export type ClientFetchEaglerSkin = { + id: Enums.EaglerSkinPacketId.CFetchSkinEaglerPlayerReq; + uuid: string; + }; + + export type ServerFetchSkinResultBuiltIn = { + id: Enums.EaglerSkinPacketId.SFetchSkinBuiltInRes; + uuid: string; + skinId: number; + }; + + export type ServerFetchSkinResultCustom = { + id: Enums.EaglerSkinPacketId.SFetchSkinRes; + uuid: string; + skin: Util.BoundedBuffer; + }; + + export type ClientDownloadSkinRequest = { + id: Enums.EaglerSkinPacketId.CFetchSkinReq; + uuid: string; + url: string; + }; + + type MojangFetchProfileResponse = { + id: string; + name: string; + properties: [ + { + name: "textures"; + value: string; + signature: string; + } + ]; + }; + + type MojangTextureResponse = { + timestamp: number; + profileId: string; + profileName: string; + signatureRequired: boolean; + textures: { + SKIN: { + url: string; + metadata: { + model: "slim"; + }; + }; + CAPE: { + url: string; + }; + }; + }; + + export async function skinUrlFromUuid(uuid: string): Promise { + const response = (await (await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`)).json()) as unknown as MojangFetchProfileResponse; + const parsed = JSON.parse(Buffer.from(response.properties[0].value, "base64").toString()) as unknown as MojangTextureResponse; + return parsed.textures.SKIN.url; + } + + export function downloadSkin(skinUrl: string): Promise { + const url = new URL(skinUrl); + if (url.protocol != "https:" && url.protocol != "http:") throw new Error("Invalid skin URL protocol!"); + return new Promise(async (res, rej) => { + const skin = await fetch(skinUrl); + if (skin.status != 200) { + rej({ + url: skinUrl, + status: skin.status, + }); + return; + } else { + res(Buffer.from(await skin.arrayBuffer())); + } + }); + } + + export function safeDownloadSkin(skinUrl: string, backoff: ExponentialBackoffRequestController): Promise { + return new Promise((res, rej) => { + backoff.queueTask(async (err) => { + if (err) return rej(err); + try { + res(await downloadSkin(skinUrl)); + } catch (err) { + if (err.status == 429) throw new Error("Ratelimited!"); + else throw new Error("Unexpected HTTP status code: " + err.status); + } + }); + }); + } + + export function readClientDownloadSkinRequestPacket(message: Buffer): ClientDownloadSkinRequest { + const ret: ClientDownloadSkinRequest = { + id: null, + uuid: null, + url: null, + }; + const id = MineProtocol.readVarInt(message), + uuid = MineProtocol.readUUID(id.newBuffer), + url = MineProtocol.readString(uuid.newBuffer, 1); + ret.id = id.value; + ret.uuid = uuid.value; + ret.url = url.value; + return ret; + } + + export function writeClientDownloadSkinRequestPacket(uuid: string | Buffer, url: string): Buffer { + return Buffer.concat([[Enums.EaglerSkinPacketId.CFetchSkinReq], MineProtocol.writeUUID(uuid), [0x0], MineProtocol.writeString(url)].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr)))); + } + + export function readServerFetchSkinResultBuiltInPacket(message: Buffer): ServerFetchSkinResultBuiltIn { + const ret: ServerFetchSkinResultBuiltIn = { + id: null, + uuid: null, + skinId: null, + }; + const id = MineProtocol.readVarInt(message), + uuid = MineProtocol.readUUID(id.newBuffer), + skinId = MineProtocol.readVarInt(id.newBuffer.subarray(id.newBuffer.length)); + ret.id = id.value; + ret.uuid = uuid.value; + ret.skinId = skinId.value; + return this; + } + + export function writeServerFetchSkinResultBuiltInPacket(uuid: string | Buffer, skinId: number): Buffer { + uuid = typeof uuid == "string" ? Util.uuidStringToBuffer(uuid) : uuid; + return Buffer.concat([Buffer.from([Enums.EaglerSkinPacketId.SFetchSkinBuiltInRes]), uuid as Buffer, Buffer.from([skinId >> 24, skinId >> 16, skinId >> 8, skinId & 0xff])]); + } + + export function readServerFetchSkinResultCustomPacket(message: Buffer): ServerFetchSkinResultCustom { + const ret: ServerFetchSkinResultCustom = { + id: null, + uuid: null, + skin: null, + }; + const id = MineProtocol.readVarInt(message), + uuid = MineProtocol.readUUID(id.newBuffer), + skin = uuid.newBuffer.subarray(0, Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH); + ret.id = id.value; + ret.uuid = uuid.value; + ret.skin = skin; + return this; + } + + export function writeClientFetchEaglerSkin(uuid: string | Buffer, url: string): Buffer { + uuid = typeof uuid == "string" ? Util.uuidStringToBuffer(uuid) : uuid; + return Buffer.concat([[Enums.EaglerSkinPacketId.CFetchSkinEaglerPlayerReq], uuid, [0x00], MineProtocol.writeString(url)].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr)))); + } + + export function writeServerFetchSkinResultCustomPacket(uuid: string | Buffer, skin: Buffer, downloaded: boolean): Buffer { + uuid = typeof uuid == "string" ? Util.uuidStringToBuffer(uuid) : uuid; + return Buffer.concat( + [ + [Enums.EaglerSkinPacketId.SFetchSkinRes], + uuid, + [-1], // TODO: if buggy, use 0xff instead + skin.subarray(0, Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH), + ].map((arr) => (arr instanceof Uint8Array ? arr : Buffer.from(arr))) + ); + } + + export function readClientFetchEaglerSkinPacket(buff: Buffer): ClientFetchEaglerSkin { + const ret: ClientFetchEaglerSkin = { + id: null, + uuid: null, + }; + const id = MineProtocol.readVarInt(buff), + uuid = MineProtocol.readUUID(id.newBuffer); + ret.id = id.value; + ret.uuid = uuid.value; + return ret; + } + + export class EaglerSkin { + owner: Player; + type: Enums.SkinType; + // update this over time + builtInSkin?: Util.Range<0, 23>; + skin?: Util.BoundedBuffer; + } +} diff --git a/eaglerproxy/files/src/proxy/skins/ImageEditor.ts b/eaglerproxy/files/src/proxy/skins/ImageEditor.ts new file mode 100644 index 0000000..ca4d4ea --- /dev/null +++ b/eaglerproxy/files/src/proxy/skins/ImageEditor.ts @@ -0,0 +1,253 @@ +import { Logger } from "../../logger.js"; +import { Constants } from "../Constants.js"; +import { Enums } from "../Enums.js"; +import { MineProtocol } from "../Protocol.js"; +import { Util } from "../Util.js"; +import fs from "fs/promises"; + +let Jimp: Jimp = null; +type Jimp = any; + +let sharp: any = null; +type Sharp = any; + +export namespace ImageEditor { + let loadedLibraries: boolean = false; + + export async function loadLibraries(native: boolean) { + if (loadedLibraries) return; + if (native) sharp = (await import("sharp")).default; + else { + try { + Jimp = (await import("jimp" as any)).default; + } catch (err) { + const logger = new Logger("ImageEditor.js"); + logger.fatal("**** ERROR: UNABLE TO LOAD JIMP!"); + logger.fatal("Please ensure that Jimp is installed by running 'npm install jimp' in the terminal."); + logger.fatal("If you'd like to use the faster native image editor, please set the 'useNatives' option in the config to true."); + logger.fatal(`Error: ${err.stack}`); + process.exit(1); + } + Jimp.appendConstructorOption( + "Custom Bitmap Constructor", + (args) => args[0] && args[0].width != null && args[0].height != null && args[0].data != null, + (res, rej, args) => { + this.bitmap = args[0]; + res(); + } + ); + } + + loadedLibraries = true; + } + + export async function copyRawPixelsJS(imageIn: Jimp, imageOut: Jimp, dx1: number, dy1: number, dx2: number, dy2: number, sx1: number, sy1: number, sx2: number, sy2: number): Promise { + console.log(imageOut); + if (dx1 > dx2) { + return _copyRawPixelsJS(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, imageIn.getWidth(), imageOut.getWidth(), true); + } else { + return _copyRawPixelsJS(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, imageIn.getWidth(), imageOut.getWidth(), false); + } + } + + // async function _copyRawPixelsJS(imageIn: Jimp, imageOut: Jimp, srcX: number, srcY: number, dstX: number, dstY: number, width: number, height: number, imgSrcWidth: number, imgDstWidth: number, flip: boolean): Promise { + // const inData = imageIn.bitmap.data, + // outData = imageOut.bitmap.data; + + // for (let y = 0; y < height; y++) { + // for (let x = 0; x < width; x++) { + // let srcIndex = (srcY + y) * imgSrcWidth + srcX + x; + // let dstIndex = (dstY + y) * imgDstWidth + dstX + x; + + // if (flip) { + // srcIndex = (srcY + y) * imgSrcWidth + srcX + (width - x - 1); + // } + + // for (let c = 0; c < 4; c++) { + // // Assuming RGBA channels + // outData[dstIndex * 4 + c] = inData[srcIndex * 4 + c]; + // } + // } + // } + // return imageOut; + + // // return sharp(outData, { + // // raw: { + // // width: outMeta.width!, + // // height: outMeta.height!, + // // channels: 4, + // // }, + // // }); + // } + + async function _copyRawPixelsJS(imageIn: Jimp, imageOut: Jimp, srcX: number, srcY: number, dstX: number, dstY: number, width: number, height: number, imgSrcWidth: number, imgDstWidth: number, flip: boolean) { + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let srcIndex = (srcY + y) * imgSrcWidth + srcX + x; + + if (flip) { + srcIndex = (srcY + y) * imgSrcWidth + srcX + (width - x - 1); + } + + const pixelColor = imageIn.getPixelColor(srcX + x, srcY + y); + const rgba = Jimp.intToRGBA(pixelColor); + + imageOut.setPixelColor(Jimp.rgbaToInt(rgba.r, rgba.g, rgba.b, rgba.a), dstX + x, dstY + y); + } + } + + return imageOut; + } + + export async function copyRawPixels(imageIn: Sharp, imageOut: Sharp, dx1: number, dy1: number, dx2: number, dy2: number, sx1: number, sy1: number, sx2: number, sy2: number): Promise { + const inMeta = await imageIn.metadata(), + outMeta = await imageOut.metadata(); + + if (dx1 > dx2) { + return _copyRawPixels(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, inMeta.width!, outMeta.width!, true); + } else { + return _copyRawPixels(imageIn, imageOut, sx1, sy1, dx1, dy1, sx2 - sx1, sy2 - sy1, inMeta.width!, outMeta.width!, false); + } + } + + async function _copyRawPixels(imageIn: Sharp, imageOut: Sharp, srcX: number, srcY: number, dstX: number, dstY: number, width: number, height: number, imgSrcWidth: number, imgDstWidth: number, flip: boolean): Promise { + const inData = await imageIn.raw().toBuffer(); + const outData = await imageOut.raw().toBuffer(); + const outMeta = await imageOut.metadata(); + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let srcIndex = (srcY + y) * imgSrcWidth + srcX + x; + let dstIndex = (dstY + y) * imgDstWidth + dstX + x; + + if (flip) { + srcIndex = (srcY + y) * imgSrcWidth + srcX + (width - x - 1); + } + + for (let c = 0; c < 4; c++) { + // Assuming RGBA channels + outData[dstIndex * 4 + c] = inData[srcIndex * 4 + c]; + } + } + } + + return sharp(outData, { + raw: { + width: outMeta.width!, + height: outMeta.height!, + channels: 4, + }, + }); + } + + export async function toEaglerSkinJS(image: Buffer): Promise> { + let jimpImage = await Jimp.read(image), + height = jimpImage.getHeight(); + if (height != 64) { + // assume 32 height skin + let imageOut = await Jimp.create(64, 64, 0x0); + + for (let x = 0; x < jimpImage.getWidth(); x++) { + for (let y = 0; y < jimpImage.getHeight(); y++) { + imageOut.setPixelColor(jimpImage.getPixelColor(x, y), x, y); + } + } + + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 24, 48, 20, 52, 4, 16, 8, 20); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 28, 48, 24, 52, 8, 16, 12, 20); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 20, 52, 16, 64, 8, 20, 12, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 24, 52, 20, 64, 4, 20, 8, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 28, 52, 24, 64, 0, 20, 4, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 32, 52, 28, 64, 12, 20, 16, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 40, 48, 36, 52, 44, 16, 48, 20); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 44, 48, 40, 52, 48, 16, 52, 20); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 36, 52, 32, 64, 48, 20, 52, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 40, 52, 36, 64, 44, 20, 48, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 44, 52, 40, 64, 40, 20, 44, 32); + imageOut = await copyRawPixelsJS(jimpImage, imageOut, 48, 52, 44, 64, 52, 20, 56, 32); + + jimpImage = imageOut; + } + + const newBuff = Buffer.alloc(Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH); + const bitmap = jimpImage.bitmap.data; + for (let i = 1; i < 64 ** 2; i++) { + const bytePos = i * 4; + // red, green, blue, alpha => alpha, blue, green, red + newBuff[bytePos] = bitmap[bytePos + 3]; + newBuff[bytePos + 1] = bitmap[bytePos + 2]; + newBuff[bytePos + 2] = bitmap[bytePos + 1]; + newBuff[bytePos + 3] = bitmap[bytePos]; + } + return newBuff; + } + + export async function toEaglerSkin(image: Buffer): Promise> { + const meta = await sharp(image).metadata(); + let sharpImage = sharp(image); + if (meta.height != 64) { + // assume 32 height skin + let imageOut = sharp(await sharpImage.extend({ bottom: 32, background: { r: 0, g: 0, b: 0, alpha: 0 } }).toBuffer()); + + imageOut = await copyRawPixels(sharpImage, imageOut, 24, 48, 20, 52, 4, 16, 8, 20); + imageOut = await copyRawPixels(sharpImage, imageOut, 28, 48, 24, 52, 8, 16, 12, 20); + imageOut = await copyRawPixels(sharpImage, imageOut, 20, 52, 16, 64, 8, 20, 12, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 24, 52, 20, 64, 4, 20, 8, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 28, 52, 24, 64, 0, 20, 4, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 32, 52, 28, 64, 12, 20, 16, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 40, 48, 36, 52, 44, 16, 48, 20); + imageOut = await copyRawPixels(sharpImage, imageOut, 44, 48, 40, 52, 48, 16, 52, 20); + imageOut = await copyRawPixels(sharpImage, imageOut, 36, 52, 32, 64, 48, 20, 52, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 40, 52, 36, 64, 44, 20, 48, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 44, 52, 40, 64, 40, 20, 44, 32); + imageOut = await copyRawPixels(sharpImage, imageOut, 48, 52, 44, 64, 52, 20, 56, 32); + + sharpImage = imageOut; + } + + const r = await sharpImage.extractChannel("red").raw({ depth: "uchar" }).toBuffer(); + const g = await sharpImage.extractChannel("green").raw({ depth: "uchar" }).toBuffer(); + const b = await sharpImage.extractChannel("blue").raw({ depth: "uchar" }).toBuffer(); + const a = await sharpImage.ensureAlpha().extractChannel(3).toColorspace("b-w").raw({ depth: "uchar" }).toBuffer(); + const newBuff = Buffer.alloc(Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH); + for (let i = 1; i < 64 ** 2; i++) { + const bytePos = i * 4; + newBuff[bytePos] = a[i]; + newBuff[bytePos + 1] = b[i]; + newBuff[bytePos + 2] = g[i]; + newBuff[bytePos + 3] = r[i]; + } + return newBuff; + } + + export function generateEaglerMOTDImage(file: string | Buffer): Promise { + return new Promise((res, rej) => { + sharp(file) + .resize(Constants.ICON_SQRT, Constants.ICON_SQRT, { + kernel: "nearest", + }) + .raw({ + depth: "uchar", + }) + .toBuffer() + .then((buff) => { + for (const pixel of buff) { + if ((pixel & 0xffffff) == 0) { + buff[buff.indexOf(pixel)] = 0; + } + } + res(buff); + }) + .catch(rej); + }); + } + + export function generateEaglerMOTDImageJS(file: string | Buffer): Promise { + return new Promise(async (res, rej) => { + Jimp.read(typeof file == "string" ? await fs.readFile(file) : file, async (err, image) => { + image = image.resize(Constants.ICON_SQRT, Constants.ICON_SQRT, Jimp.RESIZE_NEAREST_NEIGHBOR); + res(image.bitmap.data); + }); + }); + } +} diff --git a/eaglerproxy/files/src/proxy/skins/SkinServer.ts b/eaglerproxy/files/src/proxy/skins/SkinServer.ts new file mode 100644 index 0000000..809a407 --- /dev/null +++ b/eaglerproxy/files/src/proxy/skins/SkinServer.ts @@ -0,0 +1,146 @@ +import DiskDB from "../databases/DiskDB.js"; +import crypto from "crypto"; +import { Logger } from "../../logger.js"; +import { Constants } from "../Constants.js"; +import { Enums } from "../Enums.js"; +import { Player } from "../Player.js"; +import { Proxy } from "../Proxy.js"; +import { Util } from "../Util.js"; +import { CSChannelMessagePacket } from "../packets/channel/CSChannelMessage.js"; +import { SCChannelMessagePacket } from "../packets/channel/SCChannelMessage.js"; +import { EaglerSkins } from "./EaglerSkins.js"; +import { ImageEditor } from "./ImageEditor.js"; +import { MineProtocol } from "../Protocol.js"; +import ExponentialBackoffRequestController from "../ratelimit/ExponentialBackoffRequestController.js"; + +export class SkinServer { + public allowedSkinDomains: string[]; + public cache: DiskDB; + public proxy: Proxy; + public backoffController: ExponentialBackoffRequestController; + public usingNative: boolean; + public usingCache: boolean; + private _logger: Logger; + private deleteTask: NodeJS.Timer; + private lifetime: number; + + constructor(proxy: Proxy, native: boolean, sweepInterval: number, cacheLifetime: number, cacheFolder: string = "./skinCache", useCache: boolean = true, allowedSkinDomains?: string[]) { + this.allowedSkinDomains = allowedSkinDomains ?? ["textures.minecraft.net"]; + if (useCache) { + this.cache = new DiskDB( + cacheFolder, + (v) => exportCachedSkin(v), + (b) => readCachedSkin(b), + (k) => k.replaceAll("-", "") + ); + } + this.proxy = proxy ?? PROXY; + this.usingCache = useCache; + this.usingNative = native; + this.lifetime = cacheLifetime; + this.backoffController = new ExponentialBackoffRequestController(); + this._logger = new Logger("SkinServer"); + this._logger.info("Started EaglercraftX skin server."); + if (useCache) this.deleteTask = setInterval(async () => await this.cache.filter((ent) => Date.now() < ent.expires), sweepInterval); + } + + public unload() { + if (this.deleteTask != null) clearInterval(this.deleteTask); + } + + public async handleRequest(packet: CSChannelMessagePacket, caller: Player, proxy: Proxy) { + if (packet.messageType == Enums.ChannelMessageType.SERVER) throw new Error("Server message was passed to client message handler!"); + else if (packet.channel != Constants.EAGLERCRAFT_SKIN_CHANNEL_NAME) throw new Error("Cannot handle non-EaglerX skin channel messages!"); + + { + const rl = proxy.ratelimit.skinsConnection.consume(caller.username), + rlip = proxy.ratelimit.skinsIP.consume(caller.ws._socket.remoteAddress); + if (!rl.success || !rlip.success) return; + } + + switch (packet.data[0] as Enums.EaglerSkinPacketId) { + default: + throw new Error("Unknown operation!"); + break; + case Enums.EaglerSkinPacketId.CFetchSkinEaglerPlayerReq: + const parsedPacket_0 = EaglerSkins.readClientFetchEaglerSkinPacket(packet.data); + const player = this.proxy.fetchUserByUUID(parsedPacket_0.uuid); + if (player) { + if (player.skin.type == Enums.SkinType.BUILTIN) { + const response = new SCChannelMessagePacket(); + response.channel = Constants.EAGLERCRAFT_SKIN_CHANNEL_NAME; + response.data = EaglerSkins.writeServerFetchSkinResultBuiltInPacket(player.uuid, player.skin.builtInSkin); + caller.write(response); + } else if (player.skin.type == Enums.SkinType.CUSTOM) { + const response = new SCChannelMessagePacket(); + response.channel = Constants.EAGLERCRAFT_SKIN_CHANNEL_NAME; + response.data = EaglerSkins.writeServerFetchSkinResultCustomPacket(player.uuid, player.skin.skin, false); + caller.write(response); + } else this._logger.warn(`Player ${caller.username} attempted to fetch player ${player.uuid}'s skin, but their skin hasn't loaded yet!`); + } + break; + case Enums.EaglerSkinPacketId.CFetchSkinReq: + const parsedPacket_1 = EaglerSkins.readClientDownloadSkinRequestPacket(packet.data), + url = new URL(parsedPacket_1.url).hostname; + if (!this.allowedSkinDomains.some((domain) => Util.areDomainsEqual(domain, url))) { + this._logger.warn(`Player ${caller.username} tried to download a skin with a disallowed domain name (${url})!`); + break; + } + try { + let cacheHit = null, + skin = null; + if (this.usingCache) { + (cacheHit = await this.cache.get(parsedPacket_1.uuid)), (skin = cacheHit != null ? cacheHit.data : null); + + if (!skin) { + const fetched = await EaglerSkins.safeDownloadSkin(parsedPacket_1.url, this.backoffController); + skin = fetched; + await this.cache.set(parsedPacket_1.uuid, { + uuid: parsedPacket_1.uuid, + expires: Date.now() + this.lifetime, + data: fetched, + }); + } + } else { + skin = await EaglerSkins.safeDownloadSkin(parsedPacket_1.url, this.backoffController); + } + + const processed = this.usingNative ? await ImageEditor.toEaglerSkin(skin) : await ImageEditor.toEaglerSkinJS(skin), + response = new SCChannelMessagePacket(); + response.channel = Constants.EAGLERCRAFT_SKIN_CHANNEL_NAME; + response.data = EaglerSkins.writeServerFetchSkinResultCustomPacket(parsedPacket_1.uuid, processed, true); + caller.write(response); + } catch (err) { + this._logger.warn(`Failed to fetch skin URL ${parsedPacket_1.url} for player ${caller.username}: ${err.stack ?? err}`); + } + } + } +} + +export type CachedSkin = { + uuid: string; + expires: number; + data: Buffer; +}; + +function digestMd5Hex(data: Buffer | string): string { + return crypto.createHash("md5").update(data).digest("hex"); +} + +function exportCachedSkin(skin: CachedSkin): Buffer { + const endUuid = MineProtocol.writeString(skin.uuid), + encExp = MineProtocol.writeVarLong(skin.expires), + encSkin = MineProtocol.writeBinary(skin.data); + return Buffer.concat([endUuid, encExp, encSkin]); +} + +function readCachedSkin(data: Buffer): CachedSkin { + const readUuid = MineProtocol.readString(data), + readExp = MineProtocol.readVarLong(readUuid.newBuffer), + readSkin = MineProtocol.readBinary(readExp.newBuffer); + return { + uuid: readUuid.value, + expires: readExp.value, + data: readSkin.value, + }; +} diff --git a/eaglerproxy/files/tsconfig.json b/eaglerproxy/files/tsconfig.json new file mode 100644 index 0000000..cdd5196 --- /dev/null +++ b/eaglerproxy/files/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "esnext", + "esModuleInterop": true, + "target": "ESNext", + "moduleResolution": "node", + "sourceMap": false, + "outDir": "build", + "resolveJsonModule": true, + "rootDir": "src", + "skipLibCheck": true + }, + "include": ["src/**/*.json", "src/**/*"], + "hooks": ["copy-files"] +}