deepslate-protocol 0.3.1

Minecraft protocol primitives for the Deepslate proxy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Login state packets.

use bytes::{Buf, BufMut, Bytes};
use uuid::Uuid;

use crate::types::{self, GameProfile, ProfileProperty, ProtocolError};
use crate::varint;

use super::Packet;

/// Maximum length (in bytes) for an RSA-encrypted field.
///
/// Minecraft uses 1024-bit RSA, producing 128-byte ciphertext. We allow up to
/// 256 bytes to accommodate potential future key-size changes while still
/// rejecting obviously malformed packets early.
const MAX_ENCRYPTED_FIELD: usize = 256;

/// Serverbound login start (packet ID 0x00 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginStartPacket {
    /// The player's username.
    pub username: String,
    /// The player's UUID (sent by client since 1.19.1).
    pub uuid: Uuid,
}

impl Packet for LoginStartPacket {
    const PACKET_ID: i32 = 0x00;

    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let username = types::read_string_max(buf, 16)?;
        let uuid = types::read_uuid(buf)?;
        Ok(Self { username, uuid })
    }

    fn encode(&self, buf: &mut impl BufMut) {
        types::write_string(buf, &self.username);
        types::write_uuid(buf, self.uuid);
    }
}

/// Clientbound encryption request (packet ID 0x01 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionRequestPacket {
    /// Server ID (empty string for modern Minecraft).
    pub server_id: String,
    /// DER-encoded RSA public key.
    pub public_key: Vec<u8>,
    /// Random verify token (4 bytes).
    pub verify_token: Vec<u8>,
    /// Whether the server should authenticate the player (1.20.5+).
    pub should_authenticate: bool,
}

impl Packet for EncryptionRequestPacket {
    const PACKET_ID: i32 = 0x01;

    #[allow(clippy::cast_sign_loss)]
    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let server_id = types::read_string_max(buf, 20)?;
        let pk_len = varint::read_var_int(buf)? as usize;
        if pk_len > MAX_ENCRYPTED_FIELD {
            return Err(ProtocolError::ByteArrayTooLong {
                length: pk_len,
                max: MAX_ENCRYPTED_FIELD,
            });
        }
        if buf.remaining() < pk_len {
            return Err(ProtocolError::UnexpectedEof);
        }
        let public_key = buf.copy_to_bytes(pk_len).to_vec();
        let vt_len = varint::read_var_int(buf)? as usize;
        if vt_len > MAX_ENCRYPTED_FIELD {
            return Err(ProtocolError::ByteArrayTooLong {
                length: vt_len,
                max: MAX_ENCRYPTED_FIELD,
            });
        }
        if buf.remaining() < vt_len {
            return Err(ProtocolError::UnexpectedEof);
        }
        let verify_token = buf.copy_to_bytes(vt_len).to_vec();
        let should_authenticate = if buf.has_remaining() {
            buf.get_u8() != 0
        } else {
            true
        };
        Ok(Self {
            server_id,
            public_key,
            verify_token,
            should_authenticate,
        })
    }

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    fn encode(&self, buf: &mut impl BufMut) {
        types::write_string(buf, &self.server_id);
        varint::write_var_int(buf, self.public_key.len() as i32);
        buf.put_slice(&self.public_key);
        varint::write_var_int(buf, self.verify_token.len() as i32);
        buf.put_slice(&self.verify_token);
        buf.put_u8(u8::from(self.should_authenticate));
    }
}

/// Serverbound encryption response (packet ID 0x01 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionResponsePacket {
    /// RSA-encrypted shared secret.
    pub shared_secret: Vec<u8>,
    /// RSA-encrypted verify token.
    pub verify_token: Vec<u8>,
}

impl Packet for EncryptionResponsePacket {
    const PACKET_ID: i32 = 0x01;

