Archive eaglerproxy (server, 1.8.8, clean)
This commit is contained in:
@@ -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": []
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
build
|
||||
.sourcehash
|
||||
.DS_Store
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,104 @@
|
||||
# EaglerProxy
|
||||
|
||||
<a href="https://repl.it/github/WorldEditAxe/eaglerproxy"><img height="30px" src="https://raw.githubusercontent.com/FogNetwork/Tsunami/main/deploy/replit2.svg"><img></a>
|
||||
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._
|
||||
**<u>If you are running the proxy through either Termux or CodeSandbox's on-device runtime:</u>**
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,4 @@
|
||||
export const config = {
|
||||
bindInternalServerPort: 25569,
|
||||
bindInternalServerIp: "127.0.0.1",
|
||||
};
|
||||
@@ -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",
|
||||
};
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
const logger = new PLUGIN_MANAGER.Logger("ExamplePlugin");
|
||||
logger.info("Hi!");
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "Example Plugin",
|
||||
"id": "examplePlugin",
|
||||
"version": "1.0.0",
|
||||
"entry_point": "index.js",
|
||||
"requirements": [],
|
||||
"incompatibilities": [],
|
||||
"load_after": []
|
||||
}
|
||||
@@ -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;
|
||||
Generated
+2296
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{ pkgs }: {
|
||||
deps = [
|
||||
pkgs.yarn
|
||||
pkgs.esbuild
|
||||
pkgs.nodejs-18_x
|
||||
|
||||
pkgs.nodePackages.typescript
|
||||
pkgs.nodePackages.typescript-language-server
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
cd ~/$REPL_SLUG/build
|
||||
node index.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")
|
||||
),
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "replit_runtime",
|
||||
"description": "Runtime preparation utility for Repls. Determines whether or not a recompilation is necessary.",
|
||||
"type": "commonjs"
|
||||
}
|
||||
@@ -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.<ENV name>
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
Vendored
+16
@@ -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;
|
||||
}
|
||||
>;
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
};
|
||||
};
|
||||
@@ -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
|
||||
);
|
||||
@@ -0,0 +1,11 @@
|
||||
const f = Object.freeze;
|
||||
|
||||
// bridge meta
|
||||
export const BRIDGE_VERSION: Readonly<number> = f(1);
|
||||
|
||||
// adapter meta
|
||||
export const PROXY_BRANDING: Readonly<string> = f("EaglerProxy");
|
||||
export const PROXY_VERSION: Readonly<string> = f("1.1.0");
|
||||
|
||||
export const NETWORK_VERSION: Readonly<number> = f(0x03);
|
||||
export const VANILLA_PROTOCOL_VERSION: Readonly<number> = f(47);
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import mc from "minecraft-protocol";
|
||||
import { Enums } from "../../proxy/Enums.js";
|
||||
|
||||
export async function getTokenProfileTheAltening(token: string): Promise<object> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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 <mode: online|offline> <ip>${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 <mode: online|offline> <ip>${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 <mode: online|offline> <ip>${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 <mode: online|offline> <ip>${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 <mode: online|offline> <ip>${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 <mode: online|offline> <ip>${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?") : ""}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
},
|
||||
};
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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": []
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { ServerDeviceCodeResponse, auth } from "../auth.js";
|
||||
import { config } from "../config.js";
|
||||
|
||||
const LINK_STR = `
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>EagPAAS - Connect</title>
|
||||
<style>
|
||||
:root {
|
||||
font-family: "Arial";
|
||||
}
|
||||
code {
|
||||
padding: 3px 10px 3px 10px;
|
||||
border-radius: 5px;
|
||||
font-family: monospace;
|
||||
background-color: #1a1a1a;
|
||||
color: white;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
window.addEventListener("load", () => {
|
||||
let param = new URLSearchParams(window.location.search),
|
||||
url = param.get("url")
|
||||
if (url == null) url = "ERROR!"
|
||||
else {
|
||||
try {
|
||||
const parsed = new URL(url), session = JSON.parse(parsed.searchParams.get("session"))
|
||||
if (session.expires_on < Date.now()) {
|
||||
url = "EXPIRED: get a new link!"
|
||||
}
|
||||
} catch (_e) {
|
||||
console.error(_e)
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById("connect-url").innerHTML =
|
||||
url.replace(
|
||||
"wss:",
|
||||
window.location.protocol == "wss:" ? "wss:" : "ws:",
|
||||
)
|
||||
const parsedURL = new URL(url)
|
||||
document.getElementById("connect-url-vanilla").innerHTML =
|
||||
"vanilla+online://" + parsedURL.searchParams.get("ip") + ":" + parsedURL.searchParams.get("port") + "/?session=" + parsedURL.searchParams.get("session")
|
||||
})
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>EagPAAS - Connect to Server</h1>
|
||||
<p>
|
||||
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)
|
||||
<br><br><code id="connect-url">loading...</code><br><br>
|
||||
|
||||
If your Eaglercraft client supports <code>vanilla://</code> URLs, this will also work:
|
||||
<br><br><code id="connect-url-vanilla">loading...</code><br><br>
|
||||
|
||||
Note that your session will eventually expire, and you will need to log back in again.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
`;
|
||||
|
||||
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) {}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Client, Server } from "minecraft-protocol";
|
||||
|
||||
export type ServerGlobals = {
|
||||
server: Server;
|
||||
players: Map<string, ClientState>;
|
||||
};
|
||||
|
||||
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",
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 = `<!DOCTYPE html><!-- Served by ${meta.PROXY_BRANDING} (version: ${meta.PROXY_VERSION}) --><html> <head> <title>EaglerProxy landing page</title> <style> :root { font-family: "Arial" } code { padding: 3px 10px 3px 10px; border-radius: 5px; font-family: monospace; background-color: #1a1a1a; color: white; } </style> <script type="text/javascript"> window.addEventListener('load', () => { document.getElementById("connect-url").innerText = window.location.href.replace(window.location.protocol, window.location.protocol == "https:" ? "wss:" : "ws:"); }); </script> </head> <body> <h1>426 - Upgrade Required</h1> <p>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: <code id="connect-url">loading...</code> (connect from any recent EaglercraftX client via Multiplayer > Direct Connect)</p> </body></html>`;
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
@@ -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<MOTD> {
|
||||
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<MOTD> {
|
||||
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<typeof Date.now>;
|
||||
type: "motd";
|
||||
uuid: ReturnType<typeof randomUUID>;
|
||||
vers: string;
|
||||
};
|
||||
}
|
||||
@@ -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<Map<Enums.PacketId, Packet & { class: any }>> {
|
||||
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;
|
||||
}
|
||||
@@ -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<Packet> {
|
||||
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<void | never>(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<U extends keyof PlayerEvents>(event: U, listener: PlayerEvents[U]): this;
|
||||
once<U extends keyof PlayerEvents>(event: U, listener: PlayerEvents[U]): this;
|
||||
|
||||
emit<U extends keyof PlayerEvents>(event: U, ...args: Parameters<PlayerEvents[U]>): boolean;
|
||||
}
|
||||
@@ -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<T> = {
|
||||
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<number> {
|
||||
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<number> {
|
||||
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<Buffer> {
|
||||
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<string> {
|
||||
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<number> {
|
||||
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<string> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, Player>();
|
||||
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<Motd.MOTD> }) => 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<U extends keyof ProxyEvents>(event: U, listener: ProxyEvents[U]): this;
|
||||
emit<U extends keyof ProxyEvents>(event: U, ...args: Parameters<ProxyEvents[U]>): boolean;
|
||||
}
|
||||
@@ -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<B, E> = number;
|
||||
|
||||
export type BoundedBuffer<S extends number> = 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<Buffer> {
|
||||
return new Promise<Buffer>((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<string[]> {
|
||||
const ents = [];
|
||||
for await (const f of _getFiles(dir)) {
|
||||
ents.push(f);
|
||||
}
|
||||
return ents;
|
||||
}
|
||||
|
||||
export async function fsExists(path: string): Promise<boolean> {
|
||||
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;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import path from "path";
|
||||
import fs from "fs/promises";
|
||||
import fss from "fs";
|
||||
|
||||
export default class DiskDB<T extends any> {
|
||||
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<T | null> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<Enums.SkinType, "NOT_LOADED">;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
};
|
||||
}
|
||||
@@ -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<string, { exports: any; metadata: PluginLoaderTypes.PluginMetadataPathed }>;
|
||||
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<Map<string, PluginLoaderTypes.PluginMetadataPathed>> {
|
||||
const ret: Map<string, PluginLoaderTypes.PluginMetadataPathed> = 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("<metadata>.name is either null or not of a string type!");
|
||||
if (typeof metadata.id != "string") throw new TypeError("<metadata>.id is either null or not of a string type!");
|
||||
if (/ /gm.test(metadata.id)) throw new Error(`<metadata>.id contains whitespace!`);
|
||||
if (!semver.valid(metadata.version)) throw new Error("<metadata>.version is either null, not a string, or is not a valid SemVer!");
|
||||
if (typeof metadata.entry_point != "string") throw new TypeError("<metadata>.entry_point is either null or not a string!");
|
||||
if (!metadata.entry_point.endsWith(".js")) throw new Error(`<metadata>.entry_point (${metadata.entry_point}) references a non-JavaScript file!`);
|
||||
if (!(await Util.fsExists(pathUtil.resolve(path, metadata.entry_point)))) throw new Error(`<metadata>.entry_point (${metadata.entry_point}) references a non-existent file!`);
|
||||
if (metadata.requirements instanceof Array == false) throw new TypeError("<metadata>.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(`<metadata>.requirements[${(metadata.requirements as any).indexOf(requirement)}] is either null or not an object!`);
|
||||
if (typeof requirement.id != "string") throw new TypeError(`<metadata>.requirements[${(metadata.requirements as any).indexOf(requirement)}].id is either null or not a string!`);
|
||||
if (/ /gm.test(requirement.id)) throw new TypeError(`<metadata>.requirements[${(metadata.requirements as any).indexOf(requirement)}].id contains whitespace!`);
|
||||
if (semver.validRange(requirement.version) == null && requirement.version != "any")
|
||||
throw new TypeError(`<metadata>.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("<metadata>.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(`<metadata>.load_after[${(metadata.load_after as any).indexOf(loadReq)}] is either null, or not a valid ID!`);
|
||||
if (/ /gm.test(loadReq)) throw new TypeError(`<metadata>.load_after[${(metadata.load_after as any).indexOf(loadReq)}] contains whitespace!`);
|
||||
}
|
||||
if (metadata.incompatibilities instanceof Array == false) throw new TypeError("<metadata>.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(`<metadata>.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}] is either null or not an object!`);
|
||||
if (typeof incompatibility.id != "string") throw new TypeError(`<metadata>.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}].id is either null or not a string!`);
|
||||
if (/ /gm.test(incompatibility.id)) throw new TypeError(`<metadata>.incompatibilities[${(metadata.load_after as any).indexOf(incompatibility)}].id contains whitespace!`);
|
||||
if (semver.validRange(incompatibility.version) == null) throw new TypeError(`<metadata>.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<string, PluginLoaderTypes.PluginMetadataPathed>) {
|
||||
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<string, PluginLoaderTypes.PluginMetadataPathed>): 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<string, PluginLoaderTypes.PluginMetadataPathed>, order: PluginLoaderTypes.PluginLoadOrder): Promise<number> {
|
||||
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<U extends keyof PluginManagerEvents>(event: U, listener: PluginManagerEvents[U]): this;
|
||||
|
||||
emit<U extends keyof PluginManagerEvents>(event: U, ...args: Parameters<PluginManagerEvents[U]>): boolean;
|
||||
|
||||
once<U extends keyof PluginManagerEvents>(event: U, listener: PluginManagerEvents[U]): this;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { Logger } from "../../logger.js";
|
||||
|
||||
export default class BucketRateLimiter {
|
||||
public capacity: number;
|
||||
public refillsPerMin: number;
|
||||
public keyMap: Map<string, KeyData>;
|
||||
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;
|
||||
};
|
||||
@@ -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<void>;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<typeof Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH>;
|
||||
};
|
||||
|
||||
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<string> {
|
||||
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<Buffer> {
|
||||
const url = new URL(skinUrl);
|
||||
if (url.protocol != "https:" && url.protocol != "http:") throw new Error("Invalid skin URL protocol!");
|
||||
return new Promise<Buffer>(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<Buffer> {
|
||||
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<typeof Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH>;
|
||||
}
|
||||
}
|
||||
@@ -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<Jimp> {
|
||||
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<Jimp> {
|
||||
// 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<Sharp> {
|
||||
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<Sharp> {
|
||||
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<Util.BoundedBuffer<typeof Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH>> {
|
||||
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<Util.BoundedBuffer<typeof Constants.EAGLERCRAFT_SKIN_CUSTOM_LENGTH>> {
|
||||
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<Buffer> {
|
||||
return new Promise<Buffer>((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<Buffer> {
|
||||
return new Promise<Buffer>(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);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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<CachedSkin>;
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
Reference in New Issue
Block a user