Archive eaglerproxy (server, 1.8.8, clean)

This commit is contained in:
2026-11-27 22:15:37 -06:00
parent 0f05955131
commit b4485b1e38
66 changed files with 8178 additions and 0 deletions
@@ -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