    #[allow(clippy::cast_sign_loss)]
    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let ss_len = varint::read_var_int(buf)? as usize;
        if ss_len > MAX_ENCRYPTED_FIELD {
            return Err(ProtocolError::ByteArrayTooLong {
                length: ss_len,
                max: MAX_ENCRYPTED_FIELD,
            });
        }
        if buf.remaining() < ss_len {
            return Err(ProtocolError::UnexpectedEof);
        }
        let shared_secret = buf.copy_to_bytes(ss_len).to_vec();
        let vt_len = varint::read_var_int(buf)? as usize;
        if vt_len > MAX_ENCRYPTED_FIELD {
            return Err(ProtocolError::ByteArrayTooLong {
                length: vt_len,
                max: MAX_ENCRYPTED_FIELD,
            });
        }
        if buf.remaining() < vt_len {
            return Err(ProtocolError::UnexpectedEof);
        }
        let verify_token = buf.copy_to_bytes(vt_len).to_vec();
        Ok(Self {
            shared_secret,
            verify_token,
        })
    }

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    fn encode(&self, buf: &mut impl BufMut) {
        varint::write_var_int(buf, self.shared_secret.len() as i32);
        buf.put_slice(&self.shared_secret);
        varint::write_var_int(buf, self.verify_token.len() as i32);
        buf.put_slice(&self.verify_token);
    }
}

/// Clientbound login success (packet ID 0x02 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginSuccessPacket {
    /// The player's game profile.
    pub uuid: Uuid,
    /// The player's username.
    pub username: String,
    /// Profile properties.
    pub properties: Vec<ProfileProperty>,
}

impl LoginSuccessPacket {
    /// Create from a game profile.
    #[must_use]
    pub fn from_profile(profile: &GameProfile) -> Self {
        Self {
            uuid: profile.id,
            username: profile.name.clone(),
            properties: profile.properties.clone(),
        }
    }
}

impl Packet for LoginSuccessPacket {
    const PACKET_ID: i32 = 0x02;

    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let uuid = types::read_uuid(buf)?;
        let username = types::read_string_max(buf, 16)?;
        let properties = types::read_properties(buf)?;
        Ok(Self {
            uuid,
            username,
            properties,
        })
    }

    fn encode(&self, buf: &mut impl BufMut) {
        types::write_uuid(buf, self.uuid);
        types::write_string(buf, &self.username);
        types::write_properties(buf, &self.properties);
    }
}

/// Clientbound set compression (packet ID 0x03 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetCompressionPacket {
    /// Compression threshold in bytes. Packets larger than this will be compressed.
    /// A value of -1 disables compression.
    pub threshold: i32,
}

impl Packet for SetCompressionPacket {
    const PACKET_ID: i32 = 0x03;

    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let threshold = varint::read_var_int(buf)?;
        Ok(Self { threshold })
    }

    fn encode(&self, buf: &mut impl BufMut) {
        varint::write_var_int(buf, self.threshold);
    }
}

/// Clientbound login plugin message (packet ID 0x04 in LOGIN state).
/// Used by Velocity's modern forwarding protocol.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginPluginRequestPacket {
    /// Message ID for correlating request/response.
    pub message_id: i32,
    /// Channel identifier (e.g., "`velocity:player_info`").
    pub channel: String,
    /// Plugin-specific payload data.
    pub data: Bytes,
}

impl Packet for LoginPluginRequestPacket {
    const PACKET_ID: i32 = 0x04;

    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let message_id = varint::read_var_int(buf)?;
        let channel = types::read_string(buf)?;
        let data = buf.copy_to_bytes(buf.remaining());
        Ok(Self {
            message_id,
            channel,
            data,
        })
    }

    fn encode(&self, buf: &mut impl BufMut) {
        varint::write_var_int(buf, self.message_id);
        types::write_string(buf, &self.channel);
        buf.put_slice(&self.data);
    }
}

