Skip to main content

azalea_client/plugins/
chat_signing.rs

1use std::time::{Duration, Instant};
2
3use azalea_auth::certs::{Certificates, FetchCertificatesError};
4use azalea_protocol::packets::game::{
5    ServerboundChatSessionUpdate,
6    s_chat_session_update::{ProfilePublicKeyData, RemoteChatSessionData},
7};
8use bevy_app::prelude::*;
9use bevy_ecs::prelude::*;
10use bevy_tasks::{IoTaskPool, Task, futures_lite::future};
11use chrono::Utc;
12use tracing::{debug, error};
13use uuid::Uuid;
14
15use super::{client_chat, login::IsAuthenticated, packet::game::SendGamePacketEvent};
16use crate::{InGameState, account::Account};
17
18pub struct ChatSigningPlugin;
19impl Plugin for ChatSigningPlugin {
20    fn build(&self, app: &mut App) {
21        app.add_systems(
22            Update,
23            (
24                request_certs_if_needed,
25                poll_request_certs_task,
26                handle_queued_certs_to_send,
27            )
28                .chain()
29                .before(client_chat::handler::handle_send_chat_kind_event),
30        );
31    }
32}
33
34#[derive(Component)]
35pub struct RequestCertsTask(pub Task<Result<Certificates, FetchCertificatesError>>);
36
37/// A component that makes us have to wait until the given time to refresh the
38/// certs.
39///
40/// This is used to avoid spamming requests if requesting certs fails. Usually,
41/// we just check [`Certificates::expires_at`].
42#[derive(Component, Debug)]
43pub struct OnlyRefreshCertsAfter {
44    pub refresh_at: Instant,
45}
46/// A component that's present when this client has sent its certificates to the
47/// server.
48///
49/// This should be removed if you want to re-send the certs.
50///
51/// If you want to get the client's actual certificates, you can get that from
52/// the `certs` in the [`Account`] component.
53#[derive(Component)]
54pub struct ChatSigningSession {
55    pub session_id: Uuid,
56    pub messages_sent: u32,
57}
58
59pub fn poll_request_certs_task(
60    mut commands: Commands,
61    mut query: Query<(Entity, &mut RequestCertsTask, &Account)>,
62) {
63    for (entity, mut auth_task, account) in query.iter_mut() {
64        if let Some(poll_res) = future::block_on(future::poll_once(&mut auth_task.0)) {
65            debug!("Finished requesting certs");
66            commands.entity(entity).remove::<RequestCertsTask>();
67
68            match poll_res {
69                Ok(certs) => {
70                    commands.entity(entity).insert(QueuedCertsToSend {
71                        certs: certs.clone(),
72                    });
73                    account.set_certs(certs);
74                }
75                Err(err) => {
76                    error!("Error requesting certs: {err:?}. Retrying in an hour.");
77
78                    commands.entity(entity).insert(OnlyRefreshCertsAfter {
79                        refresh_at: Instant::now() + Duration::from_secs(60 * 60),
80                    });
81                }
82            }
83        }
84    }
85}
86
87#[allow(clippy::type_complexity)]
88pub fn request_certs_if_needed(
89    mut commands: Commands,
90    mut query: Query<
91        (
92            Entity,
93            &Account,
94            Option<&OnlyRefreshCertsAfter>,
95            Option<&ChatSigningSession>,
96        ),
97        (
98            Without<RequestCertsTask>,
99            With<InGameState>,
100            With<IsAuthenticated>,
101        ),
102    >,
103) {
104    for (entity, account, only_refresh_certs_after, chat_signing_session) in query.iter_mut() {
105        if let Some(only_refresh_certs_after) = only_refresh_certs_after
106            && only_refresh_certs_after.refresh_at > Instant::now()
107        {
108            continue;
109        }
110
111        let certs = account.certs();
112        let should_refresh = if let Some(certs) = certs {
113            // certs were already requested and we're waiting for them to
114            // refresh
115
116            // but maybe they weren't sent yet, in which case we still want to
117            // send the certs
118            if chat_signing_session.is_none() {
119                true
120            } else {
121                Utc::now() > certs.expires_at
122            }
123        } else {
124            true
125        };
126
127        if should_refresh && let Some(access_token) = account.access_token() {
128            let task_pool = IoTaskPool::get();
129
130            debug!("Started task to fetch certs");
131            let task = task_pool.spawn(async_compat::Compat::new(async move {
132                azalea_auth::certs::fetch_certificates(&access_token).await
133            }));
134            commands
135                .entity(entity)
136                .insert(RequestCertsTask(task))
137                .remove::<OnlyRefreshCertsAfter>();
138        }
139    }
140}
141
142/// A component that's present on players that should send their chat signing
143/// certificates as soon as possible.
144///
145/// This is removed when the certificates get sent.
146#[derive(Component)]
147pub struct QueuedCertsToSend {
148    pub certs: Certificates,
149}
150
151pub fn handle_queued_certs_to_send(
152    mut commands: Commands,
153    query: Query<(Entity, &QueuedCertsToSend), With<IsAuthenticated>>,
154) {
155    for (entity, queued_certs) in &query {
156        let certs = &queued_certs.certs;
157
158        let session_id = Uuid::new_v4();
159
160        let chat_session = RemoteChatSessionData {
161            session_id,
162            profile_public_key: ProfilePublicKeyData {
163                expires_at: certs.expires_at.timestamp_millis() as u64,
164                key: certs.public_key_der.clone(),
165                key_signature: certs.signature_v2.clone(),
166            },
167        };
168
169        debug!("Sending chat signing certs to server");
170
171        commands.trigger(SendGamePacketEvent::new(
172            entity,
173            ServerboundChatSessionUpdate { chat_session },
174        ));
175        commands
176            .entity(entity)
177            .remove::<QueuedCertsToSend>()
178            .insert(ChatSigningSession {
179                session_id,
180                messages_sent: 0,
181            });
182    }
183}