@xx_amaba_xx/robloxbot 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,17 @@
1
1
  /**
2
- * RakNet headless transport skeleton.
2
+ * RakNet headless transport for Roblox.
3
3
  *
4
- * Implements the Transport ABC with packet encoding/decoding helpers
5
- * and connection-state tracking. The actual socket connection and
6
- * RakNet framing (frame splitting, reliability, sequencing, ACKs) are
7
- * NOT implemented — connect()/send() throw NotImplementedError with
8
- * clear upgrade instructions.
4
+ * Implements UDP socket, RakNet handshake, and basic framing.
5
+ * Packet structures in src/constants/packets.js are placeholders —
6
+ * fill them in by capturing/decoding real Roblox traffic.
9
7
  *
10
- * To make this transport real:
11
- * 1. Implement connect() to open a UDP/TCP socket to Roblox's game
12
- * servers and complete the RakNet handshake.
13
- * 2. Implement send() to frame packets per RakNet spec and send them.
14
- * 3. Implement a receive loop that decodes incoming frames and emits
15
- * "packet" events with decoded Roblox packet objects.
16
- * 4. Fill in real field layouts in src/constants/packets.js as you
17
- * reverse-engineer the protocol.
8
+ * References:
9
+ * - RakNet protocol spec (RakNet 4.x, used by Roblox)
10
+ * - Roblox protocol reverse-engineering community docs
18
11
  */
19
12
 
20
13
  import { Transport } from "./base.js";
