${config.allowCustomPorts ? " [port]" : ""}.`,
+ color: "gold",
+ },
+ ],
+ });
+ }
+
+ let connectionType = mode == "offline" ? ConnectType.OFFLINE : ConnectType.ONLINE,
+ addr = ip,
+ addrPort = Number(port);
+ if (connectionType == ConnectType.ONLINE) {
+ if ((sender as any)._onlineSession == null) {
+ sendPluginChatMessage(sender, {
+ text: `You either connected to this proxy under offline mode, or your online/TheAltening session has timed out and has become invalid.`,
+ color: "red",
+ });
+ return sendPluginChatMessage(sender, {
+ text: `To switch to online servers, please reconnect and log-in through online/TheAltening mode.`,
+ color: "red",
+ });
+ } else {
+ if (!(await isValidIp(addr))) {
+ return sendPluginChatMessage(sender, {
+ text: "This IP is invalid!",
+ color: "red",
+ });
+ }
+ const savedAuth = (sender as any)._onlineSession;
+ sendPluginChatMessage(sender, {
+ text: `(joining server under ${savedAuth.username}/your ${savedAuth.isTheAltening ? "TheAltening" : "Minecraft"} account's username)`,
+ color: "aqua",
+ });
+ sendPluginChatMessage(sender, {
+ text: "Attempting to switch servers, please wait... (if you don't get connected to the target server after a while, the server might not be a Minecraft server at all. Reconnect and try again.)",
+ color: "gray",
+ });
+ (sender as any)._serverSwitchLock = true;
+ try {
+ await sender.switchServers({
+ host: addr,
+ port: addrPort,
+ version: "1.8.8",
+ keepAlive: false,
+ skipValidation: true,
+ hideErrors: true,
+ ...savedAuth,
+ });
+ (sender as any)._serverSwitchLock = false;
+ } catch (err) {
+ if (sender.state! != Enums.ClientState.DISCONNECTED) {
+ sender.disconnect(
+ Enums.ChatColor.RED +
+ `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (addr.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}`
+ );
+ }
+ }
+ }
+ } else {
+ sendPluginChatMessage(sender, {
+ text: `(joining server under ${sender.username}/Eaglercraft username)`,
+ color: "aqua",
+ });
+ sendPluginChatMessage(sender, {
+ text: "Attempting to switch servers, please wait... (if you don't get connected to the target server for a while, the server might be online only)",
+ color: "gray",
+ });
+ try {
+ (sender as any)._serverSwitchLock = true;
+ await sender.switchServers({
+ host: addr,
+ port: addrPort,
+ version: "1.8.8",
+ username: sender.username,
+ auth: "offline",
+ keepAlive: false,
+ skipValidation: true,
+ hideErrors: true,
+ });
+ (sender as any)._serverSwitchLock = false;
+ } catch (err) {
+ if (sender.state! != Enums.ClientState.DISCONNECTED) {
+ sender.disconnect(
+ Enums.ChatColor.RED +
+ `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (addr.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}`
+ );
+ }
+ }
+ }
+}
diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/config.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/config.ts
new file mode 100644
index 0000000..68f40fb
--- /dev/null
+++ b/eaglerproxy/files/src/plugins/EagProxyAAS/config.ts
@@ -0,0 +1,12 @@
+export const config = {
+ bindInternalServerPort: 25569,
+ bindInternalServerIp: "127.0.0.1",
+ allowCustomPorts: true,
+ allowDirectConnectEndpoints: true,
+ disallowHypixel: false,
+ showDisclaimers: false,
+ authentication: {
+ enabled: false,
+ password: "nope",
+ },
+};
diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/index.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/index.ts
new file mode 100644
index 0000000..737d796
--- /dev/null
+++ b/eaglerproxy/files/src/plugins/EagProxyAAS/index.ts
@@ -0,0 +1,143 @@
+import { config } from "./config.js";
+import { createServer } from "minecraft-protocol";
+import { ClientState, ConnectionState, ConnectType, ServerGlobals } from "./types.js";
+import { handleConnect, hushConsole, isValidIp, sendChatComponent, setSG } from "./utils.js";
+import path from "path";
+import { readFileSync } from "fs";
+import { handleCommand } from "./commands.js";
+import { registerEndpoints } from "./service/endpoints.js";
+
+const PluginManager = PLUGIN_MANAGER;
+const metadata = JSON.parse(
+ readFileSync(process.platform == "win32" ? path.join(path.dirname(new URL(import.meta.url).pathname), "metadata.json").slice(1) : path.join(path.dirname(new URL(import.meta.url).pathname), "metadata.json")).toString()
+);
+
+const Logger = PluginManager.Logger;
+const Enums = PluginManager.Enums;
+const Chat = PluginManager.Chat;
+const Constants = PluginManager.Constants;
+const Motd = PluginManager.Motd;
+const Player = PluginManager.Player;
+const MineProtocol = PluginManager.MineProtocol;
+const EaglerSkins = PluginManager.EaglerSkins;
+const Util = PluginManager.Util;
+hushConsole();
+
+const logger = new Logger("EaglerProxyAAS");
+logger.info(`Starting ${metadata.name} v${metadata.version}...`);
+logger.info(`(internal server port: ${config.bindInternalServerPort}, internal server IP: ${config.bindInternalServerIp})`);
+
+logger.info("Starting internal server...");
+let server = createServer({
+ host: config.bindInternalServerIp,
+ port: config.bindInternalServerPort,
+ motdMsg: `${Enums.ChatColor.GOLD}EaglerProxy as a Service`,
+ "online-mode": false,
+ version: "1.8.9",
+ }),
+ sGlobals: ServerGlobals = {
+ server: server,
+ players: new Map(),
+ };
+setSG(sGlobals);
+
+server.on("login", async (client) => {
+ const proxyPlayer = PluginManager.proxy.players.get(client.username);
+ if (proxyPlayer != null) {
+ const url = new URL(proxyPlayer.ws.httpRequest.url, `http${PluginManager.proxy.config.tls?.enabled ? "s" : ""}://${proxyPlayer.ws.httpRequest.headers.host}`);
+ let host = url.searchParams.get("ip"),
+ port = url.searchParams.get("port"),
+ type = url.searchParams.get("authType") as any;
+ let params: {
+ ip: string;
+ port: number;
+ mode: ConnectType;
+ session: any | null;
+ } = undefined;
+ if (host != undefined && url.searchParams.size > 0) {
+ if (!config.allowDirectConnectEndpoints) {
+ return proxyPlayer.disconnect(Enums.ChatColor.RED + "Direct connect endpoints are disabled");
+ }
+ if (config.disallowHypixel && /^(?:[\w-]+\.)?hypixel\.net$/.test(host)) {
+ return proxyPlayer.disconnect(Enums.ChatColor.RED + "Hypixel is disabled for this proxy");
+ }
+ if (isNaN(Number(port)) && port != null) return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad port number");
+ else if (port == null) port = "25565";
+ if (!(await isValidIp(host))) {
+ return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad host");
+ }
+ if (type != "OFFLINE" && type != "ONLINE" && type != "THEALTENING" && type != null) {
+ return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad authType provided");
+ } else if (type == null) type = undefined;
+ type = type == undefined ? undefined : type == "OFFLINE" ? ConnectType.OFFLINE : type == "ONLINE" ? ConnectType.ONLINE : ConnectType.THEALTENING;
+ let sess = undefined;
+ // try {
+ // sess = JSON.parse(url.searchParams.get("session"));
+ // } catch (e) {
+ // console.log(e);
+ // return proxyPlayer.disconnect(Enums.ChatColor.RED + "Bad session data provided (get a new URL?)");
+ // }
+ // if (sess && sess.expires_on != null && sess.expires_on < Date.now()) {
+ // return proxyPlayer.disconnect(Enums.ChatColor.RED + "Session expired (get a new URL/try reloggging?)");
+ // }
+
+ params = {
+ ip: host,
+ port: Number(port),
+ mode: type,
+ session: sess,
+ };
+ }
+
+ logger.info(`Client ${client.username} has connected to the authentication server.`);
+ client.on("end", () => {
+ sGlobals.players.delete(client.username);
+ logger.info(`Client ${client.username} has disconnected from the authentication server.`);
+ });
+ const cs: ClientState = {
+ state: ConnectionState.AUTH,
+ gameClient: client,
+ token: null,
+ lastStatusUpdate: null,
+ };
+ sGlobals.players.set(client.username, cs);
+ handleConnect(cs, params);
+ } else {
+ logger.warn(`Proxy player object is null for ${client.username}?!`);
+ client.end("Indirect connection to internal authentication server detected!");
+ }
+});
+
+logger.info("Redirecting backend server IP... (this is required for the plugin to function)");
+CONFIG.adapter.server = {
+ host: config.bindInternalServerIp,
+ port: config.bindInternalServerPort,
+};
+CONFIG.adapter.motd = {
+ l1: Enums.ChatColor.GOLD + "EaglerProxy as a Service",
+};
+
+if (config.allowDirectConnectEndpoints) {
+ PLUGIN_MANAGER.addListener("proxyFinishLoading", () => {
+ registerEndpoints();
+ if (config.allowDirectConnectEndpoints) {
+ PluginManager.proxy.config.motd = "REALTIME";
+ PluginManager.proxy.on("fetchMotd", (ws, req, result) => {
+ let url = new URL(req.url, "https://bogus.lol"),
+ ip = url.searchParams.get("ip"),
+ port = url.searchParams.get("port");
+ port = port || "25565";
+ if (!config.allowCustomPorts && port != "25565") return;
+ if (ip != null && !isNaN(Number(port))) {
+ // check if ip is public
+ result.motd = new Promise(async (res) => {
+ if (await isValidIp(ip)) {
+ res(await Motd.MOTD.generateMOTDFromPing(ip, Number(port), PluginManager.proxy.config.useNatives || true));
+ }
+ res(null);
+ });
+ }
+ });
+ }
+ });
+}
diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json b/eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json
new file mode 100644
index 0000000..2be802c
--- /dev/null
+++ b/eaglerproxy/files/src/plugins/EagProxyAAS/metadata.json
@@ -0,0 +1,34 @@
+{
+ "name": "EaglerProxy as a Service",
+ "id": "eagpaas",
+ "version": "2.0.0",
+ "entry_point": "index.js",
+ "requirements": [
+ {
+ "id": "eaglerproxy",
+ "version": "any"
+ },
+ {
+ "id": "module:vec3",
+ "version": "^0.1.0"
+ },
+ {
+ "id": "module:prismarine-chunk",
+ "version": "^1.33.0"
+ },
+ {
+ "id": "module:prismarine-block",
+ "version": "^1.16.0"
+ },
+ {
+ "id": "module:prismarine-registry",
+ "version": "^1.6.0"
+ },
+ {
+ "id": "module:minecraft-protocol",
+ "version": "^1.40.0"
+ }
+ ],
+ "load_after": [],
+ "incompatibilities": []
+}
diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts
new file mode 100644
index 0000000..2e8fcbe
--- /dev/null
+++ b/eaglerproxy/files/src/plugins/EagProxyAAS/service/endpoints.ts
@@ -0,0 +1,173 @@
+import { ServerDeviceCodeResponse, auth } from "../auth.js";
+import { config } from "../config.js";
+
+const LINK_STR = `
+
+
+
+ EagPAAS - Connect
+
+
+
+
+ EagPAAS - Connect to Server
+
+ Hello there! To connect to this Minecraft server through a server list entry,
+ use this URL: (connect from any recent
+ EaglercraftX client via Multiplayer > Direct Connect)
+
loading...
+
+ If your Eaglercraft client supports vanilla:// URLs, this will also work:
+
loading...
+
+ Note that your session will eventually expire, and you will need to log back in again.
+
+
+
+
+`;
+
+export async function registerEndpoints() {
+ const proxy = PLUGIN_MANAGER.proxy;
+ proxy.on("httpConnection", (req, res, ctx) => {
+ if (req.url.startsWith("/eagpaas/link")) {
+ ctx.handled = true;
+ res.setHeader("Content-Type", "text/html").writeHead(200).end(LINK_STR);
+ } else if (req.url.startsWith("/eagpaas/metadata")) {
+ ctx.handled = true;
+ res.writeHead(200).end(
+ JSON.stringify({
+ branding: "EagProxyAAS",
+ version: "1",
+ })
+ );
+ } else if (req.url.startsWith("/eagpaas/validate")) {
+ ctx.handled = true;
+ if (config.authentication.enabled) {
+ if (req.headers["authorization"] !== `Basic ${config.authentication.password}`) {
+ return res.writeHead(403).end(
+ JSON.stringify({
+ success: false,
+ reason: "Access Denied",
+ })
+ );
+ }
+ }
+ res.writeHead(200).end(
+ JSON.stringify({
+ success: true,
+ })
+ );
+ }
+ });
+
+ proxy.on("wsConnection", (ws, req, ctx) => {
+ try {
+ if (req.url.startsWith("/eagpaas/token")) {
+ ctx.handled = true;
+ if (config.authentication.enabled) {
+ if (req.headers.authorization !== `Basic ${config.authentication.password}`) {
+ ws.send(
+ JSON.stringify({
+ type: "ERROR",
+ error: "Access Denied",
+ })
+ );
+ ws.close();
+ return;
+ }
+ }
+
+ const quit = { quit: false },
+ authHandler = auth(quit),
+ codeCallback = (code: ServerDeviceCodeResponse) => {
+ ws.send(
+ JSON.stringify({
+ type: "CODE",
+ data: code,
+ })
+ );
+ };
+ ws.once("close", () => {
+ quit.quit = true;
+ });
+ authHandler
+ .on("code", codeCallback)
+ .on("error", (err) => {
+ ws.send(
+ JSON.stringify({
+ type: "ERROR",
+ reason: err,
+ })
+ );
+ ws.close();
+ })
+ .on("done", (result) => {
+ ws.send(
+ JSON.stringify({
+ type: "COMPLETE",
+ data: result,
+ })
+ );
+ ws.close();
+ });
+ } else if (req.url.startsWith("/eagpaas/ping")) {
+ ctx.handled = true;
+ if (config.authentication.enabled) {
+ if (req.headers.authorization !== `Basic ${config.authentication.password}`) {
+ ws.send(
+ JSON.stringify({
+ type: "ERROR",
+ error: "Access Denied",
+ })
+ );
+ ws.close();
+ return;
+ }
+ }
+
+ ws.once("message", (_) => {
+ ws.send(_);
+ ws.close();
+ });
+ }
+ } catch (err) {}
+ });
+}
diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/types.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/types.ts
new file mode 100644
index 0000000..10e952d
--- /dev/null
+++ b/eaglerproxy/files/src/plugins/EagProxyAAS/types.ts
@@ -0,0 +1,51 @@
+import { Client, Server } from "minecraft-protocol";
+
+export type ServerGlobals = {
+ server: Server;
+ players: Map;
+};
+
+export type ClientState = {
+ state: ConnectionState;
+ gameClient: Client;
+ token?: string;
+ lastStatusUpdate: number;
+};
+
+export enum ConnectionState {
+ AUTH,
+ SUCCESS,
+ DISCONNECTED,
+}
+
+export enum ChatColor {
+ BLACK = "§0",
+ DARK_BLUE = "§1",
+ DARK_GREEN = "§2",
+ DARK_CYAN = "§3",
+ DARK_RED = "§4",
+ PURPLE = "§5",
+ GOLD = "§6",
+ GRAY = "§7",
+ DARK_GRAY = "§8",
+ BLUE = "§9",
+ BRIGHT_GREEN = "§a",
+ CYAN = "§b",
+ RED = "§c",
+ PINK = "§d",
+ YELLOW = "§e",
+ WHITE = "§f",
+ // text styling
+ OBFUSCATED = "§k",
+ BOLD = "§l",
+ STRIKETHROUGH = "§m",
+ UNDERLINED = "§n",
+ ITALIC = "§o",
+ RESET = "§r",
+}
+
+export enum ConnectType {
+ ONLINE = "ONLINE",
+ OFFLINE = "OFFLINE",
+ THEALTENING = "THEALTENING",
+}
diff --git a/eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts b/eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts
new file mode 100644
index 0000000..7cee224
--- /dev/null
+++ b/eaglerproxy/files/src/plugins/EagProxyAAS/utils.ts
@@ -0,0 +1,1021 @@
+import { ConnectType, ServerGlobals } from "./types.js";
+import * as Chunk from "prismarine-chunk";
+import * as Block from "prismarine-block";
+import * as Registry from "prismarine-registry";
+import vec3 from "vec3";
+import { Client } from "minecraft-protocol";
+import { ClientState, ConnectionState } from "./types.js";
+import { auth, ServerDeviceCodeResponse } from "./auth.js";
+import { config } from "./config.js";
+import { handleCommand } from "./commands.js";
+import { getTokenProfileTheAltening } from "./auth_thealtening.js";
+import { resolve4, resolveSrv } from "dns/promises";
+
+const { Vec3 } = vec3 as any;
+const Enums = PLUGIN_MANAGER.Enums;
+const Util = PLUGIN_MANAGER.Util;
+const MAX_LIFETIME_CONNECTED = 10 * 60 * 1000,
+ MAX_LIFETIME_AUTH = 5 * 60 * 1000,
+ MAX_LIFETIME_LOGIN = 1 * 60 * 1000;
+const REGISTRY = Registry.default("1.8"),
+ McBlock = (Block as any).default("1.8"),
+ LOGIN_CHUNK = generateSpawnChunk().dump();
+const logger = new PLUGIN_MANAGER.Logger("PlayerHandler");
+
+let SERVER: ServerGlobals = null;
+
+export function hushConsole() {
+ const ignoredMethod = () => {};
+ global.console.info = ignoredMethod;
+ global.console.warn = ignoredMethod;
+ global.console.error = ignoredMethod;
+ global.console.debug = ignoredMethod;
+}
+
+export async function isValidIp(ip: string): Promise {
+ const hostPart = ip.split(":")[0];
+ const ipFormat = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
+ const match = hostPart.match(ipFormat);
+
+ if (match) {
+ const octets = match.slice(1).map(Number);
+ if (octets.some((octet) => isNaN(octet) || octet < 0 || octet > 255)) return false;
+
+ const [a, b, c, d] = octets;
+ if (
+ a === 10 ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 169 && b === 254) ||
+ a === 127 ||
+ a === 0 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 192 && b === 0 && c === 0) ||
+ (a === 192 && b === 0 && c === 2) ||
+ (a === 198 && b === 51 && c === 100) ||
+ (a === 203 && b === 0 && c === 113) ||
+ a >= 224 ||
+ (a === 192 && b === 88 && c === 99) ||
+ (a === 198 && b >= 18 && b <= 19) ||
+ (a === 192 && b === 52 && c === 193)
+ )
+ return false;
+
+ return true;
+ }
+
+ const hostnameRegex = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
+ if (!hostnameRegex.test(hostPart)) return false;
+
+ const lowerHost = hostPart.toLowerCase();
+ if (
+ ["localhost", "local", "0.0.0.0", "127.0.0.1", "::1"].includes(lowerHost) ||
+ lowerHost.endsWith(".local") ||
+ lowerHost.endsWith(".localhost") ||
+ lowerHost.endsWith(".internal") ||
+ lowerHost.endsWith(".intranet") ||
+ lowerHost.endsWith(".localdomain") ||
+ lowerHost.endsWith(".lan")
+ )
+ return false;
+
+ try {
+ if (lowerHost.startsWith("_minecraft._tcp.")) {
+ const srvRecords = await resolveSrv(hostPart);
+ return srvRecords && srvRecords.length > 0;
+ }
+
+ const addresses = await resolve4(hostPart);
+ if (addresses && addresses.length > 0) {
+ return addresses.some((addr) => {
+ const ipMatch = addr.match(ipFormat);
+ if (ipMatch) {
+ const [a, b, c, d] = ipMatch.slice(1).map(Number);
+ return !(a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || a === 127 || a === 0);
+ }
+ return false;
+ });
+ }
+ } catch (e) {
+ if (!lowerHost.startsWith("_minecraft._tcp.")) {
+ try {
+ const srvRecords = await resolveSrv(`_minecraft._tcp.${hostPart}`);
+ return srvRecords && srvRecords.length > 0;
+ } catch (e) {
+ return false;
+ }
+ }
+ return false;
+ }
+
+ return true;
+}
+
+function validateSessionObject(session: any) {
+ if (typeof session !== "object" || session === null) return false;
+
+ const hasValidAuth = typeof session.auth === "string";
+ const hasValidUsername = typeof session.username === "string";
+ const hasValidExpiresOn = typeof session.expires_on === "number" || session.expires_on instanceof Date;
+
+ if (!hasValidAuth || !hasValidUsername || !hasValidExpiresOn) return false;
+
+ if (typeof session.session !== "object" || session.session === null) return false;
+
+ const { session: sessionData } = session;
+
+ const hasValidAccessToken = typeof sessionData.accessToken === "string";
+ const hasValidClientToken = typeof sessionData.clientToken === "string";
+
+ if (!hasValidAccessToken || !hasValidClientToken) return false;
+
+ if (typeof sessionData.selectedProfile !== "object" || sessionData.selectedProfile === null) return false;
+
+ const hasValidProfileId = typeof sessionData.selectedProfile.id === "string";
+ const hasValidProfileName = typeof sessionData.selectedProfile.name === "string";
+
+ if (!hasValidProfileId || !hasValidProfileName) return false;
+
+ // Ensure no extra properties exist
+ const validSessionKeys = ["auth", "username", "expires_on", "session"];
+ const validSessionDataKeys = ["accessToken", "clientToken", "selectedProfile"];
+ const validSelectedProfileKeys = ["id", "name"];
+
+ if (Object.keys(session).some((key) => !validSessionKeys.includes(key))) return false;
+ if (Object.keys(sessionData).some((key) => !validSessionDataKeys.includes(key))) return false;
+ if (Object.keys(sessionData.selectedProfile).some((key) => !validSelectedProfileKeys.includes(key))) return false;
+
+ return true;
+}
+
+export function setSG(svr: ServerGlobals) {
+ SERVER = svr;
+}
+
+export function disconectIdle() {
+ SERVER.players.forEach((client) => {
+ if (client.state == ConnectionState.AUTH && Date.now() - client.lastStatusUpdate > MAX_LIFETIME_AUTH) {
+ client.gameClient.end("Timed out waiting for user to login via Microsoft!");
+ } else if (client.state == ConnectionState.SUCCESS && Date.now() - client.lastStatusUpdate > MAX_LIFETIME_CONNECTED) {
+ client.gameClient.end(Enums.ChatColor.RED + "Please enter the IP of the server you'd like to connect to in chat.");
+ }
+ });
+}
+
+export function handleConnect(client: ClientState, additionalParams: { ip: string; port: number; mode: ConnectType; session: any }) {
+ client.gameClient.write("login", {
+ entityId: 1,
+ gameMode: 2,
+ dimension: 1,
+ difficulty: 1,
+ maxPlayers: 1,
+ levelType: "flat",
+ reducedDebugInfo: false,
+ });
+ client.gameClient.write("map_chunk", {
+ x: 0,
+ z: 0,
+ groundUp: true,
+ bitMap: 0xffff,
+ chunkData: LOGIN_CHUNK,
+ });
+ client.gameClient.write("position", {
+ x: 0,
+ y: 65,
+ z: 8.5,
+ yaw: -90,
+ pitch: 0,
+ flags: 0x01,
+ });
+
+ client.gameClient.write("playerlist_header", {
+ header: JSON.stringify({
+ text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `,
+ }),
+ footer: JSON.stringify({
+ text: `${Enums.ChatColor.GOLD}Please wait for instructions.`,
+ }),
+ });
+
+ if (additionalParams != null && additionalParams.ip != null && additionalParams.port != null) {
+ sendMessage(client.gameClient, `${Enums.ChatColor.GREEN}Automatically connecting to server ${Enums.ChatColor.GOLD}${additionalParams.ip}:${additionalParams.port}${Enums.ChatColor.GREEN}.`);
+ }
+ if (additionalParams && additionalParams.session && additionalParams.session.expires_on - Date.now() > 24 * 60 * 60 * 1000) {
+ sendMessage(
+ client.gameClient,
+ `${Enums.ChatColor.RED}Your session token is valid for ${Math.floor((additionalParams.session.expires_on - Date.now()) / 1000 / 60)} more minutes, and will expire in less than 24 hours! Please obtain a new session URL.`
+ );
+ }
+ onConnect(client, additionalParams);
+}
+
+export function awaitCommand(client: Client, filter: (msg: string) => boolean): Promise {
+ return new Promise((res, rej) => {
+ const onMsg = (packet) => {
+ if (filter(packet.message)) {
+ client.removeListener("chat", onMsg);
+ client.removeListener("end", onEnd);
+ res(packet.message);
+ }
+ };
+ const onEnd = () => rej("Client disconnected before promise could be resolved");
+ client.on("chat", onMsg);
+ client.on("end", onEnd);
+ });
+}
+
+export function sendMessage(client: Client, msg: string) {
+ client.write("chat", {
+ message: JSON.stringify({ text: msg }),
+ position: 1,
+ });
+}
+
+export function sendCustomMessage(client: Client, msg: string, color: string, ...components: { text: string; color: string }[]) {
+ client.write("chat", {
+ message: JSON.stringify(
+ components.length > 0
+ ? {
+ text: msg,
+ color,
+ extra: components,
+ }
+ : { text: msg, color }
+ ),
+ position: 1,
+ });
+}
+
+export function sendChatComponent(client: Client, component: any) {
+ client.write("chat", {
+ message: JSON.stringify(component),
+ position: 1,
+ });
+}
+
+export function sendMessageWarning(client: Client, msg: string) {
+ client.write("chat", {
+ message: JSON.stringify({
+ text: msg,
+ color: "yellow",
+ }),
+ position: 1,
+ });
+}
+
+export function sendMessageLogin(client: Client, url: string, token: string) {
+ client.write("chat", {
+ message: JSON.stringify({
+ text: "Please open ",
+ color: Enums.ChatColor.RESET,
+ extra: [
+ {
+ text: "this link",
+ color: "gold",
+ clickEvent: {
+ action: "open_url",
+ value: `${url}/?otc=${token}`,
+ },
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click to open me in a new window!",
+ },
+ },
+ {
+ text: " to authenticate via Microsoft.",
+ },
+ ],
+ }),
+ position: 1,
+ });
+}
+
+export function updateState(client: Client, newState: "CONNECTION_TYPE" | "AUTH_THEALTENING" | "AUTH" | "SERVER", uri?: string, code?: string) {
+ switch (newState) {
+ case "CONNECTION_TYPE":
+ client.write("playerlist_header", {
+ header: JSON.stringify({
+ text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `,
+ }),
+ footer: JSON.stringify({
+ text: `${Enums.ChatColor.RED}Choose the connection type: 1 = online, 2 = offline, 3 = TheAltening.`,
+ }),
+ });
+ break;
+ case "AUTH_THEALTENING":
+ client.write("playerlist_header", {
+ header: JSON.stringify({
+ text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `,
+ }),
+ footer: JSON.stringify({
+ text: `${Enums.ChatColor.RED}panel.thealtening.com/#generator${Enums.ChatColor.GOLD} | ${Enums.ChatColor.RED}/login `,
+ }),
+ });
+ break;
+ case "AUTH":
+ if (code == null || uri == null) throw new Error("Missing code/uri required for title message type AUTH");
+ client.write("playerlist_header", {
+ header: JSON.stringify({
+ text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `,
+ }),
+ footer: JSON.stringify({
+ text: `${Enums.ChatColor.RED}${uri}${Enums.ChatColor.GOLD} | Code: ${Enums.ChatColor.RED}${code}`,
+ }),
+ });
+ break;
+ case "SERVER":
+ client.write("playerlist_header", {
+ header: JSON.stringify({
+ text: ` ${Enums.ChatColor.GOLD}EaglerProxy Authentication Server `,
+ }),
+ footer: JSON.stringify({
+ text: `${Enums.ChatColor.RED}/join ${config.allowCustomPorts ? " [port]" : ""}`,
+ }),
+ });
+ break;
+ }
+}
+
+export function printSessionMessage(client: ClientState, session: any, proxySession = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username)) {
+ const stringifiedSession = JSON.stringify(session),
+ url = new URL(proxySession.ws.httpRequest.url, "wss://" + proxySession.ws.httpRequest.headers.host);
+ url.searchParams.set("session", stringifiedSession);
+ url.protocol = "wss:";
+ const secureURL = new URL("/eagpaas/link", "http://" + proxySession.ws.httpRequest.headers.host);
+ secureURL.searchParams.set("url", url.toString());
+ const http = secureURL.toString();
+ secureURL.protocol = "https:";
+ const https = secureURL.toString();
+
+ sendChatComponent(client.gameClient, {
+ text: "Logged in! Use this server URL to continue using this account (open the link; try each one): ",
+ color: "green",
+ extra: [
+ {
+ text: "[https]",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click to copy!",
+ },
+ clickEvent: {
+ action: "open_url",
+ value: https,
+ },
+ },
+ { text: " ", color: "green" },
+ {
+ text: "[http]",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click to copy!",
+ },
+ clickEvent: {
+ action: "open_url",
+ value: http,
+ },
+ },
+ ],
+ });
+ sendChatComponent(client.gameClient, {
+ text: "Revealing/showing the URL to others (including the underling server URL) can potentially allow others to compromise your account.\n" + "Do not click or open any of the above links if others can observe you.",
+ color: "red",
+ });
+}
+
+// assuming that the player will always stay at the same pos
+export function playSelectSound(client: Client) {
+ client.write("named_sound_effect", {
+ soundName: "note.hat",
+ x: 8.5,
+ y: 65,
+ z: 8.5,
+ volume: 100,
+ pitch: 63,
+ });
+}
+
+export async function onConnect(client: ClientState, metadata?: { ip: string; port: number; mode?: ConnectType; session?: object }) {
+ try {
+ client.state = ConnectionState.AUTH;
+ client.lastStatusUpdate = Date.now();
+
+ client.gameClient.on("packet", (packet, meta) => {
+ if (meta.name == "client_command" && packet.payload == 1) {
+ client.gameClient.write("statistics", {
+ entries: [],
+ });
+ }
+ });
+
+ if (config.showDisclaimers) {
+ sendMessageWarning(client.gameClient, `WARNING: This proxy allows you to connect to any 1.8.9 server. Gameplay has shown no major issues, but please note that EaglercraftX may flag some anticheats while playing.`);
+ await new Promise((res) => setTimeout(res, 2000));
+
+ sendMessageWarning(
+ client.gameClient,
+ `ADVISORY FOR HYPIXEL PLAYERS: THIS PROXY FALLS UNDER HYPIXEL'S "DISALLOWED MODIFICATIONS" MOD CATEGORY. JOINING THE SERVER WILL RESULT IN AN IRREPEALABLE PUNISHMENT BEING APPLIED TO YOUR ACCOUNT. YOU HAVE BEEN WARNED - PLAY AT YOUR OWN RISK!`
+ );
+ await new Promise((res) => setTimeout(res, 2000));
+ }
+
+ if (config.authentication.enabled) {
+ sendCustomMessage(client.gameClient, "This instance is password-protected. Sign in with /password ", "gold");
+ const password = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/password "));
+ if (password === `/password ${config.authentication.password}`) {
+ sendCustomMessage(client.gameClient, "Successfully signed into instance!", "green");
+ } else {
+ client.gameClient.end(Enums.ChatColor.RED + "Bad password!");
+ return;
+ }
+ }
+
+ let chosenOption: ConnectType | null = null;
+ if (!metadata || metadata.mode == null) {
+ sendCustomMessage(client.gameClient, "What would you like to do?", "gray");
+ sendChatComponent(client.gameClient, {
+ text: "1) ",
+ color: "gold",
+ extra: [
+ {
+ text: "Connect to an online server (Minecraft account needed)",
+ color: "white",
+ },
+ ],
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to select!",
+ },
+
+ clickEvent: {
+ action: "run_command",
+ value: "$1",
+ },
+ });
+ sendChatComponent(client.gameClient, {
+ text: "2) ",
+ color: "gold",
+ extra: [
+ {
+ text: "Connect to an offline server (no Minecraft account needed)",
+ color: "white",
+ },
+ ],
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to select!",
+ },
+ clickEvent: {
+ action: "run_command",
+ value: "$2",
+ },
+ });
+ sendChatComponent(client.gameClient, {
+ text: "3) ",
+ color: "gold",
+ extra: [
+ {
+ text: "Connect to an online server via TheAltening account pool (no Minecraft account needed)",
+ color: "white",
+ },
+ ],
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to select!",
+ },
+ clickEvent: {
+ action: "run_command",
+ value: "$3",
+ },
+ });
+ sendCustomMessage(client.gameClient, "Select an option from the above (1 = online, 2 = offline, 3 = TheAltening), either by clicking or manually typing out the option's number on the list.", "green");
+ updateState(client.gameClient, "CONNECTION_TYPE");
+
+ while (true) {
+ const option = await awaitCommand(client.gameClient, (msg) => true);
+ switch (option.replace(/\$/gim, "")) {
+ default:
+ sendCustomMessage(client.gameClient, `I don't understand what you meant by "${option}", please reply with a valid option!`, "red");
+ break;
+ case "1":
+ chosenOption = ConnectType.ONLINE;
+ break;
+ case "2":
+ chosenOption = ConnectType.OFFLINE;
+ break;
+ case "3":
+ chosenOption = ConnectType.THEALTENING;
+ break;
+ }
+ if (chosenOption != null) {
+ if (option.startsWith("$")) playSelectSound(client.gameClient);
+ break;
+ }
+ }
+ } else chosenOption = metadata.mode;
+
+ if (chosenOption == ConnectType.ONLINE) {
+ if (!metadata || !metadata.session) {
+ if (config.showDisclaimers) {
+ sendMessageWarning(
+ client.gameClient,
+ `WARNING: You will be prompted to log in via Microsoft to obtain a session token necessary to join games. Any data related to your account will not be saved and for transparency reasons this proxy's source code is available on Github.`
+ );
+ }
+ await new Promise((res) => setTimeout(res, 2000));
+ }
+
+ client.lastStatusUpdate = Date.now();
+ let errored = false,
+ savedAuth;
+ if (!metadata || !metadata.session) {
+ const quit = { quit: false },
+ authHandler = auth(quit),
+ codeCallback = (code: ServerDeviceCodeResponse) => {
+ updateState(client.gameClient, "AUTH", code.verification_uri, code.user_code);
+ sendMessageLogin(client.gameClient, code.verification_uri, code.user_code);
+ };
+ client.gameClient.once("end", (res) => {
+ quit.quit = true;
+ });
+
+ authHandler.once("error", (err) => {
+ if (!client.gameClient.ended) client.gameClient.end(err.message);
+ errored = true;
+ });
+ if (errored) return;
+ authHandler.on("code", codeCallback);
+ await new Promise((res) =>
+ authHandler.once("done", (result) => {
+ savedAuth = result;
+ res(result);
+ })
+ );
+ sendMessage(client.gameClient, Enums.ChatColor.BRIGHT_GREEN + "Successfully logged into Minecraft!");
+ }
+
+ client.state = ConnectionState.SUCCESS;
+ client.lastStatusUpdate = Date.now();
+ let host: string, port: number;
+ if (metadata && metadata.ip != null && metadata.port != null) {
+ host = metadata.ip;
+ port = metadata.port;
+ } else {
+ updateState(client.gameClient, "SERVER");
+ sendMessage(client.gameClient, `Provide a server to join. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ while (true) {
+ const msg = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/join")),
+ parsed = msg.split(/ /gi, 3);
+ if (parsed.length < 2) sendMessage(client.gameClient, `Please provide a server to connect to. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ else if (parsed.length > 2 && isNaN(parseInt(parsed[2])))
+ sendMessage(client.gameClient, `A valid port number has to be passed! ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ else {
+ host = parsed[1];
+ if (parsed.length > 2) port = parseInt(parsed[2]);
+ if (port != null && !config.allowCustomPorts) {
+ sendCustomMessage(client.gameClient, "You are not allowed to use custom server ports! /join " + (config.allowCustomPorts ? " [port]" : ""), "red");
+ host = null;
+ port = null;
+ } else {
+ if (host.match(/^(?:\*\.)?((?!hypixel\.net$)[^.]+\.)*hypixel\.net$/) && config.disallowHypixel) {
+ sendCustomMessage(
+ client.gameClient,
+ "Disallowed server, refusing to connect! Hypixel has been known to falsely flag Eaglercraft clients, and thus we do not allow connecting to their server. /join " + (config.allowCustomPorts ? " [port]" : ""),
+ "red"
+ );
+ } else if (!(await isValidIp(host))) {
+ sendCustomMessage(client.gameClient, "Invalid server address! /join " + (config.allowCustomPorts ? " [port]" : ""), "red");
+ host = null;
+ port = null;
+ } else {
+ port = port ?? 25565;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ validateSessionObject(savedAuth);
+ const session = (metadata ? metadata.session : undefined) || {
+ auth: "mojang",
+ username: savedAuth.selectedProfile.name,
+ expires_on: savedAuth.expiresOn,
+ session: {
+ accessToken: savedAuth.accessToken,
+ clientToken: savedAuth.selectedProfile.id,
+ selectedProfile: {
+ id: savedAuth.selectedProfile.id,
+ name: savedAuth.selectedProfile.name,
+ },
+ },
+ };
+ // printSessionMessage(client, session);
+
+ try {
+ sendChatComponent(client.gameClient, {
+ text: `Joining server under ${savedAuth.selectedProfile.name}/your Minecraft account's username! Run `,
+ color: "aqua",
+ extra: [
+ {
+ text: "/eag-help",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to run this command!",
+ },
+ clickEvent: {
+ action: "run_command",
+ value: "/eag-help",
+ },
+ },
+ {
+ text: " for a list of proxy commands.",
+ color: "aqua",
+ },
+ ],
+ });
+ logger.info(`Player ${client.gameClient.username} is attempting to connect to ${host}:${port} under their Minecraft account's username (${savedAuth.selectedProfile.name}) using online mode!`);
+ const player = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username);
+ player.on("vanillaPacket", (packet, origin) => {
+ if (origin == "CLIENT" && packet.name == "chat" && (packet.params.message as string).toLowerCase().startsWith("/eag-") && !packet.cancel) {
+ packet.cancel = true;
+ handleCommand(player, packet.params.message as string);
+ }
+ });
+
+ (player as any)._onlineSession = session;
+
+ await player.switchServers({
+ host: host,
+ port: port,
+ version: "1.8.8",
+ username: savedAuth.selectedProfile.name,
+ auth: "mojang",
+ keepAlive: false,
+ session: {
+ accessToken: savedAuth.accessToken,
+ clientToken: savedAuth.selectedProfile.id,
+ selectedProfile: {
+ id: savedAuth.selectedProfile.id,
+ name: savedAuth.selectedProfile.name,
+ },
+ },
+ skipValidation: true,
+ hideErrors: true,
+ });
+ } catch (err) {
+ if (!client.gameClient.ended) {
+ client.gameClient.end(
+ Enums.ChatColor.RED +
+ `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (host.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}`
+ );
+ }
+ }
+ } else if (chosenOption == ConnectType.THEALTENING) {
+ const THEALTENING_GET_TOKEN_URL = "panel.thealtening.com/#generator";
+ client.state = ConnectionState.AUTH;
+ client.lastStatusUpdate = Date.now();
+ updateState(client.gameClient, "AUTH_THEALTENING");
+
+ if (config.showDisclaimers) {
+ sendMessageWarning(client.gameClient, `WARNING: You've chosen to use an account from TheAltening's account pool. Please note that accounts and shared, and may be banned from whatever server you are attempting to join.`);
+ }
+ sendChatComponent(client.gameClient, {
+ text: "Please log in and generate an alt token at ",
+ color: "white",
+ extra: [
+ {
+ text: THEALTENING_GET_TOKEN_URL,
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to open in a new window!",
+ },
+ clickEvent: {
+ action: "open_url",
+ value: `https://${THEALTENING_GET_TOKEN_URL}`,
+ },
+ },
+ {
+ text: ", and then run ",
+ color: "white",
+ },
+ {
+ text: "/login ",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Copy me to chat!",
+ },
+ clickEvent: {
+ action: "suggest_command",
+ value: `/login `,
+ },
+ },
+ {
+ text: " to log in.",
+ color: "white",
+ },
+ ],
+ });
+
+ let appendOptions: any;
+ while (true) {
+ const tokenResponse = await awaitCommand(client.gameClient, (msg) => msg.toLowerCase().startsWith("/login")),
+ splitResponse = tokenResponse.split(/ /gim, 2).slice(1);
+ if (splitResponse.length != 1) {
+ sendChatComponent(client.gameClient, {
+ text: "Invalid usage! Please use the command as follows: ",
+ color: "red",
+ extra: [
+ {
+ text: "/login ",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Copy me to chat!",
+ },
+ clickEvent: {
+ action: "suggest_command",
+ value: `/login `,
+ },
+ },
+ {
+ text: ".",
+ color: "red",
+ },
+ ],
+ });
+ } else {
+ const token = splitResponse[0];
+ if (!token.endsWith("@alt.com")) {
+ sendChatComponent(client.gameClient, {
+ text: "Please provide a valid token (you can get one ",
+ color: "red",
+ extra: [
+ {
+ text: "here",
+ color: "white",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to open in a new window!",
+ },
+ clickEvent: {
+ action: "open_url",
+ value: `https://${THEALTENING_GET_TOKEN_URL}`,
+ },
+ },
+ {
+ text: "). ",
+ color: "red",
+ },
+ {
+ text: "/login ",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Copy me to chat!",
+ },
+ clickEvent: {
+ action: "suggest_command",
+ value: `/login `,
+ },
+ },
+ {
+ text: ".",
+ color: "red",
+ },
+ ],
+ });
+ } else {
+ sendCustomMessage(client.gameClient, "Validating alt token...", "gray");
+ try {
+ appendOptions = await getTokenProfileTheAltening(token);
+ sendCustomMessage(client.gameClient, `Successfully validated your alt token and retrieved your session profile! You'll be joining to your preferred server as ${appendOptions.username}.`, "green");
+ break;
+ } catch (err) {
+ sendChatComponent(client.gameClient, {
+ text: `TheAltening's servers replied with an error (${err.message}), please try again! `,
+ color: "red",
+ extra: [
+ {
+ text: "/login ",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Copy me to chat!",
+ },
+ clickEvent: {
+ action: "suggest_command",
+ value: `/login `,
+ },
+ },
+ {
+ text: ".",
+ color: "red",
+ },
+ ],
+ });
+ }
+ }
+ }
+ }
+
+ client.state = ConnectionState.SUCCESS;
+ client.lastStatusUpdate = Date.now();
+ let host: string, port: number;
+ if (metadata && metadata.ip != null && metadata.port != null) {
+ host = metadata.ip;
+ port = metadata.port;
+ } else {
+ updateState(client.gameClient, "SERVER");
+ sendMessage(client.gameClient, `Provide a server to join. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ while (true) {
+ const msg = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/join")),
+ parsed = msg.split(/ /gi, 3);
+ if (parsed.length < 2) sendMessage(client.gameClient, `Please provide a server to connect to. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ else if (parsed.length > 2 && isNaN(parseInt(parsed[2])))
+ sendMessage(client.gameClient, `A valid port number has to be passed! ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ else {
+ host = parsed[1];
+ if (parsed.length > 2) port = parseInt(parsed[2]);
+ if (port != null && !config.allowCustomPorts) {
+ sendCustomMessage(client.gameClient, "You are not allowed to use custom server ports! /join ", "red");
+ host = null;
+ port = null;
+ } else if (!(await isValidIp(host))) {
+ sendCustomMessage(client.gameClient, "Invalid server address! /join " + (config.allowCustomPorts ? " [port]" : ""), "red");
+ host = null;
+ port = null;
+ } else {
+ port = port ?? 25565;
+ break;
+ }
+ }
+ }
+ }
+ try {
+ sendChatComponent(client.gameClient, {
+ text: `Joining server under ${appendOptions.username}/TheAltening account username! Run `,
+ color: "aqua",
+ extra: [
+ {
+ text: "/eag-help",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to run this command!",
+ },
+ clickEvent: {
+ action: "run_command",
+ value: "/eag-help",
+ },
+ },
+ {
+ text: " for a list of proxy commands.",
+ color: "aqua",
+ },
+ ],
+ });
+ logger.info(`Player ${client.gameClient.username} is attempting to connect to ${host}:${port} under their TheAltening alt token's username (${appendOptions.username}) using TheAltening mode!`);
+ const player = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username);
+ player.on("vanillaPacket", (packet, origin) => {
+ if (origin == "CLIENT" && packet.name == "chat" && (packet.params.message as string).toLowerCase().startsWith("/eag-") && !packet.cancel) {
+ packet.cancel = true;
+ handleCommand(player, packet.params.message as string);
+ }
+ });
+ (player as any)._onlineSession = {
+ ...appendOptions,
+ isTheAltening: true,
+ };
+
+ await player.switchServers({
+ host: host,
+ port: port,
+ version: "1.8.8",
+ keepAlive: false,
+ skipValidation: true,
+ hideErrors: true,
+ ...appendOptions,
+ });
+ } catch (err) {
+ if (!client.gameClient.ended) {
+ client.gameClient.end(
+ Enums.ChatColor.RED +
+ `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (host.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}`
+ );
+ }
+ }
+ } else {
+ client.state = ConnectionState.SUCCESS;
+ client.lastStatusUpdate = Date.now();
+ let host: string, port: number;
+ if (metadata && metadata.ip != null && metadata.port != null) {
+ host = metadata.ip;
+ port = metadata.port;
+ } else {
+ updateState(client.gameClient, "SERVER");
+ sendMessage(client.gameClient, `Provide a server to join. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ while (true) {
+ const msg = await awaitCommand(client.gameClient, (msg) => msg.startsWith("/join")),
+ parsed = msg.split(/ /gi, 3);
+ if (parsed.length < 2) sendMessage(client.gameClient, `Please provide a server to connect to. ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ else if (parsed.length > 2 && isNaN(parseInt(parsed[2])))
+ sendMessage(client.gameClient, `A valid port number has to be passed! ${Enums.ChatColor.GOLD}/join ${config.allowCustomPorts ? " [port]" : ""}${Enums.ChatColor.RESET}.`);
+ else {
+ host = parsed[1];
+ if (parsed.length > 2) port = parseInt(parsed[2]);
+ if (port != null && !config.allowCustomPorts) {
+ sendCustomMessage(client.gameClient, "You are not allowed to use custom server ports! /join ", "red");
+ host = null;
+ port = null;
+ } else if (!(await isValidIp(host))) {
+ sendCustomMessage(client.gameClient, "Invalid server address! /join " + (config.allowCustomPorts ? " [port]" : ""), "red");
+ host = null;
+ port = null;
+ } else {
+ port = port ?? 25565;
+ break;
+ }
+ }
+ }
+ }
+ try {
+ sendChatComponent(client.gameClient, {
+ text: `Joining server under ${client.gameClient.username}/Eaglercraft username! Run `,
+ color: "aqua",
+ extra: [
+ {
+ text: "/eag-help",
+ color: "gold",
+ hoverEvent: {
+ action: "show_text",
+ value: Enums.ChatColor.GOLD + "Click me to run this command!",
+ },
+ clickEvent: {
+ action: "run_command",
+ value: "/eag-help",
+ },
+ },
+ {
+ text: " for a list of proxy commands.",
+ color: "aqua",
+ },
+ ],
+ });
+ logger.info(`Player ${client.gameClient.username} is attempting to connect to ${host}:${port} under their Eaglercraft username (${client.gameClient.username}) using offline mode!`);
+ const player = PLUGIN_MANAGER.proxy.players.get(client.gameClient.username);
+ player.on("vanillaPacket", (packet, origin) => {
+ if (origin == "CLIENT" && packet.name == "chat" && (packet.params.message as string).toLowerCase().startsWith("/eag-") && !packet.cancel) {
+ packet.cancel = true;
+ handleCommand(player, packet.params.message as string);
+ }
+ });
+
+ await player.switchServers({
+ host: host,
+ port: port,
+ auth: "offline",
+ username: client.gameClient.username,
+ version: "1.8.8",
+ keepAlive: false,
+ skipValidation: true,
+ hideErrors: true,
+ });
+ } catch (err) {
+ if (!client.gameClient.ended) {
+ client.gameClient.end(
+ Enums.ChatColor.RED +
+ `Something went wrong whilst switching servers: ${err.message}${err.code == "ENOTFOUND" ? (host.includes(":") ? `\n${Enums.ChatColor.GRAY}Suggestion: Replace the : in your IP with a space.` : "\nIs that IP valid?") : ""}`
+ );
+ }
+ }
+ }
+ } catch (err) {
+ if (!client.gameClient.ended) {
+ logger.error(`Error whilst processing user ${client.gameClient.username}: ${err.stack || err}`);
+ client.gameClient.end(Enums.ChatColor.YELLOW + "Something went wrong whilst processing your request. Please reconnect.");
+ }
+ }
+}
+
+export function generateSpawnChunk(): Chunk.PCChunk {
+ const chunk = new (Chunk.default(REGISTRY))(null) as Chunk.PCChunk;
+ chunk.initialize(() => new McBlock(REGISTRY.blocksByName.air.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(8, 64, 8), new McBlock(REGISTRY.blocksByName.sea_lantern.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(8, 67, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(7, 65, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(7, 66, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(9, 65, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(9, 66, 8), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(8, 65, 7), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(8, 66, 7), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(8, 65, 9), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ chunk.setBlock(new Vec3(8, 66, 9), new McBlock(REGISTRY.blocksByName.barrier.id, REGISTRY.biomesByName.the_end.id, 0));
+ // chunk.setBlockLight(new Vec3(8, 65, 8), 15);
+ chunk.setBlockLight(new Vec3(8, 66, 8), 15);
+ return chunk;
+}
diff --git a/eaglerproxy/files/src/proxy/BungeeUtil.ts b/eaglerproxy/files/src/proxy/BungeeUtil.ts
new file mode 100644
index 0000000..06303a3
--- /dev/null
+++ b/eaglerproxy/files/src/proxy/BungeeUtil.ts
@@ -0,0 +1,101 @@
+import { Logger } from "../logger.js";
+import mcp, { states } from "minecraft-protocol";
+
+const { createSerializer, createDeserializer } = mcp;
+
+export namespace BungeeUtil {
+ export class PacketUUIDTranslator {
+ public serverSidePlayerUUID: string;
+ public clientSidePlayerUUID: string;
+
+ static readonly CAST_UUID_SERVER: string[] = [
+ "update_attributes",
+ "named_entity_spawn",
+ // drop this packet (twitch.tv integration not available anymore)
+ "player_info",
+ ];
+ static readonly CAST_UUID_CLIENT: string[] = ["spectate"];
+
+ private _logger: Logger;
+
+ constructor(ssPlayerUUID: string, csPlayerUUID: string) {
+ this.serverSidePlayerUUID = ssPlayerUUID;
+ this.clientSidePlayerUUID = csPlayerUUID;
+ this._logger = new Logger("PacketTranslator");
+ }
+
+ public translatePacketClient(packet: any, meta: any): [string, object] {
+ if (meta.name == "spectate") {
+ if (packet.target == this.clientSidePlayerUUID) {
+ packet.target = this.serverSidePlayerUUID;
+ } else if (packet.target == this.serverSidePlayerUUID) {
+ packet.target = this.clientSidePlayerUUID;
+ }
+ }
+ return [meta.name, packet];
+ }
+
+ public translatePacketServer(packet: any, meta: any): [string, object] {
+ if (meta.name == "update_attributes") {
+ for (const prop of packet.properties) {
+ for (const modifier of prop.modifiers) {
+ if (modifier.uuid == this.serverSidePlayerUUID) {
+ modifier.uuid = this.clientSidePlayerUUID;
+ } else if (modifier.uuid == this.clientSidePlayerUUID) {
+ modifier.uuid = this.serverSidePlayerUUID;
+ }
+ }
+ }
+ } else if (meta.name == "named_entity_spawn") {
+ if (packet.playerUUID == this.serverSidePlayerUUID) {
+ packet.playerUUID = this.clientSidePlayerUUID;
+ } else if (packet.playerUUID == this.clientSidePlayerUUID) {
+ packet.playerUUID = this.serverSidePlayerUUID;
+ }
+ } else if (meta.name == "player_info") {
+ for (const player of packet.data) {
+ if (player.UUID == this.serverSidePlayerUUID) {
+ player.UUID = this.clientSidePlayerUUID;
+ } else if (player.UUID == this.clientSidePlayerUUID) {
+ player.UUID = this.serverSidePlayerUUID;
+ }
+ }
+ }
+ return [meta.name, packet];
+ }
+ }
+
+ export function getRespawnSequence(
+ login: any,
+ serializer: any
+ ): [Buffer, Buffer] {
+ const dimset = getDimSets(login.dimension);
+ return [
+ serializer.createPacketBuffer({
+ name: "respawn",
+ params: {
+ dimension: dimset[0],
+ difficulty: login.difficulty,
+ gamemode: login.gameMode,
+ levelType: login.levelType,
+ },
+ }),
+ serializer.createPacketBuffer({
+ name: "respawn",
+ params: {
+ dimension: dimset[1],
+ difficulty: login.difficulty,
+ gamemode: login.gameMode,
+ levelType: login.levelType,
+ },
+ }),
+ ];
+ }
+
+ function getDimSets(loginDim: number): [number, number] {
+ return [
+ loginDim == -1 ? 0 : loginDim == 0 ? -1 : loginDim == 1 ? 0 : 0,
+ loginDim,
+ ];
+ }
+}
diff --git a/eaglerproxy/files/src/proxy/Chat.ts b/eaglerproxy/files/src/proxy/Chat.ts
new file mode 100644
index 0000000..1c333ec
--- /dev/null
+++ b/eaglerproxy/files/src/proxy/Chat.ts
@@ -0,0 +1,57 @@
+import { Enums } from "./Enums.js";
+
+export namespace Chat {
+ export type ChatExtra = {
+ text: string;
+ bold?: boolean;
+ italic?: boolean;
+ underlined?: boolean;
+ strikethrough?: boolean;
+ obfuscated?: boolean;
+ color?: Enums.ChatColor | "reset";
+ };
+
+ export type Chat = {
+ text?: string;
+ bold?: boolean;
+ italic?: boolean;
+ underlined?: boolean;
+ strikethrough?: boolean;
+ obfuscated?: boolean;
+ color?: Enums.ChatColor | "reset";
+ extra?: ChatExtra[];
+ };
+
+ export function chatToPlainString(chat: Chat): string {
+ let ret = "";
+ if (chat.text != null) ret += chat.text;
+ if (chat.extra != null) {
+ chat.extra.forEach((extra) => {
+ let append = "";
+ if (extra.bold) append += Enums.ChatColor.BOLD;
+ if (extra.italic) append += Enums.ChatColor.ITALIC;
+ if (extra.underlined) append += Enums.ChatColor.UNDERLINED;
+ if (extra.strikethrough) append += Enums.ChatColor.STRIKETHROUGH;
+ if (extra.obfuscated) append += Enums.ChatColor.OBFUSCATED;
+ if (extra.color)
+ append +=
+ extra.color == "reset"
+ ? Enums.ChatColor.RESET
+ : resolveColor(extra.color);
+ append += extra.text;
+ ret += append;
+ });
+ }
+ return ret;
+ }
+
+ const ccValues = Object.values(Enums.ChatColor);
+ const ccKeys = Object.keys(Enums.ChatColor).map((str) => str.toLowerCase());
+
+ function resolveColor(colorStr: string) {
+ return (
+ Object.values(Enums.ChatColor)[ccKeys.indexOf(colorStr.toLowerCase())] ??
+ colorStr
+ );
+ }
+}
diff --git a/eaglerproxy/files/src/proxy/Constants.ts b/eaglerproxy/files/src/proxy/Constants.ts
new file mode 100644
index 0000000..4859663
--- /dev/null
+++ b/eaglerproxy/files/src/proxy/Constants.ts
@@ -0,0 +1,17 @@
+import * as meta from "../meta.js";
+
+export namespace Constants {
+ export const EAGLERCRAFT_SKIN_CHANNEL_NAME: string = "EAG|Skins-1.8";
+ export const MAGIC_ENDING_SERVER_SKIN_DOWNLOAD_BUILTIN: number[] = [0x00, 0x00, 0x00];
+ export const MAGIC_ENDING_CLIENT_UPLOAD_SKIN_BUILTIN: number[] = [0x00, 0x05, 0x01, 0x00, 0x00, 0x00];
+ export const EAGLERCRAFT_SKIN_CUSTOM_LENGTH = 64 ** 2 * 4;
+
+ export const JOIN_SERVER_PACKET = 0x01;
+ export const PLAYER_LOOK_PACKET = 0x08;
+
+ export const ICON_SQRT = 64;
+ export const END_BUFFER_LENGTH = ICON_SQRT ** 8;
+ export const IMAGE_DATA_PREPEND = "data:image/png;base64,";
+}
+
+export const UPGRADE_REQUIRED_RESPONSE = ` EaglerProxy landing page 426 - Upgrade Required
Hello there! It appears as if you've reached the landing page for this EaglerProxy instance. Unfortunately, you cannot connect to the proxy server from here. To connect, use this server IP/URL: loading... (connect from any recent EaglercraftX client via Multiplayer > Direct Connect)
`;
diff --git a/eaglerproxy/files/src/proxy/Enums.ts b/eaglerproxy/files/src/proxy/Enums.ts
new file mode 100644
index 0000000..277ddf8
--- /dev/null
+++ b/eaglerproxy/files/src/proxy/Enums.ts
@@ -0,0 +1,71 @@
+export namespace Enums {
+ export enum PacketId {
+ CSLoginPacket = 0x01,
+ SCIdentifyPacket = 0x02,
+ SCDisconnectPacket = 0xff,
+ SCChannelMessagePacket = 0x3f,
+ CSChannelMessagePacket = 0x17,
+ CSUsernamePacket = 0x04,
+ SCSyncUuidPacket = 0x05,
+ CSSetSkinPacket = 0x07,
+ CSReadyPacket = 0x08,
+ SCReadyPacket = 0x09,
+ }
+
+ export enum ChannelMessageType {
+ CLIENT = 0x17,
+ SERVER = 0x3f,
+ }
+
+ export enum EaglerSkinPacketId {
+ CFetchSkinEaglerPlayerReq = 0x03,
+ SFetchSkinBuiltInRes = 0x04,
+ SFetchSkinRes = 0x05,
+ CFetchSkinReq = 0x06,
+ }
+
+ export enum ClientState {
+ PRE_HANDSHAKE = "PRE_HANDSHAKE",
+ POST_HANDSHAKE = "POST_HANDSHAKE",
+ DISCONNECTED = "DISCONNECTED",
+ }
+
+ export enum PacketBounds {
+ C = "C",
+ S = "S",
+ }
+
+ export enum SkinType {
+ BUILTIN,
+ CUSTOM,
+ }
+
+ export enum ChatColor {
+ AQUA = "§b",
+ BLACK = "§0",
+ DARK_BLUE = "§1",
+ DARK_GREEN = "§2",
+ DARK_CYAN = "§3",
+ DARK_RED = "§4",
+ PURPLE = "§5",
+ GOLD = "§6",
+ GRAY = "§7",
+ GREEN = "§a",
+ DARK_GRAY = "§8",
+ BLUE = "§9",
+ BRIGHT_GREEN = "§a",
+ LIGHT_PURPLE = "§d",
+ CYAN = "§b",
+ RED = "§c",
+ PINK = "§d",
+ YELLOW = "§e",
+ WHITE = "§f",
+ // text styling
+ OBFUSCATED = "§k",
+ BOLD = "§l",
+ STRIKETHROUGH = "§m",
+ UNDERLINED = "§n",
+ ITALIC = "§o",
+ RESET = "§r",
+ }
+}
diff --git a/eaglerproxy/files/src/proxy/Motd.ts b/eaglerproxy/files/src/proxy/Motd.ts
new file mode 100644
index 0000000..ceed0b1
--- /dev/null
+++ b/eaglerproxy/files/src/proxy/Motd.ts
@@ -0,0 +1,114 @@
+import { randomUUID } from "crypto";
+import pkg, { NewPingResult } from "minecraft-protocol";
+import { PROXY_BRANDING, PROXY_VERSION } from "../meta.js";
+import { Config } from "../launcher_types.js";
+import { Chat } from "./Chat.js";
+import { Constants } from "./Constants.js";
+import { ImageEditor } from "./skins/ImageEditor.js";
+const { ping } = pkg;
+
+export namespace Motd {
+ export class MOTD {
+ public jsonMotd: JSONMotd;
+ public image?: Buffer;
+ public usingNatives: boolean;
+
+ constructor(motd: JSONMotd, native: boolean, image?: Buffer) {
+ this.jsonMotd = motd;
+ this.image = image;
+ this.usingNatives = native;
+ }
+
+ public static async generateMOTDFromPing(host: string, port: number, useNatives: boolean): Promise {
+ const pingRes = await ping({ host: host, port: port });
+ if (typeof pingRes.version == "string") throw new Error("Non-1.8 server detected!");
+ else {
+ const newPingRes = pingRes as NewPingResult;
+ let image: Buffer;
+
+ if (newPingRes.favicon != null) {
+ if (!newPingRes.favicon.startsWith(Constants.IMAGE_DATA_PREPEND)) throw new Error("Invalid MOTD image!");
+ image = useNatives
+ ? await ImageEditor.generateEaglerMOTDImage(Buffer.from(newPingRes.favicon.substring(Constants.IMAGE_DATA_PREPEND.length), "base64"))
+ : await ImageEditor.generateEaglerMOTDImageJS(Buffer.from(newPingRes.favicon.substring(Constants.IMAGE_DATA_PREPEND.length), "base64"));
+ }
+
+ return new MOTD(
+ {
+ brand: PROXY_BRANDING,
+ cracked: true,
+ data: {
+ cache: true,
+ icon: newPingRes.favicon != null ? true : false,
+ max: newPingRes.players.max,
+ motd: [typeof newPingRes.description == "string" ? newPingRes.description : Chat.chatToPlainString(newPingRes.description), ""],
+ online: newPingRes.players.online,
+ players: newPingRes.players.sample != null ? newPingRes.players.sample.map((v) => v.name) : [],
+ },
+ name: "placeholder name",
+ secure: false,
+ time: Date.now(),
+ type: "motd",
+ uuid: randomUUID(), // replace placeholder with global. cached UUID
+ vers: `${PROXY_BRANDING}/${PROXY_VERSION}`,
+ },
+ useNatives,
+ image
+ );
+ }
+ }
+
+ public static async generateMOTDFromConfig(config: Config["adapter"], useNatives: boolean): Promise {
+ if (typeof config.motd != "string") {
+ const motd = new MOTD(
+ {
+ brand: PROXY_BRANDING,
+ cracked: true,
+ data: {
+ cache: true,
+ icon: config.motd.iconURL != null ? true : false,
+ max: config.maxConcurrentClients,
+ motd: [config.motd.l1, config.motd.l2 ?? ""],
+ online: 0,
+ players: [],
+ },
+ name: config.name,
+ secure: false,
+ time: Date.now(),
+ type: "motd",
+ uuid: randomUUID(),
+ vers: `${PROXY_BRANDING}/${PROXY_VERSION}`,
+ },
+ useNatives
+ );
+ if (config.motd.iconURL != null) {
+ motd.image = useNatives ? await ImageEditor.generateEaglerMOTDImage(config.motd.iconURL) : await ImageEditor.generateEaglerMOTDImageJS(config.motd.iconURL); // TODO: swap between native and pure JS
+ }
+ return motd;
+ } else throw new Error("MOTD is set to be forwarded in the config!");
+ }
+
+ public toBuffer(): [string, Buffer] {
+ return [JSON.stringify(this.jsonMotd), this.image];
+ }
+ }
+
+ export type JSONMotd = {
+ brand: string;
+ cracked: true;
+ data: {
+ cache: true;
+ icon: boolean;
+ max: number;
+ motd: [string, string];
+ online: number;
+ players: string[];
+ };
+ name: string;
+ secure: false;
+ time: ReturnType;
+ type: "motd";
+ uuid: ReturnType;
+ vers: string;
+ };
+}
diff --git a/eaglerproxy/files/src/proxy/Packet.ts b/eaglerproxy/files/src/proxy/Packet.ts
new file mode 100644
index 0000000..db5fd43
--- /dev/null
+++ b/eaglerproxy/files/src/proxy/Packet.ts
@@ -0,0 +1,44 @@
+import { readdir } from "fs/promises";
+import { dirname, join, resolve } from "path";
+import { fileURLToPath, pathToFileURL } from "url";
+import { Enums } from "./Enums.js";
+import { Util } from "./Util.js";
+
+export default interface Packet {
+ packetId: Enums.PacketId;
+ type: "packet";
+ boundTo: Enums.PacketBounds;
+ sentAfterHandshake: boolean;
+
+ serialize: () => Buffer;
+ deserialize: (packet: Buffer) => this;
+}
+
+export async function loadPackets(
+ dir?: string
+): Promise