azalea_client/plugins/
login.rs1#[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
19pub 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 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#[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 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 return Ok((key_packet, private_key));
130 };
131
132 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 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 return Err(err.into());
154 }
155 if matches!(
156 err,
157 ClientSessionServerError::InvalidSession
158 | ClientSessionServerError::ForbiddenOperation
159 ) {
160 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}