Skip to content

Commit

Permalink
Fix auth (finally) (#937)
Browse files Browse the repository at this point in the history
* Finish auth

* Clippy + fix avatar on alts

* add retrying to entitlement request
  • Loading branch information
Geometrically authored Dec 13, 2023
1 parent 260744c commit e39635c
Show file tree
Hide file tree
Showing 19 changed files with 69 additions and 46 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion theseus/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "theseus"
version = "0.6.2"
version = "0.6.3"
authors = ["Jai A <[email protected]>"]
edition = "2018"

Expand Down
5 changes: 2 additions & 3 deletions theseus/src/api/hydra/complete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub async fn wait_finish(device_code: String) -> crate::Result<Credentials> {
}
xsts_token::XSTSResponse::Success { token: xsts_token } => {
// Get xsts bearer token from xsts token
let bearer_token =
let (bearer_token, expires_in) =
bearer_token::fetch_bearer(&xsts_token, &xbl_token.uhs)
.await
.map_err(|err| {
Expand All @@ -63,8 +63,7 @@ pub async fn wait_finish(device_code: String) -> crate::Result<Credentials> {
player_info.name,
bearer_token,
oauth.refresh_token,
chrono::Utc::now()
+ chrono::Duration::seconds(oauth.expires_in),
chrono::Utc::now() + chrono::Duration::seconds(expires_in),
);

// Put credentials into state
Expand Down
20 changes: 11 additions & 9 deletions theseus/src/api/hydra/init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
//! Login route for Hydra, redirects to the Microsoft login page before going to the redirect route
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::{hydra::MicrosoftError, util::fetch::REQWEST_CLIENT};
Expand All @@ -19,17 +17,21 @@ pub struct DeviceLoginSuccess {

pub async fn init() -> crate::Result<DeviceLoginSuccess> {
// Get the initial URL
let client_id = MICROSOFT_CLIENT_ID;

// Get device code
// Define the parameters
let mut params = HashMap::new();
params.insert("client_id", client_id);
params.insert("scope", "XboxLive.signin offline_access");

// urlencoding::encode("XboxLive.signin offline_access"));
let resp = auth_retry(|| REQWEST_CLIENT.post("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode")
.header("Content-Type", "application/x-www-form-urlencoded").form(&params).send()).await?;
let resp = auth_retry(|| REQWEST_CLIENT.get("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode")
.header("Content-Length", "0")
.query(&[
("client_id", MICROSOFT_CLIENT_ID),
(
"scope",
"XboxLive.signin XboxLive.offline_access profile openid email",
),
])
.send()
).await?;

match resp.status() {
reqwest::StatusCode::OK => Ok(resp.json().await?),
Expand Down
4 changes: 4 additions & 0 deletions theseus/src/api/hydra/refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ pub async fn refresh(refresh_token: String) -> crate::Result<OauthSuccess> {
params.insert("grant_type", "refresh_token");
params.insert("client_id", MICROSOFT_CLIENT_ID);
params.insert("refresh_token", &refresh_token);
params.insert(
"redirect_uri",
"https://login.microsoftonline.com/common/oauth2/nativeclient",
);

// Poll the URL in a loop until we are successful.
// On an authorization_pending response, wait 5 seconds and try again.
Expand Down
30 changes: 19 additions & 11 deletions theseus/src/api/hydra/stages/bearer_token.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,42 @@
use serde::Deserialize;
use serde_json::json;

use super::auth_retry;

const MCSERVICES_AUTH_URL: &str =
"https://api.minecraftservices.com/launcher/login";
"https://api.minecraftservices.com/authentication/login_with_xbox";

#[derive(Deserialize)]
pub struct BearerTokenResponse {
access_token: String,
expires_in: i64,
}

#[tracing::instrument]
pub async fn fetch_bearer(token: &str, uhs: &str) -> crate::Result<String> {
pub async fn fetch_bearer(
token: &str,
uhs: &str,
) -> crate::Result<(String, i64)> {
let body = auth_retry(|| {
let client = reqwest::Client::new();
client
.post(MCSERVICES_AUTH_URL)
.header("Accept", "application/json")
.json(&json!({
"xtoken": format!("XBL3.0 x={};{}", uhs, token),
"platform": "PC_LAUNCHER"
"identityToken": format!("XBL3.0 x={};{}", uhs, token),
}))
.send()
})
.await?
.text()
.await?;

serde_json::from_str::<serde_json::Value>(&body)?
.get("access_token")
.and_then(serde_json::Value::as_str)
.map(String::from)
.ok_or(
serde_json::from_str::<BearerTokenResponse>(&body)
.map(|x| (x.access_token, x.expires_in))
.map_err(|_| {
crate::ErrorKind::HydraError(format!(
"Response didn't contain valid bearer token. body: {body}"
))
.into(),
)
.into()
})
}
2 changes: 1 addition & 1 deletion theseus/src/api/hydra/stages/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use futures::Future;
use reqwest::Response;

const RETRY_COUNT: usize = 2; // Does command 3 times
const RETRY_COUNT: usize = 9; // Does command 3 times
const RETRY_WAIT: std::time::Duration = std::time::Duration::from_secs(2);

pub mod bearer_token;
Expand Down
8 changes: 8 additions & 0 deletions theseus/src/api/hydra/stages/player_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ impl Default for PlayerInfo {

#[tracing::instrument]
pub async fn fetch_info(token: &str) -> crate::Result<PlayerInfo> {
auth_retry(|| {
REQWEST_CLIENT
.get("https://api.minecraftservices.com/entitlements/mcstore")
.bearer_auth(token)
.send()
})
.await?;

let response = auth_retry(|| {
REQWEST_CLIENT
.get(PROFILE_URL)
Expand Down
5 changes: 4 additions & 1 deletion theseus/src/api/hydra/stages/poll_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ pub async fn poll_response(device_code: String) -> crate::Result<OauthSuccess> {
params.insert("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
params.insert("client_id", MICROSOFT_CLIENT_ID);
params.insert("device_code", &device_code);
params.insert(
"scope",
"XboxLive.signin XboxLive.offline_access profile openid email",
);

// Poll the URL in a loop until we are successful.
// On an authorization_pending response, wait 5 seconds and try again.
Expand All @@ -34,7 +38,6 @@ pub async fn poll_response(device_code: String) -> crate::Result<OauthSuccess> {
.post(
"https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
)
.header("Content-Type", "application/x-www-form-urlencoded")
.form(&params)
.send()
})
Expand Down
1 change: 0 additions & 1 deletion theseus/src/api/hydra/stages/xbl_signin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ pub async fn login_xbl(token: &str) -> crate::Result<XBLLogin> {
REQWEST_CLIENT
.post(XBL_AUTH_URL)
.header(reqwest::header::ACCEPT, "application/json")
.header("x-xbl-contract-version", "1")
.json(&json!({
"Properties": {
"AuthMethod": "RPS",
Expand Down
2 changes: 1 addition & 1 deletion theseus/src/api/profile/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,8 @@ pub(crate) async fn get_loader_version_from_loader(

let loader_version = loaders
.iter()
.find(|&x| filter(x))
.cloned()
.find(filter)
.or(
// If stable was searched for but not found, return latest by default
if version == "stable" {
Expand Down
5 changes: 2 additions & 3 deletions theseus/src/launcher/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub async fn refresh_credentials(
.as_error())
}
xsts_token::XSTSResponse::Success { token: xsts_token } => {
let bearer_token =
let (bearer_token, expires_in) =
bearer_token::fetch_bearer(&xsts_token, &xbl_token.uhs)
.await
.map_err(|err| {
Expand All @@ -76,8 +76,7 @@ pub async fn refresh_credentials(

credentials.access_token = bearer_token;
credentials.refresh_token = oauth.refresh_token;
credentials.expires =
Utc::now() + Duration::seconds(oauth.expires_in);
credentials.expires = Utc::now() + Duration::seconds(expires_in);
}
}

Expand Down
2 changes: 1 addition & 1 deletion theseus/src/launcher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ pub async fn install_minecraft(

let state = State::get().await?;
let instance_path =
&io::canonicalize(&profile.get_profile_full_path().await?)?;
&io::canonicalize(profile.get_profile_full_path().await?)?;
let metadata = state.metadata.read().await;

let version_index = metadata
Expand Down
2 changes: 1 addition & 1 deletion theseus_cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "theseus_cli"
version = "0.6.2"
version = "0.6.3"
authors = ["Jai A <[email protected]>"]
edition = "2018"

Expand Down
13 changes: 7 additions & 6 deletions theseus_cli/src/subcommands/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,13 @@ impl ProfileInit {
.ok_or_else(|| eyre::eyre!("Modloader {loader} unsupported for Minecraft version {game_version}"))?
.loaders;

let loader_version =
loaders.iter().cloned().find(filter).ok_or_else(|| {
eyre::eyre!(
"Invalid version {version} for modloader {loader}"
)
})?;
let loader_version = loaders
.iter()
.find(|&x| filter(x))
.cloned()
.ok_or_else(|| {
eyre::eyre!("Invalid version {version} for modloader {loader}")
})?;

Some((loader_version, loader))
} else {
Expand Down
2 changes: 1 addition & 1 deletion theseus_gui/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "theseus_gui",
"private": true,
"version": "0.6.2",
"version": "0.6.3",
"type": "module",
"scripts": {
"dev": "vite",
Expand Down
2 changes: 1 addition & 1 deletion theseus_gui/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "theseus_gui"
version = "0.6.2"
version = "0.6.3"
description = "A Tauri App"
authors = ["you"]
license = ""
Expand Down
2 changes: 1 addition & 1 deletion theseus_gui/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
"package": {
"productName": "Modrinth App",
"version": "0.6.2"
"version": "0.6.3"
},
"tauri": {
"allowlist": {
Expand Down
2 changes: 1 addition & 1 deletion theseus_gui/src/components/ui/AccountsCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
<div v-if="displayAccounts.length > 0" class="account-group">
<div v-for="account in displayAccounts" :key="account.id" class="account-row">
<Button class="option account" @click="setAccount(account)">
<Avatar :src="`https://mc-heads.net/avatar/${selectedAccount.id}/128`" class="icon" />
<Avatar :src="`https://mc-heads.net/avatar/${account.id}/128`" class="icon" />
<p>{{ account.username }}</p>
</Button>
<Button v-tooltip="'Log out'" icon-only @click="logout(account.id)">
Expand Down

0 comments on commit e39635c

Please sign in to comment.