mirror of
https://github.com/minescope/mineping.git
synced 2025-07-12 12:24:36 +03:00
refactor: improve Bedrock error handling and validation
This commit is contained in:
@ -10,6 +10,7 @@ import crypto from "node:crypto";
|
||||
|
||||
const MAGIC = "00ffff00fefefefefdfdfdfd12345678";
|
||||
const START_TIME = new Date().getTime();
|
||||
const UNCONNECTED_PONG = 0x1c;
|
||||
|
||||
/**
|
||||
* Creates an Unconnected Ping packet.
|
||||
@ -30,12 +31,25 @@ const createUnconnectedPingFrame = (timestamp) => {
|
||||
* Extract Modt from Unconnected Pong Packet and convert to an object
|
||||
* @param {Buffer} unconnectedPongPacket
|
||||
* @returns {Object}
|
||||
* @throws {Error} If packet is malformed or invalid
|
||||
* @see {@link https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Raknet_Protocol#Unconnected_Pong}
|
||||
*/
|
||||
const extractModt = (unconnectedPongPacket) => {
|
||||
// Skip everything to Modt
|
||||
if (
|
||||
!Buffer.isBuffer(unconnectedPongPacket) ||
|
||||
unconnectedPongPacket.length < 35
|
||||
) {
|
||||
throw new Error("Invalid pong packet");
|
||||
}
|
||||
|
||||
const offset = 33;
|
||||
const length = unconnectedPongPacket.readUInt16BE(offset);
|
||||
|
||||
// Check for buffer bounds
|
||||
if (offset + 2 + length > unconnectedPongPacket.length) {
|
||||
throw new Error("Malformed pong packet");
|
||||
}
|
||||
|
||||
let modt = unconnectedPongPacket.toString(
|
||||
"utf-8",
|
||||
offset + 2,
|
||||
@ -43,6 +57,12 @@ const extractModt = (unconnectedPongPacket) => {
|
||||
);
|
||||
|
||||
const components = modt.split(";");
|
||||
|
||||
// Validate required components
|
||||
if (components.length < 9) {
|
||||
throw new Error("Invalid MODT format");
|
||||
}
|
||||
|
||||
const parsedComponents = {
|
||||
edition: components[0],
|
||||
name: components[1],
|
||||
@ -109,20 +129,23 @@ const ping = (host, port = 19132, cb, timeout = 5000) => {
|
||||
}
|
||||
|
||||
socket.on("message", (pongPacket) => {
|
||||
if (!Buffer.isBuffer(pongPacket) || pongPacket.length === 0) {
|
||||
handleError(new Error("Invalid packet received"));
|
||||
return;
|
||||
}
|
||||
|
||||
const id = pongPacket[0];
|
||||
if (id !== UNCONNECTED_PONG) {
|
||||
handleError(new Error(`Unexpected packet ID: 0x${id.toString(16)}`));
|
||||
return;
|
||||
}
|
||||
|
||||
switch (id) {
|
||||
case 0x1c: {
|
||||
const modtObject = extractModt(pongPacket);
|
||||
closeSocket();
|
||||
cb(modtObject, null);
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
handleError(new Error("Received unexpected packet"));
|
||||
break;
|
||||
}
|
||||
try {
|
||||
const modtObject = extractModt(pongPacket);
|
||||
closeSocket();
|
||||
cb(modtObject, null);
|
||||
} catch (err) {
|
||||
handleError(err);
|
||||
}
|
||||
});
|
||||
|
||||
|
Reference in New Issue
Block a user