Skip to main content

azalea_client/plugins/
login.rs

1#[cfg(feature = "online-mode")]
2use azalea_auth::sessionserver::ClientSessionServerError;
3use azalea_protocol::{
4    connect::Proxy,
5    packets::login::{ClientboundHello, ServerboundCustomQueryAnswer, ServerboundKey},
6};
7use bevy_app::prelude::*;
8use bevy_ecs::prelude::*;
9use bevy_tasks::{IoTaskPool, Task, futures_lite::future};
10use thiserror::Error;
11use tracing::{debug, error, trace, warn};
12
13use super::{
14    connection::RawConnection,
15    packet::login::{ReceiveCustomQueryEvent, ReceiveHelloEvent, SendLoginPacketEvent},
16};
17use crate::{account::Account, join::ConnectOpts};
18
19/// Some systems that run during the `login` state.
20pub struct LoginPlugin;
21impl Plugin for LoginPlugin {
22    fn build(&self, app: &mut App) {
23        app.add_observer(handle_receive_hello_event)
24            .add_systems(Update, (poll_auth_task, reply_to_custom_queries));
25    }
26}
27
28fn handle_receive_hello_event(
29    receive_hello: On<ReceiveHelloEvent>,
30    mut commands: Commands,
31    query: Query<&ConnectOpts>,
32) {
33    let task_pool = IoTaskPool::get();
34
35    let account = receive_hello.account.clone();
36    let packet = receive_hello.packet.clone();
37    let client = receive_hello.entity;
38
39    // we store the auth proxy in the ConnectOpts component to make it easily
40    // configurable. that component should've definitely been inserted by now,
41    // but if it somehow wasn't then we should let the user know.
42    let connect_opts = if let Ok(opts) = query.get(client) {
43        opts.sessionserver_proxy.clone()
44    } else {
45        warn!("ConnectOpts component missing on a client ({client}) that got ReceiveHelloEvent");
46        None
47    };
48
49    let task = task_pool.spawn(async { auth_with_account(account, packet, connect_opts).await });
50    commands.entity(client).insert(AuthTask(task));
51}
52
53/// A marker component on our clients that indicates that the server is
54/// online-mode and the client has authenticated their join with Mojang.
55#[derive(Component)]
56pub struct IsAuthenticated;
57
58pub fn poll_auth_task(
59    mut commands: Commands,
60    mut query: Query<(Entity, &mut AuthTask, &mut RawConnection)>,
61) {
62    for (entity, mut auth_task, mut raw_conn) in query.iter_mut() {
63        if let Some(poll_res) = future::block_on(future::poll_once(&mut auth_task.0)) {
64            debug!("Finished auth");
65            commands
66                .entity(entity)
67                .remove::<AuthTask>()
68                .insert(IsAuthenticated);
69            match poll_res {
70                Ok((packet, private_key)) => {
71                    // we use this instead of SendLoginPacketEvent to ensure
72                    // that it's sent right before encryption is enabled. i
73                    // guess another option would be to make a Trigger+observer
74                    // for set_encryption_key; the current implementation is
75                    // simpler though.
76                    if let Err(e) = raw_conn.write(Default::default(), packet) {
77                        error!("Error sending key packet: {e:?}");
78                    }
79                    if let Some(net_conn) = raw_conn.net_conn() {
80                        net_conn.set_encryption_key(private_key);
81                    }
82                }
83                Err(err) => {
84                    error!("Error during authentication: {err:?}");
85                }
86            }
87        }
88    }
89}
90
91type PrivateKey = [u8; 16];
92
93#[derive(Component)]
94pub struct AuthTask(Task<Result<(ServerboundKey, PrivateKey), AuthWithAccountError>>);
95
96#[derive(Debug, Error)]
97pub enum AuthWithAccountError {
98    #[error("Failed to encrypt the challenge from the server for {0:?}")]
99    Encryption(ClientboundHello),
100    #[cfg(feature = "online-mode")]
101    #[error("{0}")]
102    SessionServer(#[from] ClientSessionServerError),
103    #[cfg(feature = "online-mode")]
104    #[error("Couldn't refresh access token: {0}")]
105    Auth(#[from] azalea_auth::AuthError),
106}
107
108pub async fn auth_with_account(
109    account: Account,
110    packet: ClientboundHello,
111    proxy: Option<Proxy>,
112) -> Result<(ServerboundKey, PrivateKey), AuthWithAccountError> {
113    let Ok(encrypt_res) = azalea_crypto::encrypt(&packet.public_key, &packet.challenge) else {
114        return Err(AuthWithAccountError::Encryption(packet));
115    };
116    let key_packet = ServerboundKey {
117        key_bytes: encrypt_res.encrypted_public_key,
118        encrypted_challenge: encrypt_res.encrypted_challenge,
119    };
120    let private_key = encrypt_res.secret_key;
121
122    #[cfg(not(feature = "online-mode"))]
123    let _ = (account, proxy);
124
125    #[cfg(feature = "online-mode")]
126    if packet.should_authenticate {
127        if account.access_token().is_none() {
128            // offline mode account, no need to do auth
129            return Ok((key_packet, private_key));
130        };
131
132        // keep track of the number of times we tried authenticating so we can
133        // give up after too many
134        let mut attempts: usize = 1;
135
136        let proxy = proxy.map(Proxy::into);
137
138        while let Err(err) = {
139            let proxy = proxy.clone();
140
141            // this is necessary since reqwest usually depends on tokio and
142            // we're using `futures` here
143            async_compat::Compat::new(async {
144                account
145                    .join(&packet.public_key, &private_key, &packet.server_id, proxy)
146                    .await
147            })
148            .await
149        } {
150            if attempts >= 2 {
151                // if this is the second attempt and we failed
152                // both times, give up
153                return Err(err.into());
154            }
155            if matches!(
156                err,
157                ClientSessionServerError::InvalidSession
158                    | ClientSessionServerError::ForbiddenOperation
159            ) {
160                // uh oh, we got an invalid session and have
161                // to reauthenticate now
162
163                async_compat::Compat::new(account.refresh()).await?;
164            } else {
165                return Err(err.into());
166            }
167            attempts += 1;
168        }
169    }
170
171    Ok((key_packet, private_key))
172}
173
174pub fn reply_to_custom_queries(
175    mut commands: Commands,
176    mut events: MessageReader<ReceiveCustomQueryEvent>,
177) {
178    for event in events.read() {
179        trace!("Maybe replying to custom query: {event:?}");
180        if event.disabled {
181            continue;
182        }
183
184        commands.trigger(SendLoginPacketEvent::new(
185            event.entity,
186            ServerboundCustomQueryAnswer {
187                transaction_id: event.packet.transaction_id,
188                data: None,
189            },
190        ));
191    }
192}