/// Serverbound login plugin response (packet ID 0x02 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginPluginResponsePacket {
    /// Message ID matching the request.
    pub message_id: i32,
    /// Whether the client understood the request.
    pub successful: bool,
    /// Response payload (only meaningful if successful).
    pub data: Bytes,
}

impl Packet for LoginPluginResponsePacket {
    const PACKET_ID: i32 = 0x02;

    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let message_id = varint::read_var_int(buf)?;
        if !buf.has_remaining() {
            return Err(ProtocolError::UnexpectedEof);
        }
        let successful = buf.get_u8() != 0;
        let data = if successful {
            buf.copy_to_bytes(buf.remaining())
        } else {
            Bytes::new()
        };
        Ok(Self {
            message_id,
            successful,
            data,
        })
    }

    fn encode(&self, buf: &mut impl BufMut) {
        varint::write_var_int(buf, self.message_id);
        buf.put_u8(u8::from(self.successful));
        if self.successful {
            buf.put_slice(&self.data);
        }
    }
}

/// Serverbound login acknowledged (packet ID 0x03 in LOGIN state).
/// Sent by the client after receiving `LoginSuccess`, triggers transition to CONFIG state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginAcknowledgedPacket;

impl Packet for LoginAcknowledgedPacket {
    const PACKET_ID: i32 = 0x03;

    fn decode(_buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        Ok(Self)
    }

    fn encode(&self, _buf: &mut impl BufMut) {}
}

/// Clientbound disconnect during login (packet ID 0x00 in LOGIN state).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginDisconnectPacket {
    /// JSON text component with the disconnect reason.
    pub reason: String,
}

impl Packet for LoginDisconnectPacket {
    const PACKET_ID: i32 = 0x00;

    fn decode(buf: &mut impl Buf) -> Result<Self, ProtocolError> {
        let reason = types::read_string(buf)?;
        Ok(Self { reason })
    }

