diff --git a/README.md b/README.md index ff0ed80..9dd879e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # Legacy Cross Play +## Any questions, need help? [Join the server!](https://discord.gg/cb9rs9yfDm) +## CURRENTLY, THE ORIGINAL LEGACY CLIENT IS BROKEN, USE [THIS ONE]() **This project allows Legacy Console Edition clients to join a vanilla 1.8 Java Edition server!** ![](https://raw.githubusercontent.com/DeveloperExotic/LegacyCrossPlay/refs/heads/main/.assets/lce1.png) @@ -111,6 +113,7 @@ - [x] Fix arrow bug when colliding with player / low bow pull - [x] Falling block entities (e.g. sand, gravel, anvil) - [x] Fireball +- [x] Custom Java Edition skins --- @@ -119,6 +122,7 @@ ## Chat - [x] Receive server chat + - [x] Finter server colors - [x] Send server chat - [x] Fix chat commands (e.g. /say, /tellraw) - [x] Java edition english chat translations diff --git a/index.js b/index.js index 25f7496..3106336 100644 --- a/index.js +++ b/index.js @@ -17,6 +17,15 @@ const proxy = new LCEProxy(); process.on("SIGINT", () => { proxy.stop(); - process.exit(0); + setTimeout(() => { + process.exit(0); + }, 200); +}); + +process.on("SIGTERM", () => { + proxy.stop(); + setTimeout(() => { + process.exit(0); + }, 200); }); /* --------------------------------------------------------------- */ diff --git a/package-lock.json b/package-lock.json index f44e714..2ea8809 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "MIT", "dependencies": { "minecraft-protocol": "^1.64.0", + "pngjs": "^7.0.0", "prismarine-auth": "^2.7.0" } }, @@ -527,6 +528,15 @@ "asn1": "0.2.3" } }, + "node_modules/pngjs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", + "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==", + "license": "MIT", + "engines": { + "node": ">=14.19.0" + } + }, "node_modules/prismarine-auth": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/prismarine-auth/-/prismarine-auth-2.7.0.tgz", diff --git a/package.json b/package.json index a6fc8f7..158d237 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "license": "MIT", "dependencies": { "minecraft-protocol": "^1.64.0", + "pngjs": "^7.0.0", "prismarine-auth": "^2.7.0" } } diff --git a/src/auth.js b/src/auth.js index e625043..e926833 100644 --- a/src/auth.js +++ b/src/auth.js @@ -1,3 +1,6 @@ +/* --------------------------------------------------------------- */ +/* auth.js */ +/* --------------------------------------------------------------- */ const { Authflow, Titles } = require("prismarine-auth"); const fs = require("fs"); const path = require("path"); @@ -90,3 +93,4 @@ class MicrosoftAuth { const authInstance = new MicrosoftAuth(); module.exports = authInstance; +/* --------------------------------------------------------------- */ diff --git a/src/javaclienthandler.js b/src/javaclienthandler.js index 286da34..73b7d3e 100644 --- a/src/javaclienthandler.js +++ b/src/javaclienthandler.js @@ -13,8 +13,9 @@ const msAuth = require("./auth"); const PacketWriter = require("./packetwriter"); const { mapJavaItemToLCE, mapJavaBlockToLCE } = require("./mappings"); const { mapJavaSoundToLCE } = require("./mappings/soundmapping"); -const { parseChatComponent } = require("./utils/chat"); +const { parseChatComponent, stripColorCodes } = require("./utils/chat"); const { countSetBits, compressRLE } = require("./utils/chunk"); +const { downloadSkin, generateCustomSkinName } = require("./utils/skins"); const zlib = require("zlib"); async function connectToJavaServer(proxy, client) { @@ -53,7 +54,7 @@ async function connectToJavaServer(proxy, client) { try { javaClient = mc.createClient(authConfig); } catch (err) { - console.log(`Failed to connect to Java Edition server: ${err}`); + console.log(`DISCONNECTED: ${err}`); throw err; } @@ -61,7 +62,7 @@ async function connectToJavaServer(proxy, client) { client._lastJavaPackets = []; javaClient.on("error", (err) => { - console.log(`Failed to connect to Java Edition server: ${err}`); + console.log(`DISCONNECTED: ${err}`); if (!client._removing) { client._removing = true; const index = proxy.clients.indexOf(client); @@ -86,11 +87,14 @@ async function connectToJavaServer(proxy, client) { }); javaClient.on("disconnect", (packet) => { - console.log(`Failed to connect to Java Edition server: ${packet.reason}`); + console.log(`DISCONNECTED: ${packet.reason}`); + if (!client._removing) { + proxy.disconnectClient(client, 2); + } }); javaClient.on("kick_disconnect", (packet) => { - console.log(`Failed to connect to Java Edition server: ${packet.reason}`); + console.log(`DISCONNECTED: ${packet.reason}`); if (client.state === "play") { let reason = 10; if (packet.reason) { @@ -166,6 +170,7 @@ async function connectToJavaServer(proxy, client) { let chatText = ""; chatText = parseChatComponent(packet.message); + chatText = stripColorCodes(chatText); if (chatText && chatText.length > 0) { if (chatText.length > 100) { @@ -241,6 +246,7 @@ async function connectToJavaServer(proxy, client) { javaClient.on("window_items", (packet) => { if (client.state === "play") { if (packet.windowId < 0) { + return; } if (packet.windowId === 0) { @@ -269,10 +275,17 @@ async function connectToJavaServer(proxy, client) { invWriter.writeShort(packet.items.length); for (let i = 0; i < packet.items.length; i++) { - proxy.writeItem(invWriter, packet.items[i]); + try { + proxy.writeItem(invWriter, packet.items[i]); + } catch (err) { + invWriter.writeShort(-1); + } } const payload = invWriter.toBuffer(); + if (!payload || payload.length < 3 || payload.length > 10000) { + return; + } if (isNetworkedChest && chestData) { for (const otherClient of chestData.clients) { @@ -321,8 +334,9 @@ async function connectToJavaServer(proxy, client) { javaClient.on("set_slot", (packet) => { if (client.state === "play") { //idk why LCE sends negative window ids - if (packet.windowId < 0) { - } + //if (packet.windowId < 0) { + // return; + //} if (packet.windowId >= 0) { if (!client._windowInventories) { @@ -514,10 +528,64 @@ async function connectToJavaServer(proxy, client) { const wasAlreadySpawned = existingPlayer && existingPlayer.spawned; + let skinId = 0; + let skinUrl = null; + let customTextureName = null; + if (playerData.properties) { + const texturesProp = playerData.properties.find( + (p) => p.name === "textures", + ); + if (texturesProp && texturesProp.value) { + try { + const decoded = Buffer.from( + texturesProp.value, + "base64", + ).toString("utf8"); + const parsed = JSON.parse(decoded); + if (parsed.textures && parsed.textures.SKIN) { + skinUrl = parsed.textures.SKIN.url; + customTextureName = generateCustomSkinName( + playerData.name, + ); + + downloadSkin(skinUrl) + .then((skinData) => { + proxy.sendTexturePacket( + client, + customTextureName, + skinData, + ); + + const existingPlayerForSkin = + client.javaPlayers.get(uuid); + if ( + existingPlayerForSkin && + existingPlayerForSkin.entityId + ) { + proxy.sendTextureChangePacket( + client, + existingPlayerForSkin.entityId, + customTextureName, + ); + } + }) + .catch((err) => { + /* do nothing */ + }); + } + } catch (err) { + /* do nothing */ + } + } + } + const updatedPlayer = { name: playerData.name || "Player", gamemode: playerData.gamemode || 0, ping: playerData.ping || 0, + skinId: skinId, + skinUrl: skinUrl, + customTextureName: customTextureName, entityId: existingPlayer ? existingPlayer.entityId : null, javaEntityId: existingPlayer ? existingPlayer.javaEntityId @@ -849,6 +917,7 @@ async function connectToJavaServer(proxy, client) { const z = packet.location.z; if (blockId <= 0 || blockId > 255) { + return; } //const particleName = `blockcrack_${blockId}_${metadata}`; @@ -1013,7 +1082,9 @@ async function connectToJavaServer(proxy, client) { try { proxy.sendAddMobPacket(client, entityInfo); - } catch (err) {} + } catch (err) { + /* do nothing */ + } const relevantMetadata = entityInfo.metadata.filter((m) => { return [12, 13, 16].includes(m.key) && m.type !== 5; @@ -1037,6 +1108,7 @@ async function connectToJavaServer(proxy, client) { packet.entityId === undefined || packet.type === undefined ) { + return; } if ( @@ -1044,15 +1116,18 @@ async function connectToJavaServer(proxy, client) { !Number.isFinite(packet.y) || !Number.isFinite(packet.z) ) { + return; } if (!Number.isFinite(packet.yaw) || !Number.isFinite(packet.pitch)) { + return; } let lceEntityType = packet.type; const unsupportedEntityTypes = [78]; if (unsupportedEntityTypes.includes(lceEntityType)) { + return; } if (packet.type === 10) { @@ -1080,6 +1155,7 @@ async function connectToJavaServer(proxy, client) { } if (lceEntityType < 0 || lceEntityType > 200) { + return; } const lceEntityId = proxy.mapJavaEntityIdToLce(client, packet.entityId); @@ -1146,7 +1222,9 @@ async function connectToJavaServer(proxy, client) { try { proxy.sendAddEntityPacket(client, entityInfo); - } catch (err) {} + } catch (err) { + /* do nothing */ + } if (lceEntityType === 2) { entityInfo.waitingForItemData = true; @@ -1174,7 +1252,7 @@ async function connectToJavaServer(proxy, client) { break; default: displayBlockId = 0; - break; //no display + break; } if (displayBlockId > 0) { minecartMetadata.push({ key: 20, type: 2, value: displayBlockId }); @@ -1693,6 +1771,7 @@ async function connectToJavaServer(proxy, client) { try { if (client.state === "play") { if (!packet || packet.entityId === undefined) { + return; } if (packet.entityId === client.javaPlayerEntityId) { @@ -1918,7 +1997,9 @@ async function connectToJavaServer(proxy, client) { pitch: packet.pitch, onGround: true, }); - } catch (err) {} + } catch (err) { + /* do nothing */ + } } } }); diff --git a/src/lceproxy.js b/src/lceproxy.js index 448080e..5ef05c2 100644 --- a/src/lceproxy.js +++ b/src/lceproxy.js @@ -63,10 +63,10 @@ class LCEProxy { 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x3e, 0x46, 0x64, 0x65, 0x66, 0x67, - 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x82, 0x83, 0x96, 0x97, 0x98, 0xc8, - 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xfa, 0xfc, 0xfd, - 0xfe, 0xff, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x3c, 0x3d, 0x3e, 0x46, 0x64, 0x65, + 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x82, 0x83, 0x96, 0x97, + 0x98, 0x9a, 0x9d, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, + 0xd1, 0xfa, 0xfc, 0xfd, 0xfe, 0xff, ]); } @@ -794,6 +794,30 @@ class LCEProxy { this.sendPacket(client, 0x0d, moveWriter.toBuffer()); } + sendTexturePacket(client, textureName, textureData) { + if (!client || !client.socket || client.socket.destroyed) { + return; + } + const writer = new PacketWriter(); + writer.writeUTF(textureName); + writer.writeShort(textureData.length); + writer.writeBytes(textureData); + + this.sendPacket(client, 0x9a, writer.toBuffer()); + } + + sendTextureChangePacket(client, entityId, textureName) { + if (!client || !client.socket || client.socket.destroyed) { + return; + } + const writer = new PacketWriter(); + writer.writeInt(entityId); + writer.writeByte(0); + writer.writeUTF(textureName); + + this.sendPacket(client, 0x9d, writer.toBuffer()); + } + sendAddPlayerPacket(client, playerInfo) { let playerName = playerInfo.name || "undefined"; if (playerName.length > 16) { @@ -823,7 +847,9 @@ class LCEProxy { writer.writeLong(0); //xuid writer.writeLong(0); //OnlineXuid writer.writeByte(0); //playerIndex - writer.writeInt(0); //skinId + const skinIdToSend = playerInfo.skinId || 0; + + writer.writeInt(skinIdToSend); //skinId writer.writeInt(0); //capeId writer.writeInt(0); //uiGamePrivileges @@ -866,6 +892,14 @@ class LCEProxy { writer.writeByte(0x7f); this.sendPacket(client, 0x14, writer.toBuffer()); + + if (playerInfo.customTextureName) { + this.sendTextureChangePacket( + client, + playerInfo.entityId, + playerInfo.customTextureName, + ); + } } sendMoveEntityPacket(client, playerInfo) { @@ -2597,18 +2631,59 @@ class LCEProxy { lengthPrefix.writeUInt32BE(packetData.length, 0); const fullPacket = Buffer.concat([lengthPrefix, packetData]); - client.socket.write(fullPacket); + + if (fullPacket.length > 1000000) { + console.warn( + `[WARNING] Packet 0x${packetId.toString(16)} is too large: ${fullPacket.length} bytes`, + ); + return; + } + + if (!client._packetQueue) { + client._packetQueue = []; + client._sending = false; + } + + client._packetQueue.push(fullPacket); + + if (!client._sending) { + client._sending = true; + setImmediate(() => { + while (client._packetQueue.length > 0 && !client.socket.destroyed) { + const pkt = client._packetQueue.shift(); + client.socket.write(pkt); + } + client._sending = false; + }); + } } catch (err) { - /* do nothing */ + console.error( + `[ERROR] Failed to send packet 0x${packetId.toString(16)}:`, + err.message, + ); } } disconnectClient(client, reason = 0) { + const reasonMap = { + 0: "Generic disconnect", + 2: "Connection lost", + 10: "Kicked/Banned", + 20: "Timeout", + 23: "Server full", + }; + const reasonText = reasonMap[reason] || `Unknown (${reason})`; + console.log(`DISCONNECTED: ${reasonText}`); + if (client.socket && !client.socket.destroyed) { try { const writer = new PacketWriter(); writer.writeInt(reason); this.sendPacket(client, 0xff, writer.toBuffer()); + setTimeout(() => { + this.removeClient(client); + }, 100); + return; } catch (err) { /* do nothing */ } @@ -2674,7 +2749,7 @@ class LCEProxy { try { return await connectToJavaServerFunc(this, client); } catch (err) { - console.log(`Failed to connect to Java Edition server: ${err}`); + console.log(`DISCONNECTED: ${err}`); } } diff --git a/src/mappings/mappers.js b/src/mappings/mappers.js index 7d46153..a341840 100644 --- a/src/mappings/mappers.js +++ b/src/mappings/mappers.js @@ -5,7 +5,7 @@ function mapJavaBlockToLCE(javaBlockId, javaBlockMapping) { if (javaBlockMapping[javaBlockId] !== undefined) { return javaBlockMapping[javaBlockId]; } - return 0; + return 1; } function mapJavaParticleToLCE(particleId) { diff --git a/src/mappings/recipemapping.js b/src/mappings/recipemapping.js index ffa4990..301e3a8 100644 --- a/src/mappings/recipemapping.js +++ b/src/mappings/recipemapping.js @@ -1,3 +1,6 @@ +/* --------------------------------------------------------------- */ +/* recipemapping.js */ +/* --------------------------------------------------------------- */ //all of the crafting recipes that are sent from the client converted into a java recipe grid. //this was absolute fucking torture to write, thanks mojang for not using recipe ids in java edition crafting until 1.12! @@ -584,3 +587,4 @@ module.exports = { "melon", "melon", "melon" ], }; +/* --------------------------------------------------------------- */ diff --git a/src/packets/senders/entitypackets.js b/src/packets/senders/entitypackets.js index 2967602..bb53d2a 100644 --- a/src/packets/senders/entitypackets.js +++ b/src/packets/senders/entitypackets.js @@ -5,7 +5,11 @@ const PacketWriter = require("../../packetwriter"); function sendAddMobPacket(proxy, client, entityInfo) { try { - if (!entityInfo || entityInfo.entityId === undefined || entityInfo.javaEntityId === undefined) { + if ( + !entityInfo || + entityInfo.entityId === undefined || + entityInfo.javaEntityId === undefined + ) { return; } @@ -18,7 +22,11 @@ function sendAddMobPacket(proxy, client, entityInfo) { } client._sentEntities.add(entityKey); - if (!Number.isFinite(entityInfo.x) || !Number.isFinite(entityInfo.y) || !Number.isFinite(entityInfo.z)) { + if ( + !Number.isFinite(entityInfo.x) || + !Number.isFinite(entityInfo.y) || + !Number.isFinite(entityInfo.z) + ) { return; } @@ -26,109 +34,113 @@ function sendAddMobPacket(proxy, client, entityInfo) { const posY = Math.floor(entityInfo.y * 32); const posZ = Math.floor(entityInfo.z * 32); - if (!Number.isFinite(posX) || !Number.isFinite(posY) || !Number.isFinite(posZ)) { + if ( + !Number.isFinite(posX) || + !Number.isFinite(posY) || + !Number.isFinite(posZ) + ) { return; } const writer = new PacketWriter(); - writer.writeShort(entityInfo.entityId & 0xFFFF); + writer.writeShort(entityInfo.entityId & 0xffff); writer.writeByte(entityInfo.type & 0xff); writer.writeInt(posX); writer.writeInt(posY); writer.writeInt(posZ); - const yRotByte = Math.floor(((entityInfo.yaw % 360) / 360) * 256) & 0xff; - const xRotByte = Math.floor(((entityInfo.pitch % 360) / 360) * 256) & 0xff; - const yHeadRotByte = - Math.floor(((entityInfo.headYaw % 360) / 360) * 256) & 0xff; - writer.writeByte(yRotByte); - writer.writeByte(xRotByte); - writer.writeByte(yHeadRotByte); + const yRotByte = Math.floor(((entityInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((entityInfo.pitch % 360) / 360) * 256) & 0xff; + const yHeadRotByte = + Math.floor(((entityInfo.headYaw % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + writer.writeByte(yHeadRotByte); - let velX = entityInfo.velocityX || 0; - let velY = entityInfo.velocityY || 0; - let velZ = entityInfo.velocityZ || 0; - velX = Math.max(-3.9, Math.min(3.9, velX)); - velY = Math.max(-3.9, Math.min(3.9, velY)); - velZ = Math.max(-3.9, Math.min(3.9, velZ)); - const velocityX = Math.floor(velX * 8000); - const velocityY = Math.floor(velY * 8000); - const velocityZ = Math.floor(velZ * 8000); - writer.writeShort(velocityX); - writer.writeShort(velocityY); - writer.writeShort(velocityZ); + let velX = entityInfo.velocityX || 0; + let velY = entityInfo.velocityY || 0; + let velZ = entityInfo.velocityZ || 0; + velX = Math.max(-3.9, Math.min(3.9, velX)); + velY = Math.max(-3.9, Math.min(3.9, velY)); + velZ = Math.max(-3.9, Math.min(3.9, velZ)); + const velocityX = Math.floor(velX * 8000); + const velocityY = Math.floor(velY * 8000); + const velocityZ = Math.floor(velZ * 8000); + writer.writeShort(velocityX); + writer.writeShort(velocityY); + writer.writeShort(velocityZ); - writer.writeByte((0 << 5) | 0); - writer.writeByte(0); + writer.writeByte((0 << 5) | 0); + writer.writeByte(0); - writer.writeByte((1 << 5) | 1); - writer.writeShort(300); + writer.writeByte((1 << 5) | 1); + writer.writeShort(300); - const agableMobTypes = [92, 91, 90, 93, 120]; - if (agableMobTypes.includes(entityInfo.type)) { - const ageMetadata = entityInfo.metadata - ? entityInfo.metadata.find((m) => m.key === 12) - : null; - if (ageMetadata && ageMetadata.value !== undefined) { - writer.writeByte((2 << 5) | 12); - writer.writeInt(ageMetadata.value); + const agableMobTypes = [92, 91, 90, 93, 120]; + if (agableMobTypes.includes(entityInfo.type)) { + const ageMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 12) + : null; + if (ageMetadata && ageMetadata.value !== undefined) { + writer.writeByte((2 << 5) | 12); + writer.writeInt(ageMetadata.value); + } } - } - if (entityInfo.type === 120) { - const professionMetadata = entityInfo.metadata - ? entityInfo.metadata.find((m) => m.key === 16 && m.type === 2) - : null; - if (professionMetadata && professionMetadata.value !== undefined) { - writer.writeByte((2 << 5) | 16); - writer.writeInt(professionMetadata.value); + if (entityInfo.type === 120) { + const professionMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 16 && m.type === 2) + : null; + if (professionMetadata && professionMetadata.value !== undefined) { + writer.writeByte((2 << 5) | 16); + writer.writeInt(professionMetadata.value); + } } - } - const customNameMeta = entityInfo.metadata - ? entityInfo.metadata.find((m) => m.key === 2 && m.type === 4) - : null; - if (customNameMeta && customNameMeta.value) { - writer.writeByte((4 << 5) | 10); - writer.writeUtf(customNameMeta.value); - } - - const customNameVisibleMeta = entityInfo.metadata - ? entityInfo.metadata.find((m) => m.key === 3 && m.type === 0) - : null; - if (customNameVisibleMeta && customNameVisibleMeta.value !== undefined) { - writer.writeByte((0 << 5) | 11); - writer.writeByte(customNameVisibleMeta.value & 0xff); - } - - if (entityInfo.type === 55 || entityInfo.type === 62) { - const sizeMetadata = entityInfo.metadata - ? entityInfo.metadata.find((m) => m.key === 16 && m.type === 0) + const customNameMeta = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 2 && m.type === 4) : null; - if (sizeMetadata && sizeMetadata.value !== undefined) { - writer.writeByte((0 << 5) | 16); - writer.writeByte(sizeMetadata.value & 0xff); + if (customNameMeta && customNameMeta.value) { + writer.writeByte((4 << 5) | 10); + writer.writeUtf(customNameMeta.value); } - } - if (entityInfo.type === 51) { - const typeMetadata = entityInfo.metadata - ? entityInfo.metadata.find((m) => m.key === 13 && m.type === 0) + const customNameVisibleMeta = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 3 && m.type === 0) : null; - if (typeMetadata && typeMetadata.value !== undefined) { - writer.writeByte((0 << 5) | 13); - writer.writeByte(typeMetadata.value & 0xff); + if (customNameVisibleMeta && customNameVisibleMeta.value !== undefined) { + writer.writeByte((0 << 5) | 11); + writer.writeByte(customNameVisibleMeta.value & 0xff); } - } - writer.writeByte(0x7f); + if (entityInfo.type === 55 || entityInfo.type === 62) { + const sizeMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 16 && m.type === 0) + : null; + if (sizeMetadata && sizeMetadata.value !== undefined) { + writer.writeByte((0 << 5) | 16); + writer.writeByte(sizeMetadata.value & 0xff); + } + } - const payload = writer.toBuffer(); - if (!payload || payload.length === 0 || payload.length > 1000) { - return; - } - proxy.sendPacket(client, 0x18, payload); + if (entityInfo.type === 51) { + const typeMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 13 && m.type === 0) + : null; + if (typeMetadata && typeMetadata.value !== undefined) { + writer.writeByte((0 << 5) | 13); + writer.writeByte(typeMetadata.value & 0xff); + } + } + + writer.writeByte(0x7f); + + const payload = writer.toBuffer(); + if (!payload || payload.length === 0 || payload.length > 1000) { + return; + } + proxy.sendPacket(client, 0x18, payload); } catch (err) { /* do nothing */ } @@ -140,7 +152,11 @@ function sendAddEntityPacket(proxy, client, entityInfo) { return; } - if (!Number.isFinite(entityInfo.x) || !Number.isFinite(entityInfo.y) || !Number.isFinite(entityInfo.z)) { + if ( + !Number.isFinite(entityInfo.x) || + !Number.isFinite(entityInfo.y) || + !Number.isFinite(entityInfo.z) + ) { return; } @@ -148,13 +164,17 @@ function sendAddEntityPacket(proxy, client, entityInfo) { const posY = Math.floor(entityInfo.y * 32); const posZ = Math.floor(entityInfo.z * 32); - if (!Number.isFinite(posX) || !Number.isFinite(posY) || !Number.isFinite(posZ)) { + if ( + !Number.isFinite(posX) || + !Number.isFinite(posY) || + !Number.isFinite(posZ) + ) { return; } const writer = new PacketWriter(); - writer.writeShort(entityInfo.entityId & 0xFFFF); - writer.writeByte(entityInfo.type & 0xFF); + writer.writeShort(entityInfo.entityId & 0xffff); + writer.writeByte(entityInfo.type & 0xff); writer.writeInt(posX); writer.writeInt(posY); @@ -169,17 +189,32 @@ function sendAddEntityPacket(proxy, client, entityInfo) { writer.writeByte(yRotByte); writer.writeByte(xRotByte); - const data = entityInfo.data !== undefined && Number.isFinite(entityInfo.data) ? entityInfo.data : -1; + const data = + entityInfo.data !== undefined && Number.isFinite(entityInfo.data) + ? entityInfo.data + : -1; writer.writeInt(data); if (data > -1) { - const velocityX = Number.isFinite(entityInfo.velocityX) ? entityInfo.velocityX : 0; - const velocityY = Number.isFinite(entityInfo.velocityY) ? entityInfo.velocityY : 0; - const velocityZ = Number.isFinite(entityInfo.velocityZ) ? entityInfo.velocityZ : 0; + const velocityX = Number.isFinite(entityInfo.velocityX) + ? entityInfo.velocityX + : 0; + const velocityY = Number.isFinite(entityInfo.velocityY) + ? entityInfo.velocityY + : 0; + const velocityZ = Number.isFinite(entityInfo.velocityZ) + ? entityInfo.velocityZ + : 0; - writer.writeShort(Math.max(-32768, Math.min(32767, Math.floor(velocityX)))); - writer.writeShort(Math.max(-32768, Math.min(32767, Math.floor(velocityY)))); - writer.writeShort(Math.max(-32768, Math.min(32767, Math.floor(velocityZ)))); + writer.writeShort( + Math.max(-32768, Math.min(32767, Math.floor(velocityX))), + ); + writer.writeShort( + Math.max(-32768, Math.min(32767, Math.floor(velocityY))), + ); + writer.writeShort( + Math.max(-32768, Math.min(32767, Math.floor(velocityZ))), + ); } const buffer = writer.toBuffer(); @@ -298,7 +333,25 @@ function sendRotateHeadPacketForEntity(proxy, client, entity) { function sendEntityMetadataPacket(proxy, client, entity, metadata) { const writer = new PacketWriter(); writer.writeInt(entity.entityId); + for (const item of metadata) { + if (!item || item.type === undefined || item.key === undefined) { + console.error( + `[METADATA ERROR] entityId=${entity.entityId} invalid metadata item:`, + JSON.stringify(item), + ); + continue; + } + if (item.type < 0 || item.type > 5) { + console.error( + `[METADATA ERROR] entityId=${entity.entityId} invalid type=${item.type} key=${item.key}`, + ); + continue; + } + if (item.type === 5) { + continue; + } + if (item.key === 12 && item.type === 0) { const ageableMobTypes = [ "Pig", @@ -342,15 +395,12 @@ function sendEntityMetadataPacket(proxy, client, entity, metadata) { case 4: writer.writeUtf(item.value); break; - case 5: - continue; - default: - continue; } } writer.writeByte(0x7f); - proxy.sendPacket(client, 0x28, writer.toBuffer()); + const payload = writer.toBuffer(); + proxy.sendPacket(client, 0x28, payload); } function sendSetEntityMotionPacket(proxy, client, entity) { diff --git a/src/packets/senders/playerpackets.js b/src/packets/senders/playerpackets.js index b4b2077..2f9a03e 100644 --- a/src/packets/senders/playerpackets.js +++ b/src/packets/senders/playerpackets.js @@ -43,7 +43,7 @@ function sendAddPlayerPacket(proxy, client, playerInfo) { writer.writeLong(0); //xuid writer.writeLong(0); //OnlineXuid writer.writeByte(0); //playerIndex - writer.writeInt(0); //skinId + writer.writeInt(playerInfo.skinId || 0); //skinId writer.writeInt(0); //capeId writer.writeInt(0); //uiGamePrivileges diff --git a/src/utils/chat.js b/src/utils/chat.js index 2ce6a86..ebd13a1 100644 --- a/src/utils/chat.js +++ b/src/utils/chat.js @@ -469,6 +469,13 @@ function getTranslation(key, args = []) { return key; } +function stripColorCodes(text) { + if (!text || typeof text !== "string") { + return text; + } + return text.replace(/ยง./g, ""); +} + function parseChatComponent(component) { if (!component) return ""; @@ -523,5 +530,5 @@ function parseChatComponent(component) { return result; } -module.exports = { getTranslation, parseChatComponent }; +module.exports = { getTranslation, parseChatComponent, stripColorCodes }; /* --------------------------------------------------------------- */ diff --git a/src/utils/items.js b/src/utils/items.js index 9cfc4f3..2136e28 100644 --- a/src/utils/items.js +++ b/src/utils/items.js @@ -67,122 +67,68 @@ function readItem(reader) { } function writeItemNBT(writer, item) { - const PacketWriter = require("../packetwriter"); - - let customName = null; - let storedEnchantments = null; - - if (item.nbtData && item.nbtData.value) { - if (item.nbtData.value.display) { - const display = item.nbtData.value.display.value; - if (display.Name) { - customName = display.Name.value; - try { - const parsed = JSON.parse(customName); - if (parsed.text) { - customName = parsed.text; - } else if (typeof parsed === "string") { - customName = parsed; - } - } catch (err) { - /* do nothing */ - } - } - } - - if (item.nbtData.value.StoredEnchantments) { - storedEnchantments = item.nbtData.value.StoredEnchantments.value.value; - } - } - - if (!customName && !storedEnchantments) { - writer.writeShort(-1); - return; - } - - const nbtWriter = new PacketWriter(); - - nbtWriter.writeByte(10); - nbtWriter.writeString(""); - - if (customName) { - nbtWriter.writeByte(10); - nbtWriter.writeString("display"); - nbtWriter.writeByte(8); - nbtWriter.writeString("Name"); - nbtWriter.writeString(customName); - nbtWriter.writeByte(0); - } - - if (storedEnchantments) { - nbtWriter.writeByte(9); - nbtWriter.writeString("StoredEnchantments"); - nbtWriter.writeByte(10); - nbtWriter.writeInt(storedEnchantments.length); - - for (const ench of storedEnchantments) { - nbtWriter.writeByte(2); - nbtWriter.writeString("id"); - nbtWriter.writeShort(ench.id.value); - nbtWriter.writeByte(2); - nbtWriter.writeString("lvl"); - nbtWriter.writeShort(ench.lvl.value); - nbtWriter.writeByte(0); - } - } - - nbtWriter.writeByte(0); - - const nbtData = nbtWriter.toBuffer(); - writer.writeShort(nbtData.length); - writer.writeBytes(nbtData); + writer.writeShort(-1); + return; } function writeItem(writer, item, mapJavaItemToLCE) { - if (!item || item.blockId === -1 || item.itemId === -1 || item === null) { + try { + if (!item || item === null) { + writer.writeShort(-1); + return; + } + + let javaItemId = + item.itemId !== undefined + ? item.itemId + : item.blockId !== undefined + ? item.blockId + : -1; + + if ( + javaItemId === -1 || + javaItemId === undefined || + !Number.isFinite(javaItemId) + ) { + writer.writeShort(-1); + return; + } + + let lceItemId = mapJavaItemToLCE(javaItemId); + let auxValue = + item.itemDamage !== undefined ? item.itemDamage : item.metadata || 0; + + if ( + lceItemId === undefined || + lceItemId === null || + lceItemId === -1 || + lceItemId === 0 || + !Number.isFinite(lceItemId) + ) { + lceItemId = 1; + auxValue = 0; + } + + if (lceItemId < 0 || lceItemId > 2267) { + lceItemId = 1; + auxValue = 0; + } + + if (!Number.isFinite(auxValue)) { + auxValue = 0; + } + + writer.writeShort(lceItemId); + + const count = item.itemCount || item.count || 1; + writer.writeByte(Math.max(1, Math.min(255, count))); + + writer.writeShort(Math.max(0, Math.min(32767, auxValue))); + + writeItemNBT(writer, item); + } catch (err) { writer.writeShort(-1); - return; } - - let javaItemId = - item.itemId !== undefined - ? item.itemId - : item.blockId !== undefined - ? item.blockId - : -1; - - if (javaItemId === -1 || javaItemId === undefined) { - writer.writeShort(-1); - return; - } - - let lceItemId = mapJavaItemToLCE(javaItemId); - let auxValue = - item.itemDamage !== undefined ? item.itemDamage : item.metadata || 0; - - if ( - lceItemId === undefined || - lceItemId === null || - lceItemId === -1 || - lceItemId === 0 - ) { - lceItemId = 1; - auxValue = 0; - } - - if (lceItemId < 0 || lceItemId > 2267) { - lceItemId = 1; - auxValue = 0; - } - - writer.writeShort(lceItemId); - - const count = item.itemCount || item.count || 1; - writer.writeByte(Math.max(1, Math.min(255, count))); - - writer.writeShort(Math.max(0, Math.min(32767, auxValue))); - - writeItemNBT(writer, item); } module.exports = { diff --git a/src/utils/skins.js b/src/utils/skins.js new file mode 100644 index 0000000..a05e07a --- /dev/null +++ b/src/utils/skins.js @@ -0,0 +1,119 @@ +/* --------------------------------------------------------------- */ +/* skins.js */ +/* --------------------------------------------------------------- */ +const https = require("https"); +const http = require("http"); +const { PNG } = require("pngjs"); + +const skinCache = new Map(); + +function convertSkinTo64x32(skinBuffer) { + return new Promise((resolve, reject) => { + try { + const png = PNG.sync.read(skinBuffer); + + if (png.height === 32) { + resolve(skinBuffer); + return; + } + + const newPng = new PNG({ width: 64, height: 32 }); + newPng.data.fill(0); + + function copy(sx, sy, w, h, dx, dy) { + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + const srcIdx = ((sy + y) * 64 + (sx + x)) << 2; + const dstIdx = ((dy + y) * 64 + (dx + x)) << 2; + newPng.data[dstIdx] = png.data[srcIdx]; + newPng.data[dstIdx + 1] = png.data[srcIdx + 1]; + newPng.data[dstIdx + 2] = png.data[srcIdx + 2]; + newPng.data[dstIdx + 3] = png.data[srcIdx + 3]; + } + } + } + + for (let y = 0; y < 32; y++) { + for (let x = 0; x < 64; x++) { + const idx = (y * 64 + x) << 2; + newPng.data[idx] = 0; + newPng.data[idx + 1] = 0; + newPng.data[idx + 2] = 0; + newPng.data[idx + 3] = 0; + } + } + + copy(0, 0, 64, 16, 0, 0); + copy(16, 16, 16, 16, 16, 16); + copy(32, 16, 16, 16, 32, 16); + copy(0, 16, 16, 16, 0, 16); + copy(40, 16, 16, 16, 40, 16); + copy(20, 16, 8, 4, 20, 16); + copy(28, 16, 8, 4, 28, 16); + copy(20, 20, 8, 12, 20, 20); + copy(28, 20, 8, 12, 28, 20); + copy(4, 16, 4, 4, 4, 16); + copy(8, 16, 4, 4, 8, 16); + copy(4, 20, 4, 12, 4, 20); + copy(8, 20, 4, 12, 8, 20); + copy(44, 16, 4, 4, 44, 16); + copy(48, 16, 4, 4, 48, 16); + copy(44, 20, 4, 12, 44, 20); + copy(48, 20, 4, 12, 48, 20); + + copy(32, 0, 32, 16, 32, 0); + + resolve(PNG.sync.write(newPng)); + } catch (err) { + reject(err); + } + }); +} + +function downloadSkin(url) { + return new Promise((resolve, reject) => { + if (skinCache.has(url)) { + resolve(skinCache.get(url)); + return; + } + + const protocol = url.startsWith("https") ? https : http; + + protocol + .get(url, (res) => { + if (res.statusCode !== 200) { + return; + } + + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => { + const skinData = Buffer.concat(chunks); + convertSkinTo64x32(skinData) + .then((convertedSkin) => { + skinCache.set(url, convertedSkin); + resolve(convertedSkin); + }) + .catch(reject); + }); + }) + .on("error", reject); + }); +} + +function generateCustomSkinName(playerName) { + let hash = 0; + for (let i = 0; i < playerName.length; i++) { + hash = (hash << 5) - hash + playerName.charCodeAt(i); + hash = hash & hash; + } + const skinId = (Math.abs(hash) & 0x7fffffe0) | 0x20; + return `ugcskin${skinId.toString(16).toUpperCase().padStart(8, "0")}.png`; +} + +module.exports = { + downloadSkin, + generateCustomSkinName, + skinCache, +}; +/* --------------------------------------------------------------- */