21
- import { NotImplementedError } from "../exceptions.js";
14
+ import { NotImplementedError, TransportError } from "../exceptions.js";
22
15
  import {
23
16
  PACKET_OPCODES,
24
17
  PACKET_NAMES,
@@ -26,13 +19,45 @@ import {
26
19
  TYPE_SIZES,
27
20
  getPacketFields,
28
21
  isPacketDefined,
22
+ encodeCompound,
23
+ decodeCompound,
29
24
  } from "../constants/packets.js";
30
25
 
31
- // Fixed-width type encoders/decoders (little-endian).
26
+ // ─── Constants ────────────────────────────────────────────────────────
27
+
28
+ // RakNet built-in message IDs (0x00–0x1F reserved)
29
+ const RAKNET = {
30
+ ID_CONNECTED_PONG: 0x00,
31
+ ID_UNCONNECTED_PING: 0x01,
32
+ ID_UNCONNECTED_PONG: 0x1C,
33
+ ID_CONNECTION_REQUEST: 0x09,
34
+ ID_CONNECTION_REQUEST_ACCEPTED: 0x10,
35
+ ID_NEW_INCOMING_CONNECTION: 0x13,
36
+ ID_DISCONNECTION_NOTIFICATION: 0x15,
37
+ ID_CONNECTION_LOST: 0x16,
38
+ ID_CONNECTED_PING: 0x03,
39
+ ID_GAME_PACKET: 0xFE, // user packets start here (Roblox uses 0x80+)
40
+ };
41
+
42
+ // Reliability types
43
+ const RELIABILITY = {
44
+ UNRELIABLE: 0x0,
45
+ UNRELIABLE_SEQUENCED: 0x1,
46
+ RELIABLE: 0x2,
47
+ RELIABLE_ORDERED: 0x3,
48
+ RELIABLE_SEQUENCED: 0x4,
49
+ UNRELIABLE_WITH_ACK_RECEIPT: 0x5,
50
+ RELIABLE_WITH_ACK_RECEIPT: 0x6,
51
+ RELIABLE_ORDERED_WITH_ACK_RECEIPT: 0x7,
52
+ };
53
+
54
+ // ─── Type Encoders/Decoders ──────────────────────────────────────────
55
+
32
56
  const ENCODERS = {
33
57
  u8: (view, offset, value) => view.setUint8(offset, value, true),
34
58
  u16: (view, offset, value) => view.setUint16(offset, value, true),
35
59
  u32: (view, offset, value) => view.setUint32(offset, value, true),
60
+ u64: (view, offset, value) => view.setBigUint64(offset, BigInt(value), true),
36
61
  i32: (view, offset, value) => view.setInt32(offset, value, true),
37
62
  f32: (view, offset, value) => view.setFloat32(offset, value, true),
38
63
  f64: (view, offset, value) => view.setFloat64(offset, value, true),
@@ -43,18 +68,20 @@ const DECODERS = {
43
68
  u8: (view, offset) => view.getUint8(offset, true),
44
69
  u16: (view, offset) => view.getUint16(offset, true),
45
70
  u32: (view, offset) => view.getUint32(offset, true),
71
+ u64: (view, offset) => Number(view.getBigUint64(offset, true)),
46
72
  i32: (view, offset) => view.getInt32(offset, true),
47
73
  f32: (view, offset) => view.getFloat32(offset, true),
48
74
  f64: (view, offset) => view.getFloat64(offset, true),
49
75
  bool: (view, offset) => view.getUint8(offset, true) !== 0,
50
76
  };
51
77
 
78
+ // ─── Packet Encoding/Decoding (Roblox game packets) ──────────────────
79
+
52
80
  /**
53
- * Encode a packet object into an ArrayBuffer using the field descriptor
54
- * for its opcode. Strings are length-prefixed (u16 length + UTF-8 bytes).
81
+ * Encode a Roblox game packet (opcode 0x80+) into ArrayBuffer.
55
82
  * Returns { buffer, byteLength }.
56
83
  */
57
- export function encodePacket({ opcode, ...fields }) {
84
+ function encodePacket({ opcode, ...fields }) {
58
85
  const fieldDescs = getPacketFields(opcode);
59
86
  if (!fieldDescs) {
60
87
  throw new Error(
@@ -63,8 +90,7 @@ export function encodePacket({ opcode, ...fields }) {
63
90
  );
64
91
  }
65
92
 
66
- // First pass: compute total byte length.
67
- let byteLength = 1; // opcode byte
93
+ let byteLength = 1;
68
94
  const fieldData = [];
69
95
  for (const desc of fieldDescs) {
70
96
  const value = fields[desc.name];
@@ -77,17 +103,18 @@ export function encodePacket({ opcode, ...fields }) {
77
103
  const buf = value instanceof Uint8Array ? value : new Uint8Array(0);
78
104
  fieldData.push({ desc, value: buf, size: 2 + buf.length });
79
105
  byteLength += 2 + buf.length;
106
+ } else if (TYPE_SIZES[desc.type] && !ENCODERS[desc.type]) {
107
+ // Compound type (vector3, cframe, etc.)
108
+ fieldData.push({ desc, value, size: TYPE_SIZES[desc.type] });
109
+ byteLength += TYPE_SIZES[desc.type];
80
110
  } else {
81
111
  const size = TYPE_SIZES[desc.type];
82
- if (!size) {
83
- throw new Error(`Unknown field type "${desc.type}" for field ${desc.name}`);
84
- }
112
+ if (!size) throw new Error(`Unknown field type "${desc.type}" for ${desc.name}`);
85
113
  fieldData.push({ desc, value, size });
86
114
  byteLength += size;
87
115
  }
88
116
  }
89
117
 
90
- // Second pass: write into buffer.
91
118
  const buffer = new ArrayBuffer(byteLength);
92
119
  const view = new DataView(buffer);
93
120
  let offset = 0;
@@ -106,6 +133,9 @@ export function encodePacket({ opcode, ...fields }) {
106
133
  offset += 2;
107
134
  new Uint8Array(buffer).set(value, offset);
108
135
  offset += value.length;
136
+ } else if (TYPE_SIZES[desc.type] && !ENCODERS[desc.type]) {
137
+ // Compound type
138
+ offset += encodeCompound(desc.type, value, view, offset);
109
139
  } else {
110
140
  ENCODERS[desc.type](view, offset, value);
111
141
  offset += size;
@@ -116,10 +146,10 @@ export function encodePacket({ opcode, ...fields }) {
116
146
  }
117
147
 
118
148
  /**
119
- * Decode an ArrayBuffer into a packet object using the field descriptor
120
- * for its opcode. Returns { opcode, fields }.
149
+ * Decode an ArrayBuffer into a Roblox game packet.
150
+ * Returns { opcode, opcodeName, fields, _undefined? }.
121
151
  */
122
- export function decodePacket(buffer) {
152
+ function decodePacket(buffer) {
123
153
  const view = new DataView(buffer);
124
154
  let offset = 0;
125
155
 
@@ -149,6 +179,10 @@ export function decodePacket(buffer) {
149
179
  offset += 2;
150
180
  fields[desc.name] = new Uint8Array(buffer.slice(offset, offset + len));
151
181
  offset += len;
182
+ } else if (TYPE_SIZES[desc.type] && !DECODERS[desc.type]) {
183
+ // Compound type
184
+ fields[desc.name] = decodeCompound(desc.type, view, offset);
185
+ offset += TYPE_SIZES[desc.type];
152
186
  } else {
153
187
  fields[desc.name] = DECODERS[desc.type](view, offset);
154
188
  offset += TYPE_SIZES[desc.type];
@@ -162,15 +196,194 @@ export function decodePacket(buffer) {
162
196
  };
163
197
  }
164
198
 
165
- export class RakNetTransport extends Transport {
199
+ // ─── RakNet Frame Helpers ────────────────────────────────────────────
200
+
201
+ /**
202
+ * Write a 3-byte (24-bit) unsigned integer (little-endian).
203
+ */
204
+ function writeU24(view, offset, value) {
205
+ view.setUint8(offset, value & 0xFF);
206
+ view.setUint8(offset + 1, (value >> 8) & 0xFF);
207
+ view.setUint8(offset + 2, (value >> 16) & 0xFF);
208
+ }
209
+
210
+ /**
211
+ * Read a 3-byte (24-bit) unsigned integer (little-endian).
212
+ */
213
+ function readU24(view, offset) {
214
+ return view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16);
215
+ }
216
+
217
+ /**
218
+ * Build a RakNet frame from a raw payload.
219
+ * Returns ArrayBuffer ready to send over UDP.
220
+ */
221
+ function buildRakNetFrame(payload, options = {}) {
222
+ const {
223
+ reliability = RELIABILITY.RELIABLE_ORDERED,
224
+ orderingChannel = 0,
225
+ orderingIndex = 0,
226
+ sequenceNumber = 0,
227
+ isSplit = false,
228
+ splitCount = 1,
229
+ splitId = 0,
230
+ splitIndex = 0,
231
+ } = options;
232
+
233
+ const headerSize = 1 + 3 + (reliability >= RELIABILITY.RELIABLE ? 4 : 0) +
234
+ (reliability >= RELIABILITY.UNRELIABLE_SEQUENCED ? 4 : 0) +
235
+ (isSplit ? 12 : 0);
236
+
237
+ const buffer = new ArrayBuffer(headerSize + payload.byteLength);
238
+ const view = new DataView(buffer);
239
+ let offset = 0;
240
+
241
+ // Message ID (0xFE for game packets)
242
+ view.setUint8(offset, RAKNET.ID_GAME_PACKET);
243
+ offset += 1;
244
+
245
+ // Frame flags: reliability (3 bits) + hasSplit (1 bit) + reserved (4 bits)
246
+ const flags = (reliability & 0x07) | (isSplit ? 0x80 : 0);
247
+ view.setUint8(offset, flags);
248
+ offset += 1;
249
+
250
+ // Message length (24-bit, bytes of payload only)
251
+ writeU24(view, offset, payload.byteLength);
252
+ offset += 3;
253
+
254
+ // Reliable/sequenced: message sequence number (32-bit)
255
+ if (reliability >= RELIABILITY.RELIABLE) {
256
+ view.setUint32(offset, sequenceNumber, true);
257
+ offset += 4;
258
+ }
259
+
260
+ // Sequenced: ordering channel + ordering index
261
+ if (reliability >= RELIABILITY.UNRELIABLE_SEQUENCED) {
262
+ view.setUint8(offset, orderingChannel);
263
+ offset += 1;
264
+ view.setUint32(offset, orderingIndex, true);
265
+ offset += 4;
266
+ }
267
+
268
+ // Split packet info
269
+ if (isSplit) {
270
+ view.setUint32(offset, splitCount, true);
271
+ offset += 4;
272
+ view.setUint32(offset, splitId, true);
273
+ offset += 4;
274
+ view.setUint32(offset, splitIndex, true);
275
+ offset += 4;
276
+ }
277
+
278
+ // Payload
279
+ new Uint8Array(buffer).set(new Uint8Array(payload), offset);
280
+
281
+ return buffer;
282
+ }
283
+
284
+ /**
285
+ * Parse a RakNet frame from received UDP data.
286
+ * Returns { frameType, payload, reliable?, sequenced?, split? } or null if not a game packet.
287
+ */
288
+ function parseRakNetFrame(buffer) {
289
+ const view = new DataView(buffer);
290
+ let offset = 0;
291
+
292
+ if (buffer.byteLength < 2) return null;
293
+
294
+ const messageId = view.getUint8(offset);
295
+ offset += 1;
296
+
297
+ // Only handle game packets (0xFE) and built-in RakNet messages we care about
298
+ if (messageId === RAKNET.ID_GAME_PACKET) {
299
+ const flags = view.getUint8(offset);
300
+ offset += 1;
301
+
302
+ const reliability = flags & 0x07;
303
+ const isSplit = (flags & 0x80) !== 0;
304
+
305
+ const length = readU24(view, offset);
306
+ offset += 3;
307
+
308
+ let reliableSeq = null;
309
+ let orderedSeq = null;
310
+
311
+ if (reliability >= RELIABILITY.RELIABLE) {
312
+ reliableSeq = view.getUint32(offset, true);
313
+ offset += 4;
314
+ }
315
+ if (reliability >= RELIABILITY.UNRELIABLE_SEQUENCED) {
316
+ orderedSeq = {
317
+ channel: view.getUint8(offset),
318
+ index: view.getUint32(offset + 1, true),
319
+ };
320
+ offset += 5;
321
+ }
322
+
323
+ let splitInfo = null;
324
+ if (isSplit) {
325
+ splitInfo = {
326
+ count: view.getUint32(offset, true),
327
+ id: view.getUint32(offset + 4, true),
328
+ index: view.getUint32(offset + 8, true),
329
+ };
330
+ offset += 12;
331
+ }
332
+
333
+ const payload = buffer.slice(offset, offset + length);
334
+ return {
335
+ frameType: "game",
336
+ payload,
337
+ reliability,
338
+ reliableSeq,
339
+ orderedSeq,
340
+ split: splitInfo,
341
+ };
342
+ }
343
+
344
+ // Built-in RakNet messages
345
+ const builtinNames = {
346
+ [RAKNET.ID_UNCONNECTED_PONG]: "unconnected_pong",
347
+ [RAKNET.ID_CONNECTION_REQUEST_ACCEPTED]: "connection_accepted",
348
+ [RAKNET.ID_NEW_INCOMING_CONNECTION]: "new_connection",
349
+ [RAKNET.ID_DISCONNECTION_NOTIFICATION]: "disconnect",
350
+ [RAKNET.ID_CONNECTION_LOST]: "connection_lost",
351
+ [RAKNET.ID_CONNECTED_PONG]: "connected_pong",
352
+ };
353
+
354
+ if (builtinNames[messageId]) {
355
+ return {
356
+ frameType: "builtin",
357
+ messageId,
358
+ name: builtinNames[messageId],
359
+ payload: buffer.slice(offset),
360
+ };
361
+ }
362
+
363
+ return { frameType: "unknown", messageId, payload: buffer.slice(offset) };
364
+ }
365
+
366
+ // ─── RakNetTransport Class ───────────────────────────────────────────
367
+
368
+ class RakNetTransport extends Transport {
166
369
  constructor(options = {}) {
167
370
  super();
168
371
  this.options = options;
169
372
  this._host = options.host || "roblox.com";
170
373
  this._port = options.port || 5222;
171
374
  this._connected = false;
172
- this._socket = null; // set by connect() when implemented
375
+ this._socket = null;
173
376
  this._receiveLoop = null;
377
+ this._guid = BigInt("0x" + crypto.getRandomValues(new Uint8Array(8)).reduce((s, b) => s + b.toString(16).padStart(2, "0"), ""));
378
+ this._remoteGuid = null;
379
+ this._mtu = 1400;
380
+ this._sendSeq = 0;
381
+ this._recvSeq = 0;
382
+ this._orderingIndices = new Array(256).fill(0);
383
+ this._pendingAcks = new Map(); // seq -> { frame, retries, timeout }
384
+ this._ackInterval = null;
385
+ this._pingInterval = null;
386
+ this._lastRecv = Date.now();
174
387
  }
175
388
 
176
389
  get connected() {
@@ -185,45 +398,82 @@ export class RakNetTransport extends Transport {
185
398
  return this._port;
186
399
  }
187
400
 
401
+ get localGuid() {
402
+ return this._guid;
403
+ }
404
+
405
+ get remoteGuid() {
406
+ return this._remoteGuid;
407
+ }
408
+
188
409
  /**
189
- * Connect to the Roblox game server and complete the RakNet handshake.
190
- * Not implemented — socket + handshake logic needed.
410
+ * Connect to Roblox game server via RakNet UDP.
411
+ * Performs handshake: unconnected ping → connection request → accepted.
191
412
  */
192
413
  async connect(options = {}) {
193
414
  const host = options.host || this._host;
194
415
  const port = options.port || this._port;
195
416
 
196
- throw new NotImplementedError(
197
- `RakNet.connect to ${host}:${port}. ` +
198
- "To implement: open a UDP socket, send RakNet connection request, " +
199
- "wait for ID_CONNECTION_REQUEST_ACCEPTED, then start a receive loop " +
200
- "that decodes incoming frames via decodePacket() and emits 'packet' events."
201
- );
417
+ // Resolve hostname
418
+ const addrs = await this._resolveHost(host);
419
+ if (addrs.length === 0) {
420
+ throw new TransportError(`Failed to resolve ${host}`);
421
+ }
422
+ this._remoteAddr = addrs[0];
423
+ this._remotePort = port;
424
+
425
+ // Create UDP socket
426
+ this._socket = this._createSocket();
427
+
428
+ // Start receive loop
429
+ this._startReceiveLoop();
430
+
431
+ // Step 1: Unconnected ping (get server GUID, MTU, etc.)
432
+ const pong = await this._sendUnconnectedPing();
433
+ this._remoteGuid = pong.serverGuid;
434
+ this._mtu = pong.mtu || 1400;
435
+
436
+ // Step 2: Connection request
437
+ await this._sendConnectionRequest();
438
+
439
+ // Step 3: Wait for connection accepted
440
+ await this._waitForConnectionAccepted();
441
+
442
+ this._connected = true;
443
+ this._startAckLoop();
444
+ this._startPingLoop();
445
+
446
+ this.emit("connect", { host, port, guid: this._remoteGuid });
447
+ return { host, port, guid: this._remoteGuid };
202
448
  }
203
449
 
204
450
  /**
205
- * Disconnect and close the socket.
451
+ * Disconnect and cleanup.
206
452
  */
207
453
  async disconnect() {
454
+ if (this._connected && this._socket) {
455
+ // Send disconnection notification
456
+ const buf = new ArrayBuffer(1);
457
+ new DataView(buf).setUint8(0, RAKNET.ID_DISCONNECTION_NOTIFICATION);
458
+ this._socket.send(buf, 0, buf.byteLength, this._remotePort, this._remoteAddr);
459
+ }
460
+
208
461
  this._connected = false;
209
462
  if (this._socket) {
210
- try {
211
- this._socket.close();
212
- } catch (_) {
213
- // ignore close errors
214
- }
463
+ try { this._socket.close(); } catch { /* ignore */ }
215
464
  this._socket = null;
216
465
  }
217
- if (this._receiveLoop) {
218
- clearInterval(this._receiveLoop);
219
- this._receiveLoop = null;
220
- }
466
+ if (this._receiveLoop) { clearInterval(this._receiveLoop); this._receiveLoop = null; }
467
+ if (this._ackInterval) { clearInterval(this._ackInterval); this._ackInterval = null; }
468
+ if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; }
469
+ this._pendingAcks.clear();
470
+
221
471
  this.emit("disconnect", {});
222
472
  }
223
473
 
224
474
  /**
225
- * Send a RakNet-framed packet. Not implemented — framing logic needed.
226
- * Accepts { opcode, ...fields } and encodes via encodePacket().
475
+ * Send a Roblox game packet (opcode 0x80+).
476
+ * Handles RakNet framing, reliability, sequencing, and splitting.
227
477
  */
228
478
  send(packet) {
229
479
  if (!this._connected) {
@@ -231,18 +481,335 @@ export class RakNetTransport extends Transport {
231
481
  }
232
482
 
233
483
  const encoded = encodePacket(packet);
234
- throw new NotImplementedError(
235
- `RakNet.send for packet opcode 0x${packet.opcode.toString(16)} (${
236
- PACKET_NAMES[packet.opcode] ?? "unknown"
237
- }). ` +
238
- "To implement: wrap the encoded buffer in a RakNet frame (reliability, " +
239
- "sequencing, split size) and write it to the socket."
240
- );
484
+ const payload = encoded.buffer;
485
+
486
+ // Split if larger than MTU
487
+ if (payload.byteLength > this._mtu - 100) {
488
+ return this._sendSplit(payload);
489
+ }
490
+
491
+ return this._sendFrame(payload, {
492
+ reliability: RELIABILITY.RELIABLE_ORDERED,
493
+ orderingChannel: 0,
494
+ orderingIndex: this._orderingIndices[0]++,
495
+ sequenceNumber: ++this._sendSeq,
496
+ });
241
497
  }
242
498
 
243
- /**
244
- * Register an event listener.
245
- */
499
+ // ─── Internal: Socket & Receive Loop ────────────────────────────────
500
+
501
+ _createSocket() {
502
+ // Node.js dgram socket (UDP)
503
+ const dgram = require("node:dgram");
504
+ const socket = dgram.createSocket("udp4");
505
+
506
+ socket.on("message", (msg, rinfo) => {
507
+ this._handleMessage(msg, rinfo);
508
+ });
509
+
510
+ socket.on("error", (err) => {
511
+ this.emit("error", new TransportError(`Socket error: ${err.message}`));
512
+ });
513
+
514
+ socket.on("close", () => {
515
+ if (this._connected) {
516
+ this._connected = false;
517
+ this.emit("disconnect", { reason: "socket_closed" });
518
+ }
519
+ });
520
+
521
+ return socket;
522
+ }
523
+
524
+ _startReceiveLoop() {
525
+ // Handled by socket.on("message") event
526
+ }
527
+
528
+ _handleMessage(buffer, rinfo) {
529
+ // Verify source
530
+ if (rinfo.address !== this._remoteAddr || rinfo.port !== this._remotePort) return;
531
+
532
+ this._lastRecv = Date.now();
533
+
534
+ const frame = parseRakNetFrame(buffer);
535
+ if (!frame) return;
536
+
537
+ switch (frame.frameType) {
538
+ case "game":
539
+ this._handleGameFrame(frame);
540
+ break;
541
+ case "builtin":
542
+ this._handleBuiltinFrame(frame);
543
+ break;
544
+ }
545
+ }
546
+
547
+ _handleGameFrame(frame) {
548
+ // Handle ACKs for reliable packets we sent
549
+ if (frame.reliability >= RELIABILITY.RELIABLE && frame.reliableSeq !== null) {
550
+ this._handleAck(frame.reliableSeq);
551
+ }
552
+
553
+ // Send ACK for reliable packets we received
554
+ if (frame.reliability >= RELIABILITY.RELIABLE) {
555
+ this._sendAck(frame.reliableSeq);
556
+ }
557
+
558
+ // Decode and emit Roblox packet
559
+ if (frame.payload && frame.payload.byteLength > 0) {
560
+ this._emitPacket(frame.payload);
561
+ }
562
+ }
563
+
564
+ _handleBuiltinFrame(frame) {
565
+ switch (frame.name) {
566
+ case "connection_accepted":
567
+ this._handleConnectionAccepted(frame.payload);
568
+ break;
569
+ case "new_connection":
570
+ this._handleNewConnection(frame.payload);
571
+ break;
572
+ case "disconnect":
573
+ case "connection_lost":
574
+ this._connected = false;
575
+ this.emit("disconnect", { reason: frame.name });
576
+ break;
577
+ }
578
+ }
579
+
580
+ // ─── Internal: Handshake Steps ──────────────────────────────────────
581
+
582
+ _sendUnconnectedPing() {
583
+ return new Promise((resolve, reject) => {
584
+ const timeout = setTimeout(() => reject(new TransportError("Unconnected ping timeout")), 5000);
585
+
586
+ const onPong = (frame) => {
587
+ if (frame.frameType === "builtin" && frame.name === "unconnected_pong") {
588
+ clearTimeout(timeout);
589
+ this._socket.off("message", onMessage);
590
+ resolve({
591
+ serverGuid: frame.payload.byteLength >= 8
592
+ ? BigInt("0x" + Array.from(new Uint8Array(frame.payload.slice(0, 8))).map(b => b.toString(16).padStart(2, "0")).join(""))
593
+ : this._guid,
594
+ mtu: frame.payload.byteLength >= 10
595
+ ? new DataView(frame.payload.slice(8, 10)).getUint16(0, true)
596
+ : 1400,
597
+ });
598
+ }
599
+ };
600
+
601
+ const onMessage = (msg, rinfo) => {
602
+ const frame = parseRakNetFrame(msg);
603
+ if (frame) onPong(frame);
604
+ };
605
+
606
+ this._socket.on("message", onMessage);
607
+
608
+ // Build unconnected ping
609
+ const buf = new ArrayBuffer(1 + 8 + 8 + 1); // ID + clientGuid + timestamp + magic
610
+ const view = new DataView(buf);
611
+ view.setUint8(0, RAKNET.ID_UNCONNECTED_PING);
612
+ // Write client GUID (8 bytes)
613
+ const guidBytes = new Uint8Array(8);
614
+ for (let i = 0; i < 8; i++) guidBytes[i] = (this._guid >> (8 * i)) & 0xFF;
615
+ new Uint8Array(buf).set(guidBytes, 1);
616
+ // Timestamp
617
+ view.setBigUint64(9, BigInt(Date.now()), true);
618
+ // Magic (RakNet offline message ID)
619
+ const magic = new Uint8Array([0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78]);
620
+ new Uint8Array(buf).set(magic, 17);
621
+
622
+ this._socket.send(buf, 0, buf.byteLength, this._remotePort, this._remoteAddr);
623
+ });
624
+ }
625
+
626
+ _sendConnectionRequest() {
627
+ return new Promise((resolve, reject) => {
628
+ const timeout = setTimeout(() => reject(new TransportError("Connection request timeout")), 5000);
629
+
630
+ const onAccepted = (frame) => {
631
+ if (frame.frameType === "builtin" && frame.name === "connection_accepted") {
632
+ clearTimeout(timeout);
633
+ this._socket.off("message", onMessage);
634
+ resolve();
635
+ }
636
+ };
637
+
638
+ const onMessage = (msg, rinfo) => {
639
+ const frame = parseRakNetFrame(msg);
640
+ if (frame) onAccepted(frame);
641
+ };
642
+
643
+ this._socket.on("message", onMessage);
644
+
645
+ // Build connection request (simplified)
646
+ const buf = new ArrayBuffer(1 + 8 + 8 + 4 + 4 + 16); // ID + clientGuid + timestamp + useSecurity + mtu + offlineMessageId
647
+ const view = new DataView(buf);
648
+ view.setUint8(0, RAKNET.ID_CONNECTION_REQUEST);
649
+ // Client GUID
650
+ const guidBytes = new Uint8Array(8);
651
+ for (let i = 0; i < 8; i++) guidBytes[i] = (this._guid >> (8 * i)) & 0xFF;
652
+ new Uint8Array(buf).set(guidBytes, 1);
653
+ // Timestamp
654
+ view.setBigUint64(9, BigInt(Date.now()), true);
655
+ // Use security (0 = none)
656
+ view.setUint32(17, 0, true);
657
+ // MTU
658
+ view.setUint32(21, this._mtu, true);
659
+ // Offline message ID (magic)
660
+ const magic = new Uint8Array([0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78]);
661
+ new Uint8Array(buf).set(magic, 25);
662
+
663
+ this._socket.send(buf, 0, buf.byteLength, this._remotePort, this._remoteAddr);
664
+ });
665
+ }
666
+
667
+ _waitForConnectionAccepted() {
668
+ return new Promise((resolve, reject) => {
669
+ const timeout = setTimeout(() => reject(new TransportError("Connection accepted timeout")), 10000);
670
+
671
+ const onAccepted = (frame) => {
672
+ if (frame.frameType === "builtin" && frame.name === "connection_accepted") {
673
+ clearTimeout(timeout);
674
+ this._socket.off("message", onMessage);
675
+ resolve();
676
+ }
677
+ };
678
+
679
+ const onMessage = (msg, rinfo) => {
680
+ const frame = parseRakNetFrame(msg);
681
+ if (frame) onAccepted(frame);
682
+ };
683
+
684
+ this._socket.on("message", onMessage);
685
+ });
686
+ }
687
+
688
+ _handleConnectionAccepted(payload) {
689
+ // Extract server GUID, MTU, etc.
690
+ if (payload.byteLength >= 8) {
691
+ this._remoteGuid = BigInt("0x" + Array.from(new Uint8Array(payload.slice(0, 8))).map(b => b.toString(16).padStart(2, "0")).join(""));
692
+ }
693
+ if (payload.byteLength >= 10) {
694
+ this._mtu = new DataView(payload.slice(8, 10)).getUint16(0, true);
695
+ }
696
+ }
697
+
698
+ _handleNewConnection(payload) {
699
+ // Server confirms connection
700
+ }
701
+
702
+ // ─── Internal: Frame Sending ────────────────────────────────────────
703
+
704
+ _sendFrame(payload, options) {
705
+ const frame = buildRakNetFrame(payload, options);
706
+ this._socket.send(frame, 0, frame.byteLength, this._remotePort, this._remoteAddr);
707
+
708
+ // Track for ACK if reliable
709
+ if (options.reliability >= RELIABILITY.RELIABLE) {
710
+ this._pendingAcks.set(options.sequenceNumber, {
711
+ frame,
712
+ options,
713
+ retries: 0,
714
+ sentAt: Date.now(),
715
+ });
716
+ }
717
+
718
+ return { sent: true, sequenceNumber: options.sequenceNumber };
719
+ }
720
+
721
+ _sendSplit(payload) {
722
+ const maxChunk = this._mtu - 100;
723
+ const chunks = [];
724
+ for (let i = 0; i < payload.byteLength; i += maxChunk) {
725
+ chunks.push(payload.slice(i, i + maxChunk));
726
+ }
727
+
728
+ const splitId = Math.floor(Math.random() * 0xFFFFFFFF);
729
+ const results = [];
730
+
731
+ for (let i = 0; i < chunks.length; i++) {
732
+ const result = this._sendFrame(chunks[i], {
733
+ reliability: RELIABILITY.RELIABLE_ORDERED,
734
+ orderingChannel: 0,
735
+ orderingIndex: this._orderingIndices[0]++,
736
+ sequenceNumber: ++this._sendSeq,
737
+ isSplit: true,
738
+ splitCount: chunks.length,
739
+ splitId,
740
+ splitIndex: i,
741
+ });
742
+ results.push(result);
743
+ }
744
+
745
+ return { sent: true, parts: results };
746
+ }
747
+
748
+ // ─── Internal: ACK Handling ────────────────────────────────────────
749
+
750
+ _startAckLoop() {
751
+ this._ackInterval = setInterval(() => {
752
+ const now = Date.now();
753
+ for (const [seq, entry] of this._pendingAcks) {
754
+ // Resend if no ACK after 100ms, max 5 retries
755
+ if (now - entry.sentAt > 100 && entry.retries < 5) {
756
+ this._socket.send(entry.frame, 0, entry.frame.byteLength, this._remotePort, this._remoteAddr);
757
+ entry.retries++;
758
+ entry.sentAt = now;
759
+ } else if (entry.retries >= 5) {
760
+ // Give up
761
+ this._pendingAcks.delete(seq);
762
+ this.emit("error", new TransportError(`Packet ${seq} failed after 5 retries`));
763
+ }
764
+ }
765
+ }, 50);
766
+ }
767
+
768
+ _sendAck(seq) {
769
+ const buf = new ArrayBuffer(1 + 4);
770
+ const view = new DataView(buf);
771
+ view.setUint8(0, 0xC0); // ACK packet type (custom)
772
+ view.setUint32(1, seq, true);
773
+ this._socket.send(buf, 0, buf.byteLength, this._remotePort, this._remoteAddr);
774
+ }
775
+
776
+ _handleAck(seq) {
777
+ this._pendingAcks.delete(seq);
778
+ }
779
+
780
+ // ─── Internal: Ping/Pong ────────────────────────────────────────────
781
+
782
+ _startPingLoop() {
783
+ this._pingInterval = setInterval(() => {
784
+ if (Date.now() - this._lastRecv > 10000) {
785
+ this.emit("error", new TransportError("Connection timeout"));
786
+ this.disconnect();
787
+ return;
788
+ }
789
+
790
+ // Send connected ping
791
+ const buf = new ArrayBuffer(1 + 8);
792
+ const view = new DataView(buf);
793
+ view.setUint8(0, RAKNET.ID_CONNECTED_PING);
794
+ view.setBigUint64(1, BigInt(Date.now()), true);
795
+ this._socket.send(buf, 0, buf.byteLength, this._remotePort, this._remoteAddr);
796
+ }, 5000);
797
+ }
798
+
799
+ // ─── Internal: DNS Resolution ──────────────────────────────────────
800
+
801
+ async _resolveHost(host) {
802
+ const dns = require("node:dns/promises");
803
+ try {
804
+ const records = await dns.resolve4(host);
805
+ return records;
806
+ } catch {
807
+ return [];
808
+ }
809
+ }
810
+
811
+ // ─── EventEmitter Methods ──────────────────────────────────────────
812
+
246
813
  on(event, listener) {
247
814
  if (typeof this._listeners === "undefined") this._listeners = {};
248
815
  if (!this._listeners[event]) this._listeners[event] = [];
@@ -250,9 +817,6 @@ export class RakNetTransport extends Transport {
250
817
  return () => this.off(event, listener);
251
818
  }
252
819
 
253
- /**
254
- * Register a one-time listener.
255
- */
256
820
  once(event, listener) {
257
821
  const unsubscribe = this.on(event, (...args) => {
258
822
  unsubscribe();
@@ -261,31 +825,21 @@ export class RakNetTransport extends Transport {
261
825
  return unsubscribe;
262
826
  }
263
827
 
264
- /**
265
- * Remove a listener.
266
- */
267
828
  off(event, listener) {
268
829
  if (!this._listeners || !this._listeners[event]) return;
269
830
  const idx = this._listeners[event].indexOf(listener);
270
831
  if (idx !== -1) this._listeners[event].splice(idx, 1);
271
832
  }
272
833
 
273
- /**
274
- * Emit an event to all registered listeners.
275
- */
276
834
  emit(event, data) {
277
835
  if (!this._listeners || !this._listeners[event]) return;
278
836
  for (const listener of this._listeners[event]) {
279
- try {
280
- listener(data);
281
- } catch (_) {
282
- // listener errors shouldn't break the transport
283
- }
837
+ try { listener(data); } catch { /* ignore */ }
284
838
  }
285
839
  }
286
840
 
287
841
  /**
288
- * Internal: emit a decoded packet event.
842
+ * Internal: emit decoded Roblox packet event.
289
843
  */
290
844
  _emitPacket(buffer) {
291
845
  try {
@@ -299,5 +853,5 @@ export class RakNetTransport extends Transport {
299
853
  }
300
854
  }
301
855
 
302
- export { encodePacket, decodePacket, isPacketDefined };
303
- export default RakNetTransport;
856
+ export { encodePacket, decodePacket, isPacketDefined, RakNetTransport };
857
+ export default RakNetTransport;