    fn encode(&self, buf: &mut impl BufMut) {
        types::write_string(buf, &self.reason);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    fn profile_property_strategy() -> impl Strategy<Value = ProfileProperty> {
        (
            ".{0,32}",                                // name
            ".{0,1024}",                              // value
            prop::option::weighted(0.5, ".{0,1024}"), // signature
        )
            .prop_map(|(name, value, signature)| ProfileProperty {
                name,
                value,
                signature,
            })
    }

    proptest! {
        #[test]
        fn login_start_roundtrip(
            username in ".{0,16}",
            u in any::<u128>()
        ) {
            let packet = LoginStartPacket {
                username,
                uuid: Uuid::from_u128(u),
            };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = LoginStartPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn encryption_request_roundtrip(
            server_id in ".{0,20}",
            public_key in prop::collection::vec(any::<u8>(), 0..=MAX_ENCRYPTED_FIELD),
            verify_token in prop::collection::vec(any::<u8>(), 0..=MAX_ENCRYPTED_FIELD),
            should_authenticate in any::<bool>()
        ) {
            let packet = EncryptionRequestPacket {
                server_id,
                public_key,
                verify_token,
                should_authenticate,
            };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = EncryptionRequestPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn encryption_response_roundtrip(
            shared_secret in prop::collection::vec(any::<u8>(), 0..=MAX_ENCRYPTED_FIELD),
            verify_token in prop::collection::vec(any::<u8>(), 0..=MAX_ENCRYPTED_FIELD)
        ) {
            let packet = EncryptionResponsePacket {
                shared_secret,
                verify_token,
            };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = EncryptionResponsePacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn login_success_roundtrip(
            u in any::<u128>(),
            username in ".{0,16}",
            properties in prop::collection::vec(profile_property_strategy(), 0..4)
        ) {
            let packet = LoginSuccessPacket {
                uuid: Uuid::from_u128(u),
                username,
                properties,
            };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = LoginSuccessPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn set_compression_roundtrip(threshold in any::<i32>()) {
            let packet = SetCompressionPacket { threshold };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = SetCompressionPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn login_plugin_request_roundtrip(
            message_id in any::<i32>(),
            channel in ".{0,128}",
            data in prop::collection::vec(any::<u8>(), 0..1024)
        ) {
            let packet = LoginPluginRequestPacket {
                message_id,
                channel,
                data: Bytes::from(data),
            };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = LoginPluginRequestPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn login_plugin_response_roundtrip(
            message_id in any::<i32>(),
            successful in any::<bool>(),
            data in prop::collection::vec(any::<u8>(), 0..1024)
        ) {
            let packet = LoginPluginResponsePacket {
                message_id,
                successful,
                data: if successful { Bytes::from(data) } else { Bytes::new() },
            };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = LoginPluginResponsePacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn login_acknowledged_roundtrip(packet in Just(LoginAcknowledgedPacket)) {
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = LoginAcknowledgedPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }

        #[test]
        fn login_disconnect_roundtrip(reason in ".{0,1024}") {
            let packet = LoginDisconnectPacket { reason };
            let mut buf = Vec::new();
            packet.encode(&mut buf);
            let decoded = LoginDisconnectPacket::decode(&mut &buf[..]).unwrap();
            prop_assert_eq!(decoded, packet);
        }
    }

    #[test]
    fn encryption_request_rejects_oversized_public_key() {
        let packet = EncryptionRequestPacket {
            server_id: String::new(),
            public_key: vec![0xAA; MAX_ENCRYPTED_FIELD + 1],
            verify_token: vec![0xBB; 4],
            should_authenticate: true,
        };
        let mut buf = Vec::new();
        packet.encode(&mut buf);
        let result = EncryptionRequestPacket::decode(&mut &buf[..]);
        assert!(matches!(
            result,
            Err(ProtocolError::ByteArrayTooLong {
                length,
                max: MAX_ENCRYPTED_FIELD,
            }) if length == MAX_ENCRYPTED_FIELD + 1
        ));
    }

    #[test]
    fn encryption_request_rejects_oversized_verify_token() {
        let packet = EncryptionRequestPacket {
            server_id: String::new(),
            public_key: vec![0xAA; 128],
            verify_token: vec![0xBB; MAX_ENCRYPTED_FIELD + 1],
            should_authenticate: true,
        };
        let mut buf = Vec::new();
        packet.encode(&mut buf);
        let result = EncryptionRequestPacket::decode(&mut &buf[..]);
        assert!(matches!(
            result,
            Err(ProtocolError::ByteArrayTooLong {
                length,
                max: MAX_ENCRYPTED_FIELD,
            }) if length == MAX_ENCRYPTED_FIELD + 1
        ));
    }

    #[test]
    fn encryption_response_rejects_oversized_shared_secret() {
        let packet = EncryptionResponsePacket {
            shared_secret: vec![0xAA; MAX_ENCRYPTED_FIELD + 1],
            verify_token: vec![0xBB; 4],
        };
        let mut buf = Vec::new();
        packet.encode(&mut buf);
        let result = EncryptionResponsePacket::decode(&mut &buf[..]);
        assert!(matches!(
            result,
            Err(ProtocolError::ByteArrayTooLong {
                length,
                max: MAX_ENCRYPTED_FIELD,
            }) if length == MAX_ENCRYPTED_FIELD + 1
        ));
    }

    #[test]
    fn encryption_response_rejects_oversized_verify_token() {
        let packet = EncryptionResponsePacket {
            shared_secret: vec![0xAA; 128],
            verify_token: vec![0xBB; MAX_ENCRYPTED_FIELD + 1],
        };
        let mut buf = Vec::new();
        packet.encode(&mut buf);
        let result = EncryptionResponsePacket::decode(&mut &buf[..]);
        assert!(matches!(
            result,
            Err(ProtocolError::ByteArrayTooLong {
                length,
                max: MAX_ENCRYPTED_FIELD,
            }) if length == MAX_ENCRYPTED_FIELD + 1
        ));
    }
}