Fix auth (finally) (#937)

* Finish auth

* Clippy + fix avatar on alts

* add retrying to entitlement request
This commit is contained in:
Geometrically 2023-12-12 20:57:01 -07:00 committed by GitHub
parent 260744c8af
commit e39635c75b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 69 additions and 46 deletions

6
Cargo.lock generated
View File

@ -4685,7 +4685,7 @@ dependencies = [
[[package]]
name = "theseus"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"async-recursion",
"async-tungstenite",
@ -4733,7 +4733,7 @@ dependencies = [
[[package]]
name = "theseus_cli"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"argh",
"color-eyre",
@ -4760,7 +4760,7 @@ dependencies = [
[[package]]
name = "theseus_gui"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"chrono",
"cocoa",

View File

@ -1,6 +1,6 @@
[package]
name = "theseus"
version = "0.6.2"
version = "0.6.3"
authors = ["Jai A <jaiagr+gpg@pm.me>"]
edition = "2018"

View File

@ -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| {
@ -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

View File

@ -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};
@ -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?),

View File

@ -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.

View File

@ -1,19 +1,29 @@
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()
})
@ -21,14 +31,12 @@ pub async fn fetch_bearer(token: &str, uhs: &str) -> crate::Result<String> {
.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()
})
}

View File

@ -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;

View File

@ -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)

View File

@ -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.
@ -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()
})

View File

@ -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",

View File

@ -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" {

View File

@ -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| {
@ -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);
}
}

View File

@ -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

View File

@ -1,6 +1,6 @@
[package]
name = "theseus_cli"
version = "0.6.2"
version = "0.6.3"
authors = ["Jai A <jaiagr+gpg@pm.me>"]
edition = "2018"

View File

@ -175,11 +175,12 @@ 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))

View File

@ -1,7 +1,7 @@
{
"name": "theseus_gui",
"private": true,
"version": "0.6.2",
"version": "0.6.3",
"type": "module",
"scripts": {
"dev": "vite",

View File

@ -1,6 +1,6 @@
[package]
name = "theseus_gui"
version = "0.6.2"
version = "0.6.3"
description = "A Tauri App"
authors = ["you"]
license = ""

View File

@ -8,7 +8,7 @@
},
"package": {
"productName": "Modrinth App",
"version": "0.6.2"
"version": "0.6.3"
},
"tauri": {
"allowlist": {

View File

@ -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)">