azalea_auth/
sessionserver.rs1use std::sync::LazyLock;
4
5use reqwest::StatusCode;
6use serde::Deserialize;
7use serde_json::json;
8use thiserror::Error;
9use tracing::debug;
10use uuid::Uuid;
11
12use crate::game_profile::{GameProfile, SerializableGameProfile};
13
14#[derive(Debug, Error)]
15pub enum ClientSessionServerError {
16 #[error("Error sending HTTP request to sessionserver: {0}")]
17 HttpError(#[from] reqwest::Error),
18 #[error("Multiplayer is not enabled for this account")]
19 MultiplayerDisabled,
20 #[error("This account has been banned from multiplayer")]
21 Banned,
22 #[error("The authentication servers are currently not reachable")]
23 AuthServersUnreachable,
24 #[error("Invalid or expired session")]
25 InvalidSession,
26 #[error("Unknown sessionserver error: {0}")]
27 Unknown(String),
28 #[error("Forbidden operation (expired session?)")]
29 ForbiddenOperation,
30 #[error("RateLimiter disallowed request")]
31 RateLimited,
32 #[error("Unexpected response from sessionserver (status code {status_code}): {body}")]
33 UnexpectedResponse { status_code: u16, body: String },
34}
35
36#[derive(Debug, Error)]
37pub enum ServerSessionServerError {
38 #[error("Error sending HTTP request to sessionserver: {0}")]
39 HttpError(#[from] reqwest::Error),
40 #[error("Invalid or expired session")]
41 InvalidSession,
42 #[error("Unexpected response from sessionserver (status code {status_code}): {body}")]
43 UnexpectedResponse { status_code: u16, body: String },
44 #[error("Unknown sessionserver error: {0}")]
45 Unknown(String),
46}
47
48#[derive(Deserialize)]
49pub struct ForbiddenError {
50 pub error: String,
51 pub path: String,
52}
53
54pub struct SessionServerJoinOpts<'a> {
55 pub access_token: &'a str,
56 pub public_key: &'a [u8],
58 pub private_key: &'a [u8],
59 pub uuid: &'a Uuid,
60 pub server_id: &'a str,
62
63 pub proxy: Option<reqwest::Proxy>,
64}
65
66pub async fn join(opts: SessionServerJoinOpts<'_>) -> Result<(), ClientSessionServerError> {
69 let client = if let Some(proxy) = opts.proxy {
70 reqwest::ClientBuilder::new().proxy(proxy).build()?
73 } else {
74 static REQWEST_CLIENT: LazyLock<reqwest::Client> =
78 LazyLock::new(|| reqwest::ClientBuilder::new().no_proxy().build().unwrap());
79
80 REQWEST_CLIENT.clone()
81 };
82
83 let server_hash = azalea_crypto::hex_digest(&azalea_crypto::digest_data(
84 opts.server_id.as_bytes(),
85 opts.public_key,
86 opts.private_key,
87 ));
88
89 join_with_server_id_hash(&client, opts.access_token, opts.uuid, &server_hash).await
90}
91
92pub async fn join_with_server_id_hash(
93 client: &reqwest::Client,
94 access_token: &str,
95 uuid: &Uuid,
96 server_hash: &str,
97) -> Result<(), ClientSessionServerError> {
98 let mut encode_buffer = Uuid::encode_buffer();
99 let undashed_uuid = uuid.simple().encode_lower(&mut encode_buffer);
100
101 let data = json!({
102 "accessToken": access_token,
103 "selectedProfile": undashed_uuid,
104 "serverId": server_hash
105 });
106 let res = client
107 .post("https://sessionserver.mojang.com/session/minecraft/join")
108 .json(&data)
109 .send()
110 .await?;
111
112 match res.status() {
113 StatusCode::NO_CONTENT => Ok(()),
114 StatusCode::FORBIDDEN => {
115 let forbidden = res.json::<ForbiddenError>().await?;
116 match forbidden.error.as_str() {
117 "InsufficientPrivilegesException" => {
118 Err(ClientSessionServerError::MultiplayerDisabled)
119 }
120 "UserBannedException" => Err(ClientSessionServerError::Banned),
121 "AuthenticationUnavailableException" => {
122 Err(ClientSessionServerError::AuthServersUnreachable)
123 }
124 "InvalidCredentialsException" => Err(ClientSessionServerError::InvalidSession),
125 "ForbiddenOperationException" => Err(ClientSessionServerError::ForbiddenOperation),
126 _ => Err(ClientSessionServerError::Unknown(forbidden.error)),
127 }
128 }
129 StatusCode::TOO_MANY_REQUESTS => Err(ClientSessionServerError::RateLimited),
130 status_code => {
131 debug!("Error headers: {:#?}", res.headers());
133 let body = res.text().await?;
134 Err(ClientSessionServerError::UnexpectedResponse {
135 status_code: status_code.as_u16(),
136 body,
137 })
138 }
139 }
140}
141
142pub async fn serverside_auth(
147 username: &str,
148 public_key: &[u8],
149 private_key: &[u8; 16],
150 ip: Option<&str>,
151) -> Result<GameProfile, ServerSessionServerError> {
152 let hash = azalea_crypto::hex_digest(&azalea_crypto::digest_data(
153 "".as_bytes(),
154 public_key,
155 private_key,
156 ));
157
158 let url = reqwest::Url::parse_with_params(
159 "https://sessionserver.mojang.com/session/minecraft/hasJoined",
160 if let Some(ip) = ip {
161 vec![("username", username), ("serverId", &hash), ("ip", ip)]
162 } else {
163 vec![("username", username), ("serverId", &hash)]
164 },
165 )
166 .expect("URL should always be valid");
167
168 let res = reqwest::get(url).await?;
169
170 match res.status() {
171 StatusCode::OK => {}
172 StatusCode::NO_CONTENT => {
173 return Err(ServerSessionServerError::InvalidSession);
174 }
175 StatusCode::FORBIDDEN => {
176 return Err(ServerSessionServerError::Unknown(
177 res.json::<ForbiddenError>().await?.error,
178 ));
179 }
180 status_code => {
181 debug!("Error headers: {:#?}", res.headers());
183 let body = res.text().await?;
184 return Err(ServerSessionServerError::UnexpectedResponse {
185 status_code: status_code.as_u16(),
186 body,
187 });
188 }
189 };
190
191 Ok(res.json::<SerializableGameProfile>().await?.into())
192}