Launcher Auth (#450)

* Launcher Auth

* Finish auth

* final fixes
This commit is contained in:
Geometrically
2023-08-04 23:38:34 -07:00
committed by GitHub
parent a35dd67b77
commit 47e28d24c8
38 changed files with 1200 additions and 477 deletions

View File

@@ -20,7 +20,8 @@ pub async fn authenticate_begin_flow() -> crate::Result<url::Url> {
/// This completes the authentication flow quasi-synchronously, returning the credentials
/// This can be used in conjunction with 'authenticate_begin_flow'
/// to call authenticate and call the flow from the frontend.
pub async fn authenticate_await_complete_flow() -> crate::Result<Credentials> {
pub async fn authenticate_await_complete_flow(
) -> crate::Result<(Credentials, Option<String>)> {
let credentials = AuthTask::await_auth_completion().await?;
Ok(credentials)
}
@@ -38,7 +39,7 @@ pub async fn cancel_flow() -> crate::Result<()> {
#[theseus_macros::debug_pin]
pub async fn authenticate(
browser_url: oneshot::Sender<url::Url>,
) -> crate::Result<Credentials> {
) -> crate::Result<(Credentials, Option<String>)> {
let mut flow = inner::HydraAuthFlow::new().await?;
let state = State::get().await?;
@@ -52,12 +53,12 @@ pub async fn authenticate(
let credentials = flow.extract_credentials(&state.fetch_semaphore).await?;
{
let mut users = state.users.write().await;
users.insert(&credentials).await?;
users.insert(&credentials.0).await?;
}
if state.settings.read().await.default_user.is_none() {
let mut settings = state.settings.write().await;
settings.default_user = Some(credentials.id);
settings.default_user = Some(credentials.0.id);
}
Ok(credentials)
@@ -79,8 +80,17 @@ pub async fn refresh(user: uuid::Uuid) -> crate::Result<Credentials> {
})?;
let fetch_semaphore = &state.fetch_semaphore;
if Utc::now() > credentials.expires {
inner::refresh_credentials(&mut credentials, fetch_semaphore).await?;
if Utc::now() > credentials.expires
&& inner::refresh_credentials(&mut credentials, fetch_semaphore)
.await
.is_err()
{
users.remove(credentials.id).await?;
return Err(crate::ErrorKind::OtherError(
"Please re-authenticate with your Minecraft account!".to_string(),
)
.as_error());
}
users.insert(&credentials).await?;

View File

@@ -4,6 +4,7 @@ use serde::Deserialize;
use std::path::PathBuf;
use crate::event::emit::{emit_loading, init_loading};
use crate::state::CredentialsStore;
use crate::util::fetch::{fetch_advanced, fetch_json};
use crate::util::io;
use crate::util::jre::extract_java_majorminor_version;
@@ -97,6 +98,7 @@ pub async fn auto_install_java(java_version: u32) -> crate::Result<PathBuf> {
None,
None,
&state.fetch_semaphore,
&CredentialsStore(None),
).await?;
emit_loading(&loading_bar, 10.0, Some("Downloading java version")).await?;
@@ -109,6 +111,7 @@ pub async fn auto_install_java(java_version: u32) -> crate::Result<PathBuf> {
None,
Some((&loading_bar, 80.0)),
&state.fetch_semaphore,
&CredentialsStore(None),
)
.await?;

View File

@@ -4,6 +4,7 @@ pub mod handler;
pub mod jre;
pub mod logs;
pub mod metadata;
pub mod mr_auth;
pub mod pack;
pub mod process;
pub mod profile;
@@ -14,9 +15,9 @@ pub mod tags;
pub mod data {
pub use crate::state::{
DirectoryInfo, Hooks, JavaSettings, LinkedData, MemorySettings,
ModLoader, ModrinthProject, ModrinthTeamMember, ModrinthUser,
ModrinthVersion, ProfileMetadata, ProjectMetadata, Settings, Theme,
WindowSize,
ModLoader, ModrinthCredentials, ModrinthCredentialsResult,
ModrinthProject, ModrinthTeamMember, ModrinthUser, ModrinthVersion,
ProfileMetadata, ProjectMetadata, Settings, Theme, WindowSize,
};
}

157
theseus/src/api/mr_auth.rs Normal file
View File

@@ -0,0 +1,157 @@
use crate::state::{
ModrinthAuthFlow, ModrinthCredentials, ModrinthCredentialsResult,
};
use crate::ErrorKind;
#[tracing::instrument]
pub async fn authenticate_begin_flow(provider: &str) -> crate::Result<String> {
let state = crate::State::get().await?;
let mut flow = ModrinthAuthFlow::new(provider).await?;
let url = flow.prepare_login_url().await?;
let mut write = state.modrinth_auth_flow.write().await;
*write = Some(flow);
Ok(url)
}
#[tracing::instrument]
pub async fn authenticate_await_complete_flow(
) -> crate::Result<ModrinthCredentialsResult> {
let state = crate::State::get().await?;
let mut write = state.modrinth_auth_flow.write().await;
if let Some(ref mut flow) = *write {
let creds = flow.extract_credentials(&state.fetch_semaphore).await?;
if let ModrinthCredentialsResult::Credentials(creds) = &creds {
let mut write = state.credentials.write().await;
write.login(creds.clone()).await?;
}
Ok(creds)
} else {
Err(ErrorKind::OtherError(
"No active Modrinth authenication flow!".to_string(),
)
.into())
}
}
#[tracing::instrument]
pub async fn cancel_flow() -> crate::Result<()> {
let state = crate::State::get().await?;
let mut write = state.modrinth_auth_flow.write().await;
if let Some(ref mut flow) = *write {
flow.close().await?;
}
*write = None;
Ok(())
}
pub async fn login_password(
username: &str,
password: &str,
challenge: &str,
) -> crate::Result<ModrinthCredentialsResult> {
let state = crate::State::get().await?;
let creds = crate::state::login_password(
username,
password,
challenge,
&state.fetch_semaphore,
)
.await?;
if let ModrinthCredentialsResult::Credentials(creds) = &creds {
let mut write = state.credentials.write().await;
write.login(creds.clone()).await?;
}
Ok(creds)
}
#[tracing::instrument]
pub async fn login_2fa(
code: &str,
flow: &str,
) -> crate::Result<ModrinthCredentials> {
let state = crate::State::get().await?;
let creds =
crate::state::login_2fa(code, flow, &state.fetch_semaphore).await?;
let mut write = state.credentials.write().await;
write.login(creds.clone()).await?;
Ok(creds)
}
#[tracing::instrument]
pub async fn login_minecraft(
flow: &str,
) -> crate::Result<ModrinthCredentialsResult> {
let state = crate::State::get().await?;
let creds =
crate::state::login_minecraft(flow, &state.fetch_semaphore).await?;
if let ModrinthCredentialsResult::Credentials(creds) = &creds {
let mut write = state.credentials.write().await;
write.login(creds.clone()).await?;
}
Ok(creds)
}
#[tracing::instrument]
pub async fn create_account(
username: &str,
email: &str,
password: &str,
challenge: &str,
sign_up_newsletter: bool,
) -> crate::Result<ModrinthCredentials> {
let state = crate::State::get().await?;
let creds = crate::state::create_account(
username,
email,
password,
challenge,
sign_up_newsletter,
&state.fetch_semaphore,
)
.await?;
let mut write = state.credentials.write().await;
write.login(creds.clone()).await?;
Ok(creds)
}
#[tracing::instrument]
pub async fn refresh() -> crate::Result<()> {
let state = crate::State::get().await?;
let mut write = state.credentials.write().await;
crate::state::refresh_credentials(&mut write, &state.fetch_semaphore)
.await?;
Ok(())
}
#[tracing::instrument]
pub async fn logout() -> crate::Result<()> {
let state = crate::State::get().await?;
let mut write = state.credentials.write().await;
write.logout().await?;
Ok(())
}
#[tracing::instrument]
pub async fn get_credentials() -> crate::Result<Option<ModrinthCredentials>> {
let state = crate::State::get().await?;
let read = state.credentials.read().await;
Ok(read.0.clone())
}

View File

@@ -2,6 +2,7 @@ use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::state::CredentialsStore;
use crate::{
prelude::{ModLoader, ProfilePathId},
state::ProfileInstallStage,
@@ -90,8 +91,13 @@ pub async fn import_curseforge(
thumbnail_url: Some(thumbnail_url),
}) = minecraft_instance.installed_modpack.clone()
{
let icon_bytes =
fetch(&thumbnail_url, None, &state.fetch_semaphore).await?;
let icon_bytes = fetch(
&thumbnail_url,
None,
&state.fetch_semaphore,
&CredentialsStore(None),
)
.await?;
let filename = thumbnail_url.rsplit('/').last();
if let Some(filename) = filename {
icon = Some(

View File

@@ -192,12 +192,14 @@ pub async fn generate_pack_from_version_id(
.await?;
emit_loading(&loading_bar, 0.0, Some("Fetching version")).await?;
let creds = state.credentials.read().await;
let version: ModrinthVersion = fetch_json(
Method::GET,
&format!("{}version/{}", MODRINTH_API_URL, version_id),
None,
None,
&state.fetch_semaphore,
&creds,
)
.await?;
emit_loading(&loading_bar, 10.0, None).await?;
@@ -225,6 +227,7 @@ pub async fn generate_pack_from_version_id(
None,
Some((&loading_bar, 70.0)),
&state.fetch_semaphore,
&creds,
)
.await?;
emit_loading(&loading_bar, 0.0, Some("Fetching project metadata")).await?;
@@ -235,13 +238,16 @@ pub async fn generate_pack_from_version_id(
None,
None,
&state.fetch_semaphore,
&creds,
)
.await?;
emit_loading(&loading_bar, 10.0, Some("Retrieving icon")).await?;
let icon = if let Some(icon_url) = project.icon_url {
let state = State::get().await?;
let icon_bytes = fetch(&icon_url, None, &state.fetch_semaphore).await?;
let icon_bytes =
fetch(&icon_url, None, &state.fetch_semaphore, &creds).await?;
drop(creds);
let filename = icon_url.rsplit('/').next();

View File

@@ -168,6 +168,7 @@ pub async fn install_zipped_mrpack_files(
}
}
let creds = state.credentials.read().await;
let file = fetch_mirrors(
&project
.downloads
@@ -176,8 +177,10 @@ pub async fn install_zipped_mrpack_files(
.collect::<Vec<&str>>(),
project.hashes.get(&PackFileHash::Sha1).map(|x| &**x),
&state.fetch_semaphore,
&creds,
)
.await?;
drop(creds);
let path =
std::path::Path::new(&project.path).components().next();

View File

@@ -1,4 +1,6 @@
//! Authentication flow based on Hydra
use crate::config::MODRINTH_API_URL;
use crate::state::CredentialsStore;
use crate::util::fetch::{fetch_advanced, fetch_json, FetchSemaphore};
use async_tungstenite as ws;
use chrono::{prelude::*, Duration};
@@ -10,7 +12,7 @@ use url::Url;
lazy_static! {
static ref HYDRA_URL: Url =
Url::parse("https://staging-api.modrinth.com/v2/auth/minecraft/")
Url::parse(&format!("{MODRINTH_API_URL}auth/minecraft/"))
.expect("Hydra URL parse failed");
}
@@ -40,7 +42,7 @@ struct TokenJSON {
token: String,
refresh_token: String,
expires_after: u32,
flow: String,
flow: Option<String>,
}
#[derive(Deserialize)]
@@ -68,7 +70,7 @@ pub struct HydraAuthFlow<S: AsyncRead + AsyncWrite + Unpin> {
impl HydraAuthFlow<ws::tokio::ConnectStream> {
pub async fn new() -> crate::Result<Self> {
let (socket, _) = ws::tokio::connect_async(
"wss://staging-api.modrinth.com/v2/auth/minecraft/ws",
"wss://api.modrinth.com/v2/auth/minecraft/ws",
)
.await?;
Ok(Self { socket })
@@ -96,7 +98,7 @@ impl HydraAuthFlow<ws::tokio::ConnectStream> {
pub async fn extract_credentials(
&mut self,
semaphore: &FetchSemaphore,
) -> crate::Result<Credentials> {
) -> crate::Result<(Credentials, Option<String>)> {
// Minecraft bearer token
let token_resp = self
.socket
@@ -117,14 +119,17 @@ impl HydraAuthFlow<ws::tokio::ConnectStream> {
let info = fetch_info(&token.token, semaphore).await?;
// Return structure from response
Ok(Credentials {
username: info.name,
id: info.id,
refresh_token: token.refresh_token,
access_token: token.token,
expires,
_ctor_scope: std::marker::PhantomData,
})
Ok((
Credentials {
username: info.name,
id: info.id,
refresh_token: token.refresh_token,
access_token: token.token,
expires,
_ctor_scope: std::marker::PhantomData,
},
token.flow,
))
}
}
@@ -134,10 +139,11 @@ pub async fn refresh_credentials(
) -> crate::Result<()> {
let resp = fetch_json::<TokenJSON>(
Method::POST,
"https://staging-api.modrinth.com/v2/auth/minecraft/refresh",
&format!("{MODRINTH_API_URL}auth/minecraft/refresh"),
None,
Some(serde_json::json!({ "refresh_token": credentials.refresh_token })),
semaphore,
&CredentialsStore(None),
)
.await?;
@@ -162,6 +168,7 @@ async fn fetch_info(
Some(("Authorization", &format!("Bearer {token}"))),
None,
semaphore,
&CredentialsStore(None),
)
.await?;
let value = serde_json::from_slice(&result)?;

View File

@@ -1,5 +1,6 @@
//! Downloader for Minecraft data
use crate::state::CredentialsStore;
use crate::{
event::{
emit::{emit_loading, loading_try_for_each_concurrent},
@@ -127,6 +128,7 @@ pub async fn download_client(
&client_download.url,
Some(&client_download.sha1),
&st.fetch_semaphore,
&CredentialsStore(None),
)
.await?;
write(&path, &bytes, &st.io_semaphore).await?;
@@ -206,7 +208,7 @@ pub async fn download_assets(
async {
if !resource_path.exists() {
let resource = fetch_cell
.get_or_try_init(|| fetch(&url, Some(hash), &st.fetch_semaphore))
.get_or_try_init(|| fetch(&url, Some(hash), &st.fetch_semaphore, &CredentialsStore(None)))
.await?;
write(&resource_path, resource, &st.io_semaphore).await?;
tracing::trace!("Fetched asset with hash {hash}");
@@ -216,7 +218,7 @@ pub async fn download_assets(
async {
if with_legacy {
let resource = fetch_cell
.get_or_try_init(|| fetch(&url, Some(hash), &st.fetch_semaphore))
.get_or_try_init(|| fetch(&url, Some(hash), &st.fetch_semaphore, &CredentialsStore(None)))
.await?;
let resource_path = st.directories.legacy_assets_dir().await.join(
name.replace('/', &String::from(std::path::MAIN_SEPARATOR))
@@ -273,7 +275,7 @@ pub async fn download_libraries(
artifact: Some(ref artifact),
..
}) => {
let bytes = fetch(&artifact.url, Some(&artifact.sha1), &st.fetch_semaphore)
let bytes = fetch(&artifact.url, Some(&artifact.sha1), &st.fetch_semaphore, &CredentialsStore(None))
.await?;
write(&path, &bytes, &st.io_semaphore).await?;
tracing::trace!("Fetched library {} to path {:?}", &library.name, &path);
@@ -288,7 +290,7 @@ pub async fn download_libraries(
&artifact_path
].concat();
let bytes = fetch(&url, None, &st.fetch_semaphore).await?;
let bytes = fetch(&url, None, &st.fetch_semaphore, &CredentialsStore(None)).await?;
write(&path, &bytes, &st.io_semaphore).await?;
tracing::trace!("Fetched library {} to path {:?}", &library.name, &path);
Ok::<_, crate::Error>(())
@@ -314,7 +316,7 @@ pub async fn download_libraries(
);
if let Some(native) = classifiers.get(&parsed_key) {
let data = fetch(&native.url, Some(&native.sha1), &st.fetch_semaphore).await?;
let data = fetch(&native.url, Some(&native.sha1), &st.fetch_semaphore, &CredentialsStore(None)).await?;
let reader = std::io::Cursor::new(&data);
if let Ok(mut archive) = zip::ZipArchive::new(reader) {
match archive.extract(st.directories.version_natives_dir(version).await) {

View File

@@ -6,7 +6,10 @@ use tokio::task::JoinHandle;
// A wrapper over the authentication task that allows it to be called from the frontend
// without caching the task handle in the frontend
pub struct AuthTask(Option<JoinHandle<crate::Result<Credentials>>>);
pub struct AuthTask(
#[allow(clippy::type_complexity)]
Option<JoinHandle<crate::Result<(Credentials, Option<String>)>>>,
);
impl AuthTask {
pub fn new() -> AuthTask {
@@ -37,7 +40,8 @@ impl AuthTask {
Ok(url)
}
pub async fn await_auth_completion() -> crate::Result<Credentials> {
pub async fn await_auth_completion(
) -> crate::Result<(Credentials, Option<String>)> {
// Gets the task handle from the state, replacing with None
let task = {
let state = crate::State::get().await?;

View File

@@ -52,6 +52,9 @@ pub use self::safe_processes::*;
mod discord;
pub use self::discord::*;
mod mr_auth;
pub use self::mr_auth::*;
// Global state
// RwLock on state only has concurrent reads, except for config dir change which takes control of the State
static LAUNCHER_STATE: OnceCell<RwLock<State>> = OnceCell::const_new();
@@ -77,16 +80,20 @@ pub struct State {
pub settings: RwLock<Settings>,
/// Reference to minecraft process children
pub children: RwLock<Children>,
/// Authentication flow
pub auth_flow: RwLock<AuthTask>,
/// Launcher profile metadata
pub(crate) profiles: RwLock<Profiles>,
/// Launcher user account info
pub(crate) users: RwLock<Users>,
/// Launcher tags
pub(crate) tags: RwLock<Tags>,
/// Launcher processes that should be safely exited on shutdown
pub(crate) safety_processes: RwLock<SafeProcesses>,
/// Launcher user account info
pub(crate) users: RwLock<Users>,
/// Authentication flow
pub auth_flow: RwLock<AuthTask>,
/// Modrinth Credentials Store
pub credentials: RwLock<CredentialsStore>,
/// Modrinth auth flow
pub modrinth_auth_flow: RwLock<Option<ModrinthAuthFlow>>,
/// Discord RPC
pub discord_rpc: DiscordGuard,
@@ -159,15 +166,18 @@ impl State {
!is_offline,
&io_semaphore,
&fetch_semaphore,
&CredentialsStore(None),
);
let users_fut = Users::init(&directories, &io_semaphore);
let creds_fut = CredentialsStore::init(&directories, &io_semaphore);
// Launcher data
let (metadata, profiles, tags, users) = loading_join! {
let (metadata, profiles, tags, users, creds) = loading_join! {
Some(&loading_bar), 70.0, Some("Loading metadata");
metadata_fut,
profiles_fut,
tags_fut,
users_fut,
creds_fut,
}?;
let children = Children::new();
@@ -198,10 +208,12 @@ impl State {
users: RwLock::new(users),
children: RwLock::new(children),
auth_flow: RwLock::new(auth_flow),
credentials: RwLock::new(creds),
tags: RwLock::new(tags),
discord_rpc,
safety_processes: RwLock::new(safety_processes),
file_watcher: RwLock::new(file_watcher),
modrinth_auth_flow: RwLock::new(None),
}))
}
@@ -222,6 +234,11 @@ impl State {
/// Updates state with data from the web, if we are online
pub fn update() {
tokio::task::spawn(Metadata::update());
tokio::task::spawn(Tags::update());
tokio::task::spawn(Profiles::update_projects());
tokio::task::spawn(Profiles::update_modrinth_versions());
tokio::task::spawn(CredentialsStore::update_creds());
tokio::task::spawn(async {
if let Ok(state) = crate::State::get().await {
if !*state.offline.read().await {
@@ -230,8 +247,9 @@ impl State {
let res3 = Metadata::update();
let res4 = Profiles::update_projects();
let res5 = Settings::update_java();
let res6 = CredentialsStore::update_creds();
let _ = join!(res1, res2, res3, res4, res5);
let _ = join!(res1, res2, res3, res4, res5, res6);
}
}
});

View File

@@ -0,0 +1,398 @@
use crate::config::MODRINTH_API_URL;
use crate::state::DirectoryInfo;
use crate::util::fetch::{
fetch_advanced, read_json, write, FetchSemaphore, IoSemaphore,
};
use crate::State;
use chrono::{DateTime, Duration, Utc};
use futures::TryStreamExt;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
const AUTH_JSON: &str = "auth.json";
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthUser {
pub id: String,
pub username: String,
pub name: Option<String>,
pub avatar_url: Option<String>,
pub bio: Option<String>,
pub created: DateTime<Utc>,
pub role: String,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthCredentials {
pub session: String,
pub expires_at: DateTime<Utc>,
pub user: ModrinthUser,
}
#[derive(Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum ModrinthCredentialsResult {
TwoFactorRequired { flow: String },
Credentials(ModrinthCredentials),
}
#[derive(Debug)]
pub struct CredentialsStore(pub Option<ModrinthCredentials>);
impl CredentialsStore {
pub async fn init(
dirs: &DirectoryInfo,
io_semaphore: &IoSemaphore,
) -> crate::Result<Self> {
let auth_path = dirs.caches_meta_dir().await.join(AUTH_JSON);
let user = read_json(&auth_path, io_semaphore).await.ok();
if let Some(user) = user {
Ok(Self(Some(user)))
} else {
Ok(Self(None))
}
}
pub async fn save(&self) -> crate::Result<()> {
let state = State::get().await?;
let auth_path =
state.directories.caches_meta_dir().await.join(AUTH_JSON);
if let Some(creds) = &self.0 {
write(&auth_path, &serde_json::to_vec(creds)?, &state.io_semaphore)
.await?;
}
Ok(())
}
pub async fn login(
&mut self,
credentials: ModrinthCredentials,
) -> crate::Result<&Self> {
self.0 = Some(credentials);
self.save().await?;
Ok(self)
}
#[tracing::instrument]
pub async fn update_creds() {
let res = async {
let state = State::get().await?;
let mut creds_write = state.credentials.write().await;
refresh_credentials(&mut creds_write, &state.fetch_semaphore)
.await?;
Ok::<(), crate::Error>(())
}
.await;
match res {
Ok(()) => {}
Err(err) => {
tracing::warn!("Unable to update credentials: {err}")
}
};
}
pub async fn logout(&mut self) -> crate::Result<&Self> {
self.0 = None;
self.save().await?;
Ok(self)
}
}
pub struct ModrinthAuthFlow {
socket: async_tungstenite::WebSocketStream<
async_tungstenite::tokio::ConnectStream,
>,
}
impl ModrinthAuthFlow {
pub async fn new(provider: &str) -> crate::Result<Self> {
let (socket, _) = async_tungstenite::tokio::connect_async(format!(
"wss://api.modrinth.com/v2/auth/ws?provider={provider}"
))
.await?;
Ok(Self { socket })
}
pub async fn prepare_login_url(&mut self) -> crate::Result<String> {
let code_resp = self
.socket
.try_next()
.await?
.ok_or(
crate::ErrorKind::WSClosedError(String::from(
"login socket URL",
))
.as_error(),
)?
.into_data();
#[derive(Deserialize)]
struct Url {
url: String,
}
let response = serde_json::from_slice::<Url>(&code_resp)?;
Ok(response.url)
}
pub async fn extract_credentials(
&mut self,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentialsResult> {
// Minecraft bearer token
let token_resp = self
.socket
.try_next()
.await?
.ok_or(
crate::ErrorKind::WSClosedError(String::from(
"login socket URL",
))
.as_error(),
)?
.into_data();
let response =
serde_json::from_slice::<HashMap<String, Value>>(&token_resp)?;
get_result_from_res("code", response, semaphore).await
}
pub async fn close(&mut self) -> crate::Result<()> {
self.socket.close(None).await?;
Ok(())
}
}
async fn get_result_from_res(
code_key: &str,
response: HashMap<String, Value>,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentialsResult> {
if let Some(flow) = response.get("flow").and_then(|x| x.as_str()) {
Ok(ModrinthCredentialsResult::TwoFactorRequired {
flow: flow.to_string(),
})
} else if let Some(code) = response.get(code_key).and_then(|x| x.as_str()) {
let info = fetch_info(code, semaphore).await?;
Ok(ModrinthCredentialsResult::Credentials(
ModrinthCredentials {
session: code.to_string(),
expires_at: Utc::now() + Duration::weeks(2),
user: info,
},
))
} else if let Some(error) =
response.get("description").and_then(|x| x.as_str())
{
Err(crate::ErrorKind::OtherError(format!(
"Failed to login with error {error}"
))
.as_error())
} else {
Err(crate::ErrorKind::OtherError(String::from(
"Flow/code/error not found in response!",
))
.as_error())
}
}
#[derive(Deserialize)]
struct Session {
session: String,
}
pub async fn login_password(
username: &str,
password: &str,
challenge: &str,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentialsResult> {
let resp = fetch_advanced(
Method::POST,
&format!("https://{MODRINTH_API_URL}auth/login"),
None,
Some(serde_json::json!({
"username": username,
"password": password,
"challenge": challenge,
})),
None,
None,
semaphore,
&CredentialsStore(None),
)
.await?;
let value = serde_json::from_slice::<HashMap<String, Value>>(&resp)?;
get_result_from_res("session", value, semaphore).await
}
async fn get_creds_from_res(
response: HashMap<String, Value>,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentials> {
if let Some(code) = response.get("session").and_then(|x| x.as_str()) {
let info = fetch_info(code, semaphore).await?;
Ok(ModrinthCredentials {
session: code.to_string(),
expires_at: Utc::now() + Duration::weeks(2),
user: info,
})
} else if let Some(error) =
response.get("description").and_then(|x| x.as_str())
{
Err(crate::ErrorKind::OtherError(format!(
"Failed to login with error {error}"
))
.as_error())
} else {
Err(crate::ErrorKind::OtherError(String::from(
"Flow/code/error not found in response!",
))
.as_error())
}
}
pub async fn login_2fa(
code: &str,
flow: &str,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentials> {
let resp = fetch_advanced(
Method::POST,
&format!("{MODRINTH_API_URL}auth/login/2fa"),
None,
Some(serde_json::json!({
"code": code,
"flow": flow,
})),
None,
None,
semaphore,
&CredentialsStore(None),
)
.await?;
let response = serde_json::from_slice::<HashMap<String, Value>>(&resp)?;
get_creds_from_res(response, semaphore).await
}
pub async fn create_account(
username: &str,
email: &str,
password: &str,
challenge: &str,
sign_up_newsletter: bool,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentials> {
let resp = fetch_advanced(
Method::POST,
&format!("{MODRINTH_API_URL}auth/create"),
None,
Some(serde_json::json!({
"username": username,
"email": email,
"password": password,
"challenge": challenge,
"sign_up_newsletter": sign_up_newsletter,
})),
None,
None,
semaphore,
&CredentialsStore(None),
)
.await?;
let response = serde_json::from_slice::<HashMap<String, Value>>(&resp)?;
get_creds_from_res(response, semaphore).await
}
pub async fn login_minecraft(
flow: &str,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthCredentialsResult> {
let resp = fetch_advanced(
Method::POST,
&format!("{MODRINTH_API_URL}auth/login/minecraft"),
None,
Some(serde_json::json!({
"flow": flow,
})),
None,
None,
semaphore,
&CredentialsStore(None),
)
.await?;
let response = serde_json::from_slice::<HashMap<String, Value>>(&resp)?;
get_result_from_res("session", response, semaphore).await
}
pub async fn refresh_credentials(
credentials_store: &mut CredentialsStore,
semaphore: &FetchSemaphore,
) -> crate::Result<()> {
if let Some(ref mut credentials) = credentials_store.0 {
let token = &credentials.session;
let resp = fetch_advanced(
Method::POST,
&format!("{MODRINTH_API_URL}session/refresh"),
None,
None,
Some(("Authorization", token)),
None,
semaphore,
&CredentialsStore(None),
)
.await
.ok()
.and_then(|resp| serde_json::from_slice::<Session>(&resp).ok());
if let Some(value) = resp {
credentials.user = fetch_info(&value.session, semaphore).await?;
credentials.session = value.session;
credentials.expires_at = Utc::now() + Duration::weeks(2);
} else if credentials.expires_at < Utc::now() {
credentials_store.0 = None;
}
}
Ok(())
}
async fn fetch_info(
token: &str,
semaphore: &FetchSemaphore,
) -> crate::Result<ModrinthUser> {
let result = fetch_advanced(
Method::GET,
&format!("{MODRINTH_API_URL}user"),
None,
None,
Some(("Authorization", token)),
None,
semaphore,
&CredentialsStore(None),
)
.await?;
let value = serde_json::from_slice(&result)?;
Ok(value)
}

View File

@@ -342,14 +342,17 @@ impl Profile {
let paths = profile.get_profile_full_project_paths().await?;
let caches_dir = state.directories.caches_dir();
let creds = state.credentials.read().await;
let projects = crate::state::infer_data_from_files(
profile.clone(),
paths,
caches_dir,
&state.io_semaphore,
&state.fetch_semaphore,
&creds,
)
.await?;
drop(creds);
let mut new_profiles = state.profiles.write().await;
if let Some(profile) = new_profiles.0.get_mut(&profile_path_id) {
@@ -462,14 +465,17 @@ impl Profile {
version_id: String,
) -> crate::Result<(ProjectPathId, ModrinthVersion)> {
let state = State::get().await?;
let creds = state.credentials.read().await;
let version = fetch_json::<ModrinthVersion>(
Method::GET,
&format!("{MODRINTH_API_URL}version/{version_id}"),
None,
None,
&state.fetch_semaphore,
&creds,
)
.await?;
drop(creds);
let file = if let Some(file) = version.files.iter().find(|x| x.primary)
{
file
@@ -482,12 +488,15 @@ impl Profile {
.into());
};
let creds = state.credentials.read().await;
let bytes = fetch(
&file.url,
file.hashes.get("sha1").map(|x| &**x),
&state.fetch_semaphore,
&creds,
)
.await?;
drop(creds);
let path = self
.add_project_bytes(
&file.filename,
@@ -736,14 +745,17 @@ impl Profiles {
future::try_join_all(files.into_iter().map(
|(profile, files)| async {
let profile_name = profile.profile_id();
let creds = state.credentials.read().await;
let inferred = super::projects::infer_data_from_files(
profile,
files,
caches_dir.clone(),
&state.io_semaphore,
&state.fetch_semaphore,
&creds,
)
.await?;
drop(creds);
let mut new_profiles = state.profiles.write().await;
if let Some(profile) = new_profiles.0.get_mut(&profile_name)
@@ -803,6 +815,7 @@ impl Profiles {
let linked_project = linked_project;
let state = state.clone();
async move {
let creds = state.credentials.read().await;
let versions: Vec<ModrinthVersion> = fetch_json(
Method::GET,
&format!(
@@ -813,8 +826,10 @@ impl Profiles {
None,
None,
&state.fetch_semaphore,
&creds,
)
.await?;
drop(creds);
// Versions are pre-sorted in labrinth (by versions.sort_by(|a, b| b.inner.date_published.cmp(&a.inner.date_published));)
// so we can just take the first one

View File

@@ -1,7 +1,7 @@
//! Project management + inference
use crate::config::MODRINTH_API_URL;
use crate::state::Profile;
use crate::state::{CredentialsStore, ModrinthUser, Profile};
use crate::util::fetch::{
fetch_json, write_cached_icon, FetchSemaphore, IoSemaphore,
};
@@ -168,18 +168,6 @@ pub struct ModrinthTeamMember {
pub ordering: i64,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthUser {
pub id: String,
pub github_id: Option<u64>,
pub username: String,
pub name: Option<String>,
pub avatar_url: Option<String>,
pub bio: Option<String>,
pub created: DateTime<Utc>,
pub role: String,
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum DependencyType {
@@ -289,6 +277,7 @@ pub async fn infer_data_from_files(
cache_dir: PathBuf,
io_semaphore: &IoSemaphore,
fetch_semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<HashMap<ProjectPathId, Project>> {
let mut file_path_hashes = HashMap::new();
@@ -327,6 +316,7 @@ pub async fn infer_data_from_files(
"algorithm": "sha512",
})),
fetch_semaphore,
credentials,
),
fetch_json::<HashMap<String, ModrinthVersion>>(
Method::POST,
@@ -339,6 +329,7 @@ pub async fn infer_data_from_files(
"game_versions": [profile.metadata.game_version]
})),
fetch_semaphore,
credentials,
)
)?;
@@ -357,6 +348,7 @@ pub async fn infer_data_from_files(
None,
None,
fetch_semaphore,
credentials,
)
.await?;
@@ -374,6 +366,7 @@ pub async fn infer_data_from_files(
None,
None,
fetch_semaphore,
credentials,
)
.await?
.into_iter()

View File

@@ -41,7 +41,7 @@ pub struct Settings {
#[serde(default)]
pub advanced_rendering: bool,
#[serde(default)]
pub onboarded_new: bool,
pub fully_onboarded: bool,
#[serde(default = "DirectoryInfo::get_initial_settings_dir")]
pub loaded_config_dir: Option<PathBuf>,
}
@@ -82,7 +82,7 @@ impl Settings {
developer_mode: false,
opt_out_analytics: false,
advanced_rendering: true,
onboarded_new: false,
fully_onboarded: false,
// By default, the config directory is the same as the settings directory
loaded_config_dir: DirectoryInfo::get_initial_settings_dir(),

View File

@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use crate::config::MODRINTH_API_URL;
use crate::data::DirectoryInfo;
use crate::state::CredentialsStore;
use crate::util::fetch::{
fetch_json, read_json, write, FetchSemaphore, IoSemaphore,
};
@@ -27,6 +28,7 @@ impl Tags {
fetch_online: bool,
io_semaphore: &IoSemaphore,
fetch_semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<Self> {
let mut tags = None;
let tags_path = dirs.caches_meta_dir().await.join("tags.json");
@@ -35,7 +37,7 @@ impl Tags {
{
tags = Some(tags_json);
} else if fetch_online {
match Self::fetch(fetch_semaphore).await {
match Self::fetch(fetch_semaphore, credentials).await {
Ok(tags_fetch) => tags = Some(tags_fetch),
Err(err) => {
tracing::warn!("Unable to fetch launcher tags: {err}")
@@ -58,7 +60,11 @@ impl Tags {
pub async fn update() {
let res = async {
let state = crate::State::get().await?;
let tags_fetch = Tags::fetch(&state.fetch_semaphore).await?;
let creds = state.credentials.read().await;
let tags_fetch =
Tags::fetch(&state.fetch_semaphore, &creds).await?;
drop(creds);
let tags_path =
state.directories.caches_meta_dir().await.join("tags.json");
@@ -123,7 +129,10 @@ impl Tags {
}
// Fetches the tags from the Modrinth API and stores them in the database
pub async fn fetch(semaphore: &FetchSemaphore) -> crate::Result<Self> {
pub async fn fetch(
semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<Self> {
let categories = format!("{MODRINTH_API_URL}tag/category");
let loaders = format!("{MODRINTH_API_URL}tag/loader");
let game_versions = format!("{MODRINTH_API_URL}tag/game_version");
@@ -137,6 +146,7 @@ impl Tags {
None,
None,
semaphore,
credentials,
);
let loaders_fut = fetch_json::<Vec<Loader>>(
Method::GET,
@@ -144,6 +154,7 @@ impl Tags {
None,
None,
semaphore,
credentials,
);
let game_versions_fut = fetch_json::<Vec<GameVersion>>(
Method::GET,
@@ -151,6 +162,7 @@ impl Tags {
None,
None,
semaphore,
credentials,
);
let donation_platforms_fut = fetch_json::<Vec<DonationPlatform>>(
Method::GET,
@@ -158,6 +170,7 @@ impl Tags {
None,
None,
semaphore,
credentials,
);
let report_types_fut = fetch_json::<Vec<String>>(
Method::GET,
@@ -165,6 +178,7 @@ impl Tags {
None,
None,
semaphore,
credentials,
);
let (

View File

@@ -1,6 +1,7 @@
//! Functions for fetching infromation from the Internet
use crate::event::emit::emit_loading;
use crate::event::LoadingBarId;
use crate::state::CredentialsStore;
use bytes::Bytes;
use lazy_static::lazy_static;
use reqwest::Method;
@@ -41,8 +42,19 @@ pub async fn fetch(
url: &str,
sha1: Option<&str>,
semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<Bytes> {
fetch_advanced(Method::GET, url, sha1, None, None, None, semaphore).await
fetch_advanced(
Method::GET,
url,
sha1,
None,
None,
None,
semaphore,
credentials,
)
.await
}
#[tracing::instrument(skip(json_body, semaphore))]
@@ -52,13 +64,22 @@ pub async fn fetch_json<T>(
sha1: Option<&str>,
json_body: Option<serde_json::Value>,
semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<T>
where
T: DeserializeOwned,
{
let result =
fetch_advanced(method, url, sha1, json_body, None, None, semaphore)
.await?;
let result = fetch_advanced(
method,
url,
sha1,
json_body,
None,
None,
semaphore,
credentials,
)
.await?;
let value = serde_json::from_slice(&result)?;
Ok(value)
}
@@ -66,6 +87,7 @@ where
/// Downloads a file with retry and checksum functionality
#[tracing::instrument(skip(json_body, semaphore))]
#[theseus_macros::debug_pin]
#[allow(clippy::too_many_arguments)]
pub async fn fetch_advanced(
method: Method,
url: &str,
@@ -74,6 +96,7 @@ pub async fn fetch_advanced(
header: Option<(&str, &str)>,
loading_bar: Option<(&LoadingBarId, f64)>,
semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<Bytes> {
let io_semaphore = semaphore.0.read().await;
let _permit = io_semaphore.acquire().await?;
@@ -89,6 +112,12 @@ pub async fn fetch_advanced(
req = req.header(header.0, header.1);
}
if url.starts_with("https://cdn.modrinth.com") {
if let Some(creds) = &credentials.0 {
req = req.header("Authorization", &creds.session);
}
}
let result = req.send().await;
match result {
Ok(x) => {
@@ -163,6 +192,7 @@ pub async fn fetch_mirrors(
mirrors: &[&str],
sha1: Option<&str>,
semaphore: &FetchSemaphore,
credentials: &CredentialsStore,
) -> crate::Result<Bytes> {
if mirrors.is_empty() {
return Err(crate::ErrorKind::InputError(
@@ -172,7 +202,7 @@ pub async fn fetch_mirrors(
}
for (index, mirror) in mirrors.iter().enumerate() {
let result = fetch(mirror, sha1, semaphore).await;
let result = fetch(mirror, sha1, semaphore, credentials).await;
if result.is_ok() || (result.is_err() && index == (mirrors.len() - 1)) {
return result;
@@ -186,7 +216,12 @@ pub async fn fetch_mirrors(
#[tracing::instrument(skip(semaphore))]
#[theseus_macros::debug_pin]
pub async fn check_internet(semaphore: &FetchSemaphore, timeout: u64) -> bool {
let result = fetch("https://api.modrinth.com", None, semaphore);
let result = fetch(
"https://api.modrinth.com",
None,
semaphore,
&CredentialsStore(None),
);
let result =
tokio::time::timeout(Duration::from_secs(timeout), result).await;
matches!(result, Ok(Ok(_)))