Skip to main content

elura_protocol/
lib.rs

1//! Standalone Rust implementation of the public Elura ELR2 protocol.
2
3use std::fmt;
4#[cfg(feature = "tokio-codec")]
5use std::io;
6
7use bytes::{BufMut, Bytes, BytesMut};
8use prost::Message;
9use serde::{Deserialize, Serialize};
10#[cfg(feature = "tokio-codec")]
11use tokio_util::codec::{Decoder, Encoder};
12
13pub const ELR2_MAGIC: u32 = 0x454c5232;
14pub const ELR2_VERSION: u16 = 2;
15pub const ELR2_HEADER_LENGTH: usize = 28;
16pub const DEFAULT_MAX_PAYLOAD: usize = 1 << 20;
17pub const ABSOLUTE_MAX_PAYLOAD: usize = 64 << 20;
18pub const PROTOCOL_IDENTIFIER: &str = "elura.v2";
19
20pub struct EluraRoutes;
21
22impl EluraRoutes {
23    pub const AUTHENTICATE: u32 = 1;
24    pub const HEARTBEAT: u32 = 2;
25    pub const RENEW_RECONNECT_TICKET: u32 = 3;
26    pub const SESSION_CONTROL: u32 = 4;
27    pub const FIRST_APPLICATION: u32 = 100;
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[repr(u8)]
32pub enum FrameKind {
33    Request = 1,
34    Response = 2,
35    Push = 3,
36    Error = 4,
37}
38
39impl TryFrom<u8> for FrameKind {
40    type Error = Elr2ProtocolError;
41
42    fn try_from(value: u8) -> Result<Self, Elr2ProtocolError> {
43        match value {
44            1 => Ok(Self::Request),
45            2 => Ok(Self::Response),
46            3 => Ok(Self::Push),
47            4 => Ok(Self::Error),
48            _ => Err(Elr2ProtocolError::new("unknown frame kind")),
49        }
50    }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Elr2Frame {
55    pub kind: FrameKind,
56    pub flags: u8,
57    pub route: u32,
58    pub request_id: u64,
59    pub sequence: u32,
60    pub payload: Bytes,
61}
62
63impl Elr2Frame {
64    pub fn request(route: u32, request_id: u64, payload: impl Into<Bytes>) -> ProtocolResult<Self> {
65        Self::request_with_sequence(route, request_id, 0, payload)
66    }
67
68    pub fn request_with_sequence(
69        route: u32,
70        request_id: u64,
71        sequence: u32,
72        payload: impl Into<Bytes>,
73    ) -> ProtocolResult<Self> {
74        Self::create(
75            FrameKind::Request,
76            route,
77            request_id,
78            sequence,
79            payload.into(),
80        )
81    }
82
83    pub fn response(request: &Self, payload: impl Into<Bytes>) -> ProtocolResult<Self> {
84        Self::from_request(FrameKind::Response, request, payload.into())
85    }
86
87    pub fn error(request: &Self, payload: impl Into<Bytes>) -> ProtocolResult<Self> {
88        Self::from_request(FrameKind::Error, request, payload.into())
89    }
90
91    pub fn push(route: u32, payload: impl Into<Bytes>) -> ProtocolResult<Self> {
92        Self::push_with_sequence(route, 0, payload)
93    }
94
95    pub fn push_with_sequence(
96        route: u32,
97        sequence: u32,
98        payload: impl Into<Bytes>,
99    ) -> ProtocolResult<Self> {
100        Self::create(FrameKind::Push, route, 0, sequence, payload.into())
101    }
102
103    fn from_request(kind: FrameKind, request: &Self, payload: Bytes) -> ProtocolResult<Self> {
104        if request.kind != FrameKind::Request {
105            return Err(Elr2ProtocolError::new(
106                "response source must be a request frame",
107            ));
108        }
109        Self::create(
110            kind,
111            request.route,
112            request.request_id,
113            request.sequence,
114            payload,
115        )
116    }
117
118    fn create(
119        kind: FrameKind,
120        route: u32,
121        request_id: u64,
122        sequence: u32,
123        payload: Bytes,
124    ) -> ProtocolResult<Self> {
125        let frame = Self {
126            kind,
127            flags: 0,
128            route,
129            request_id,
130            sequence,
131            payload,
132        };
133        Elr2Codec::validate(&frame, ABSOLUTE_MAX_PAYLOAD)?;
134        Ok(frame)
135    }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct Elr2ProtocolError {
140    message: String,
141}
142
143impl Elr2ProtocolError {
144    pub fn new(message: impl Into<String>) -> Self {
145        Self {
146            message: message.into(),
147        }
148    }
149}
150
151impl fmt::Display for Elr2ProtocolError {
152    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
153        formatter.write_str(&self.message)
154    }
155}
156
157impl std::error::Error for Elr2ProtocolError {}
158
159pub type ProtocolResult<T> = Result<T, Elr2ProtocolError>;
160
161#[derive(Debug, Clone)]
162pub struct Elr2Codec {
163    #[cfg(feature = "tokio-codec")]
164    max_payload: usize,
165}
166
167impl Elr2Codec {
168    #[cfg(feature = "tokio-codec")]
169    pub fn new(max_payload: usize) -> ProtocolResult<Self> {
170        validate_limit(max_payload)?;
171        Ok(Self { max_payload })
172    }
173
174    pub fn validate(frame: &Elr2Frame, max_payload: usize) -> ProtocolResult<()> {
175        validate_limit(max_payload)?;
176        if frame.payload.len() > max_payload {
177            return Err(Elr2ProtocolError::new("payload is too large"));
178        }
179        if frame.flags != 0 {
180            return Err(Elr2ProtocolError::new("unsupported frame flags"));
181        }
182        if frame.route == 0 {
183            return Err(Elr2ProtocolError::new("route must be non-zero"));
184        }
185        if frame.kind == FrameKind::Push {
186            if frame.request_id != 0 {
187                return Err(Elr2ProtocolError::new("push request id must be zero"));
188            }
189        } else if frame.request_id == 0 {
190            return Err(Elr2ProtocolError::new("request id must be non-zero"));
191        }
192        Ok(())
193    }
194
195    pub fn encode(frame: &Elr2Frame) -> ProtocolResult<Bytes> {
196        Self::encode_with_limit(frame, DEFAULT_MAX_PAYLOAD)
197    }
198
199    pub fn encode_with_limit(frame: &Elr2Frame, max_payload: usize) -> ProtocolResult<Bytes> {
200        Self::validate(frame, max_payload)?;
201        let mut output = BytesMut::with_capacity(ELR2_HEADER_LENGTH + frame.payload.len());
202        write_frame(frame, &mut output);
203        Ok(output.freeze())
204    }
205
206    pub fn decode(message: &[u8]) -> ProtocolResult<Elr2Frame> {
207        Self::decode_with_limit(message, DEFAULT_MAX_PAYLOAD)
208    }
209
210    pub fn decode_with_limit(message: &[u8], max_payload: usize) -> ProtocolResult<Elr2Frame> {
211        decode_bytes(Bytes::copy_from_slice(message), max_payload)
212    }
213
214    #[cfg(feature = "tokio-codec")]
215    fn decode_message(&self, message: Bytes) -> io::Result<Elr2Frame> {
216        decode_bytes(message, self.max_payload).map_err(protocol_io_error)
217    }
218}
219
220impl Default for Elr2Codec {
221    fn default() -> Self {
222        Self {
223            #[cfg(feature = "tokio-codec")]
224            max_payload: DEFAULT_MAX_PAYLOAD,
225        }
226    }
227}
228
229#[cfg(feature = "tokio-codec")]
230impl Decoder for Elr2Codec {
231    type Item = Elr2Frame;
232    type Error = io::Error;
233
234    fn decode(&mut self, source: &mut BytesMut) -> io::Result<Option<Self::Item>> {
235        if source.len() < ELR2_HEADER_LENGTH {
236            return Ok(None);
237        }
238        validate_header(&source[..ELR2_HEADER_LENGTH], self.max_payload)
239            .map_err(protocol_io_error)?;
240        let payload_length =
241            u32::from_be_bytes(source[24..28].try_into().expect("header length checked")) as usize;
242        let total = ELR2_HEADER_LENGTH + payload_length;
243        if source.len() < total {
244            source.reserve(total - source.len());
245            return Ok(None);
246        }
247        let message = source.split_to(total).freeze();
248        self.decode_message(message).map(Some)
249    }
250}
251
252#[cfg(feature = "tokio-codec")]
253impl Encoder<Elr2Frame> for Elr2Codec {
254    type Error = io::Error;
255
256    fn encode(&mut self, frame: Elr2Frame, destination: &mut BytesMut) -> io::Result<()> {
257        Self::validate(&frame, self.max_payload).map_err(protocol_io_error)?;
258        destination.reserve(ELR2_HEADER_LENGTH + frame.payload.len());
259        write_frame(&frame, destination);
260        Ok(())
261    }
262}
263
264fn validate_limit(max_payload: usize) -> ProtocolResult<()> {
265    if max_payload == 0 || max_payload > ABSOLUTE_MAX_PAYLOAD {
266        return Err(Elr2ProtocolError::new("max payload must be in 1..=64MiB"));
267    }
268    Ok(())
269}
270
271fn validate_header(header: &[u8], max_payload: usize) -> ProtocolResult<()> {
272    validate_limit(max_payload)?;
273    if header.len() < ELR2_HEADER_LENGTH {
274        return Err(Elr2ProtocolError::new("incomplete Elura frame"));
275    }
276    if u32::from_be_bytes(header[0..4].try_into().expect("header length checked")) != ELR2_MAGIC {
277        return Err(Elr2ProtocolError::new("invalid Elura magic"));
278    }
279    if u16::from_be_bytes(header[4..6].try_into().expect("header length checked")) != ELR2_VERSION {
280        return Err(Elr2ProtocolError::new("unsupported Elura version"));
281    }
282    FrameKind::try_from(header[6])?;
283    let payload_length =
284        u32::from_be_bytes(header[24..28].try_into().expect("header length checked")) as usize;
285    if payload_length > max_payload {
286        return Err(Elr2ProtocolError::new("Elura payload is too large"));
287    }
288    Ok(())
289}
290
291fn decode_bytes(message: Bytes, max_payload: usize) -> ProtocolResult<Elr2Frame> {
292    validate_header(&message, max_payload)?;
293    let payload_length =
294        u32::from_be_bytes(message[24..28].try_into().expect("header length checked")) as usize;
295    if message.len() != ELR2_HEADER_LENGTH + payload_length {
296        return Err(Elr2ProtocolError::new(
297            "Elura message must contain exactly one frame",
298        ));
299    }
300    let frame = Elr2Frame {
301        kind: FrameKind::try_from(message[6])?,
302        flags: message[7],
303        route: u32::from_be_bytes(message[8..12].try_into().expect("header length checked")),
304        request_id: u64::from_be_bytes(message[12..20].try_into().expect("header length checked")),
305        sequence: u32::from_be_bytes(message[20..24].try_into().expect("header length checked")),
306        payload: message.slice(ELR2_HEADER_LENGTH..),
307    };
308    Elr2Codec::validate(&frame, max_payload)?;
309    Ok(frame)
310}
311
312fn write_frame(frame: &Elr2Frame, output: &mut BytesMut) {
313    output.put_u32(ELR2_MAGIC);
314    output.put_u16(ELR2_VERSION);
315    output.put_u8(frame.kind as u8);
316    output.put_u8(frame.flags);
317    output.put_u32(frame.route);
318    output.put_u64(frame.request_id);
319    output.put_u32(frame.sequence);
320    output.put_u32(frame.payload.len() as u32);
321    output.put_slice(&frame.payload);
322}
323
324#[cfg(feature = "tokio-codec")]
325fn protocol_io_error(error: Elr2ProtocolError) -> io::Error {
326    io::Error::new(io::ErrorKind::InvalidData, error)
327}
328
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330pub struct Identity {
331    pub account_id: i64,
332    pub user_id: i64,
333    pub region_id: u32,
334    pub realm_id: u32,
335    pub generation: u64,
336}
337
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
339pub struct AuthenticateRequest {
340    pub ticket: String,
341}
342
343#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
344pub struct AuthenticateResponse {
345    pub session_id: String,
346    pub identity: Identity,
347    pub reconnect: ReconnectTicketResponse,
348}
349
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
351pub struct ReconnectTicketRenewalRequest {
352    pub ticket: String,
353}
354
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356pub struct ReconnectTicketResponse {
357    pub ticket: String,
358    pub expires_in_seconds: u64,
359}
360
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct ErrorEnvelope {
363    pub code: String,
364    pub message: String,
365    pub retryable: bool,
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub retry_after_ms: Option<u64>,
368}
369
370pub struct EluraProtocol;
371
372impl EluraProtocol {
373    pub fn authenticate(request_id: u64, ticket: impl Into<String>) -> ProtocolResult<Elr2Frame> {
374        json_request(
375            EluraRoutes::AUTHENTICATE,
376            request_id,
377            &AuthenticateRequest {
378                ticket: ticket.into(),
379            },
380        )
381    }
382
383    pub fn renew_reconnect_ticket(
384        request_id: u64,
385        ticket: impl Into<String>,
386    ) -> ProtocolResult<Elr2Frame> {
387        json_request(
388            EluraRoutes::RENEW_RECONNECT_TICKET,
389            request_id,
390            &ReconnectTicketRenewalRequest {
391                ticket: ticket.into(),
392            },
393        )
394    }
395
396    pub fn heartbeat_response(request: &Elr2Frame) -> ProtocolResult<Elr2Frame> {
397        if request.kind != FrameKind::Request
398            || request.route != EluraRoutes::HEARTBEAT
399            || request.sequence != 0
400            || !request.payload.is_empty()
401        {
402            return Err(Elr2ProtocolError::new("invalid heartbeat request"));
403        }
404        Elr2Frame::response(request, Bytes::new())
405    }
406
407    pub fn decode_authenticate(frame: &Elr2Frame) -> ProtocolResult<AuthenticateResponse> {
408        require_response(frame, EluraRoutes::AUTHENTICATE, "authentication")?;
409        let response: AuthenticateResponse = decode_json(&frame.payload)?;
410        validate_authentication_response(&response)?;
411        Ok(response)
412    }
413
414    pub fn decode_reconnect_ticket(frame: &Elr2Frame) -> ProtocolResult<ReconnectTicketResponse> {
415        require_response(
416            frame,
417            EluraRoutes::RENEW_RECONNECT_TICKET,
418            "reconnect ticket renewal",
419        )?;
420        let response: ReconnectTicketResponse = decode_json(&frame.payload)?;
421        validate_reconnect_ticket(&response)?;
422        Ok(response)
423    }
424
425    pub fn decode_error(frame: &Elr2Frame) -> ProtocolResult<ErrorEnvelope> {
426        if frame.kind != FrameKind::Error {
427            return Err(Elr2ProtocolError::new("expected an error frame"));
428        }
429        let envelope: ErrorEnvelope = decode_json(&frame.payload)?;
430        validate_error_envelope(&envelope)?;
431        Ok(envelope)
432    }
433
434    pub fn validate_client_frame(
435        frame: &Elr2Frame,
436        authenticated: bool,
437        pending_heartbeat: Option<u64>,
438    ) -> ProtocolResult<()> {
439        Elr2Codec::validate(frame, DEFAULT_MAX_PAYLOAD)?;
440        if frame.kind == FrameKind::Response && frame.route == EluraRoutes::HEARTBEAT {
441            if pending_heartbeat != Some(frame.request_id)
442                || frame.sequence != 0
443                || !frame.payload.is_empty()
444            {
445                return Err(Elr2ProtocolError::new(
446                    "heartbeat response does not match an outstanding request",
447                ));
448            }
449            return Ok(());
450        }
451        if frame.kind != FrameKind::Request {
452            return Err(Elr2ProtocolError::new(
453                "the Elura endpoint accepts request frames and heartbeat responses only",
454            ));
455        }
456        if frame.route < EluraRoutes::FIRST_APPLICATION && frame.sequence != 0 {
457            return Err(Elr2ProtocolError::new(
458                "framework requests must have sequence zero",
459            ));
460        }
461        let allowed = if authenticated {
462            frame.route == EluraRoutes::HEARTBEAT
463                || frame.route == EluraRoutes::RENEW_RECONNECT_TICKET
464                || frame.route >= EluraRoutes::FIRST_APPLICATION
465        } else {
466            frame.route == EluraRoutes::AUTHENTICATE
467        };
468        if !allowed {
469            return Err(Elr2ProtocolError::new(
470                "route is not allowed in the current session state",
471            ));
472        }
473        Ok(())
474    }
475}
476
477fn json_request<T: Serialize>(route: u32, request_id: u64, value: &T) -> ProtocolResult<Elr2Frame> {
478    let payload = serde_json::to_vec(value)
479        .map_err(|error| Elr2ProtocolError::new(format!("invalid Elura JSON payload: {error}")))?;
480    Elr2Frame::request(route, request_id, payload)
481}
482
483fn decode_json<T: for<'de> Deserialize<'de>>(payload: &[u8]) -> ProtocolResult<T> {
484    serde_json::from_slice(payload)
485        .map_err(|error| Elr2ProtocolError::new(format!("invalid Elura JSON payload: {error}")))
486}
487
488fn require_response(frame: &Elr2Frame, route: u32, description: &str) -> ProtocolResult<()> {
489    if frame.kind != FrameKind::Response || frame.route != route {
490        return Err(Elr2ProtocolError::new(format!(
491            "expected a {description} response frame"
492        )));
493    }
494    Ok(())
495}
496
497fn validate_authentication_response(response: &AuthenticateResponse) -> ProtocolResult<()> {
498    if response.session_id.is_empty()
499        || response.identity.account_id <= 0
500        || response.identity.user_id <= 0
501        || response.identity.region_id == 0
502        || response.identity.realm_id == 0
503        || response.identity.generation == 0
504    {
505        return Err(Elr2ProtocolError::new(
506            "invalid authentication response fields",
507        ));
508    }
509    validate_reconnect_ticket(&response.reconnect)
510}
511
512fn validate_reconnect_ticket(response: &ReconnectTicketResponse) -> ProtocolResult<()> {
513    if response.ticket.is_empty() || response.expires_in_seconds == 0 {
514        return Err(Elr2ProtocolError::new("invalid reconnect ticket fields"));
515    }
516    Ok(())
517}
518
519fn validate_error_envelope(envelope: &ErrorEnvelope) -> ProtocolResult<()> {
520    let valid_code = !envelope.code.is_empty()
521        && envelope.code.len() <= 64
522        && envelope
523            .code
524            .bytes()
525            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_');
526    if !valid_code || envelope.message.len() > 1024 || envelope.retry_after_ms == Some(0) {
527        return Err(Elr2ProtocolError::new("invalid error envelope fields"));
528    }
529    Ok(())
530}
531#[derive(Debug, Clone, Copy, PartialEq, Eq, prost::Enumeration)]
532#[repr(i32)]
533pub enum SessionControlAction {
534    Kick = 1,
535    AccountVersionChanged = 2,
536    DuplicateLogin = 3,
537    ForceLogout = 4,
538    ServerDraining = 5,
539}
540
541#[derive(Debug, Clone, PartialEq, Eq)]
542pub struct SessionControl {
543    pub action: SessionControlAction,
544    pub reason: String,
545}
546
547#[derive(Clone, PartialEq, Message)]
548struct SessionControlWire {
549    #[prost(enumeration = "SessionControlAction", tag = "1")]
550    action: i32,
551    #[prost(string, tag = "2")]
552    reason: String,
553}
554
555pub struct SessionControlCodec;
556
557impl SessionControlCodec {
558    pub fn encode(control: &SessionControl) -> ProtocolResult<Bytes> {
559        if control.reason.len() > 256 {
560            return Err(Elr2ProtocolError::new(
561                "Session Control reason exceeds 256 bytes",
562            ));
563        }
564        Ok(Bytes::from(
565            SessionControlWire {
566                action: control.action as i32,
567                reason: control.reason.clone(),
568            }
569            .encode_to_vec(),
570        ))
571    }
572
573    pub fn decode(payload: &[u8]) -> ProtocolResult<SessionControl> {
574        let wire = SessionControlWire::decode(payload).map_err(|error| {
575            Elr2ProtocolError::new(format!("invalid Session Control protobuf: {error}"))
576        })?;
577        let action = SessionControlAction::try_from(wire.action)
578            .map_err(|_| Elr2ProtocolError::new("unknown Session Control action"))?;
579        if wire.reason.len() > 256 {
580            return Err(Elr2ProtocolError::new(
581                "Session Control reason exceeds 256 bytes",
582            ));
583        }
584        Ok(SessionControl {
585            action,
586            reason: wire.reason,
587        })
588    }
589}