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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "theseus" name = "theseus"
version = "0.6.2" version = "0.6.3"
authors = ["Jai A <jaiagr+gpg@pm.me>"] authors = ["Jai A <jaiagr+gpg@pm.me>"]
edition = "2018" 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 } => { xsts_token::XSTSResponse::Success { token: xsts_token } => {
// Get xsts bearer token from 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) bearer_token::fetch_bearer(&xsts_token, &xbl_token.uhs)
.await .await
.map_err(|err| { .map_err(|err| {
@ -63,8 +63,7 @@ pub async fn wait_finish(device_code: String) -> crate::Result<Credentials> {
player_info.name, player_info.name,
bearer_token, bearer_token,
oauth.refresh_token, oauth.refresh_token,
chrono::Utc::now() chrono::Utc::now() + chrono::Duration::seconds(expires_in),
+ chrono::Duration::seconds(oauth.expires_in),
); );
// Put credentials into state // 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 //! 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 serde::{Deserialize, Serialize};
use crate::{hydra::MicrosoftError, util::fetch::REQWEST_CLIENT}; use crate::{hydra::MicrosoftError, util::fetch::REQWEST_CLIENT};
@ -19,17 +17,21 @@ pub struct DeviceLoginSuccess {
pub async fn init() -> crate::Result<DeviceLoginSuccess> { pub async fn init() -> crate::Result<DeviceLoginSuccess> {
// Get the initial URL // Get the initial URL
let client_id = MICROSOFT_CLIENT_ID;
// Get device code // Get device code
// Define the parameters // 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")); // urlencoding::encode("XboxLive.signin offline_access"));
let resp = auth_retry(|| REQWEST_CLIENT.post("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode") let resp = auth_retry(|| REQWEST_CLIENT.get("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode")
.header("Content-Type", "application/x-www-form-urlencoded").form(&params).send()).await?; .header("Content-Length", "0")
.query(&[
("client_id", MICROSOFT_CLIENT_ID),
(
"scope",
"XboxLive.signin XboxLive.offline_access profile openid email",
),
])
.send()
).await?;
match resp.status() { match resp.status() {
reqwest::StatusCode::OK => Ok(resp.json().await?), 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("grant_type", "refresh_token");
params.insert("client_id", MICROSOFT_CLIENT_ID); params.insert("client_id", MICROSOFT_CLIENT_ID);
params.insert("refresh_token", &refresh_token); 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. // Poll the URL in a loop until we are successful.
// On an authorization_pending response, wait 5 seconds and try again. // 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 serde_json::json;
use super::auth_retry; use super::auth_retry;
const MCSERVICES_AUTH_URL: &str = 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] #[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 body = auth_retry(|| {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
client client
.post(MCSERVICES_AUTH_URL) .post(MCSERVICES_AUTH_URL)
.header("Accept", "application/json")
.json(&json!({ .json(&json!({
"xtoken": format!("XBL3.0 x={};{}", uhs, token), "identityToken": format!("XBL3.0 x={};{}", uhs, token),
"platform": "PC_LAUNCHER"
})) }))
.send() .send()
}) })
@ -21,14 +31,12 @@ pub async fn fetch_bearer(token: &str, uhs: &str) -> crate::Result<String> {
.text() .text()
.await?; .await?;
serde_json::from_str::<serde_json::Value>(&body)? serde_json::from_str::<BearerTokenResponse>(&body)
.get("access_token") .map(|x| (x.access_token, x.expires_in))
.and_then(serde_json::Value::as_str) .map_err(|_| {
.map(String::from)
.ok_or(
crate::ErrorKind::HydraError(format!( crate::ErrorKind::HydraError(format!(
"Response didn't contain valid bearer token. body: {body}" "Response didn't contain valid bearer token. body: {body}"
)) ))
.into(), .into()
) })
} }

View File

@ -3,7 +3,7 @@
use futures::Future; use futures::Future;
use reqwest::Response; 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); const RETRY_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
pub mod bearer_token; pub mod bearer_token;

View File

@ -24,6 +24,14 @@ impl Default for PlayerInfo {
#[tracing::instrument] #[tracing::instrument]
pub async fn fetch_info(token: &str) -> crate::Result<PlayerInfo> { 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(|| { let response = auth_retry(|| {
REQWEST_CLIENT REQWEST_CLIENT
.get(PROFILE_URL) .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("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
params.insert("client_id", MICROSOFT_CLIENT_ID); params.insert("client_id", MICROSOFT_CLIENT_ID);
params.insert("device_code", &device_code); 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. // Poll the URL in a loop until we are successful.
// On an authorization_pending response, wait 5 seconds and try again. // 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( .post(
"https://login.microsoftonline.com/consumers/oauth2/v2.0/token", "https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
) )
.header("Content-Type", "application/x-www-form-urlencoded")
.form(&params) .form(&params)
.send() .send()
}) })

View File

@ -19,7 +19,6 @@ pub async fn login_xbl(token: &str) -> crate::Result<XBLLogin> {
REQWEST_CLIENT REQWEST_CLIENT
.post(XBL_AUTH_URL) .post(XBL_AUTH_URL)
.header(reqwest::header::ACCEPT, "application/json") .header(reqwest::header::ACCEPT, "application/json")
.header("x-xbl-contract-version", "1")
.json(&json!({ .json(&json!({
"Properties": { "Properties": {
"AuthMethod": "RPS", "AuthMethod": "RPS",

View File

@ -272,8 +272,8 @@ pub(crate) async fn get_loader_version_from_loader(
let loader_version = loaders let loader_version = loaders
.iter() .iter()
.find(|&x| filter(x))
.cloned() .cloned()
.find(filter)
.or( .or(
// If stable was searched for but not found, return latest by default // If stable was searched for but not found, return latest by default
if version == "stable" { if version == "stable" {

View File

@ -64,7 +64,7 @@ pub async fn refresh_credentials(
.as_error()) .as_error())
} }
xsts_token::XSTSResponse::Success { token: xsts_token } => { xsts_token::XSTSResponse::Success { token: xsts_token } => {
let bearer_token = let (bearer_token, expires_in) =
bearer_token::fetch_bearer(&xsts_token, &xbl_token.uhs) bearer_token::fetch_bearer(&xsts_token, &xbl_token.uhs)
.await .await
.map_err(|err| { .map_err(|err| {
@ -76,8 +76,7 @@ pub async fn refresh_credentials(
credentials.access_token = bearer_token; credentials.access_token = bearer_token;
credentials.refresh_token = oauth.refresh_token; credentials.refresh_token = oauth.refresh_token;
credentials.expires = credentials.expires = Utc::now() + Duration::seconds(expires_in);
Utc::now() + Duration::seconds(oauth.expires_in);
} }
} }

View File

@ -177,7 +177,7 @@ pub async fn install_minecraft(
let state = State::get().await?; let state = State::get().await?;
let instance_path = 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 metadata = state.metadata.read().await;
let version_index = metadata let version_index = metadata

View File

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

View File

@ -175,11 +175,12 @@ impl ProfileInit {
.ok_or_else(|| eyre::eyre!("Modloader {loader} unsupported for Minecraft version {game_version}"))? .ok_or_else(|| eyre::eyre!("Modloader {loader} unsupported for Minecraft version {game_version}"))?
.loaders; .loaders;
let loader_version = let loader_version = loaders
loaders.iter().cloned().find(filter).ok_or_else(|| { .iter()
eyre::eyre!( .find(|&x| filter(x))
"Invalid version {version} for modloader {loader}" .cloned()
) .ok_or_else(|| {
eyre::eyre!("Invalid version {version} for modloader {loader}")
})?; })?;
Some((loader_version, loader)) Some((loader_version, loader))

View File

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

View File

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

View File

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

View File

@ -42,7 +42,7 @@
<div v-if="displayAccounts.length > 0" class="account-group"> <div v-if="displayAccounts.length > 0" class="account-group">
<div v-for="account in displayAccounts" :key="account.id" class="account-row"> <div v-for="account in displayAccounts" :key="account.id" class="account-row">
<Button class="option account" @click="setAccount(account)"> <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> <p>{{ account.username }}</p>
</Button> </Button>
<Button v-tooltip="'Log out'" icon-only @click="logout(account.id)"> <Button v-tooltip="'Log out'" icon-only @click="logout(account.id)">