Skip to content

Extend Theseus auth subsystem to fetch complete user profiles #3491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ rand = "=0.8.5" # Locked on 0.8 until argon2 and p256 update to 0.9
rand_chacha = "=0.3.1" # Locked on 0.3 until we can update rand to 0.9
redis = "=0.29.5" # Locked on 0.29 until deadpool-redis updates to 0.30
regex = "1.11.1"
heck = "0.5.0"
reqwest = { version = "0.12.15", default-features = false }
rust-s3 = { version = "0.35.1", default-features = false, features = [
"fail-on-err",
Expand Down
31 changes: 18 additions & 13 deletions apps/app-frontend/src/components/ui/AccountsCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
size="36px"
:src="
selectedAccount
? `https://mc-heads.net/avatar/${selectedAccount.id}/128`
? `https://mc-heads.net/avatar/${selectedAccount.profile.id}/128`
: 'https://launcher-files.modrinth.com/assets/steve_head.png'
"
/>
<div class="flex flex-col w-full">
<span>{{ selectedAccount ? selectedAccount.username : 'Select account' }}</span>
<span>{{ selectedAccount ? selectedAccount.profile.name : 'Select account' }}</span>
<span class="text-secondary text-xs">Minecraft account</span>
</div>
<DropdownIcon class="w-5 h-5 shrink-0" />
Expand All @@ -28,12 +28,17 @@
:class="{ expanded: mode === 'expanded', isolated: mode === 'isolated' }"
>
<div v-if="selectedAccount" class="selected account">
<Avatar size="xs" :src="`https://mc-heads.net/avatar/${selectedAccount.id}/128`" />
<Avatar size="xs" :src="`https://mc-heads.net/avatar/${selectedAccount.profile.id}/128`" />
<div>
<h4>{{ selectedAccount.username }}</h4>
<h4>{{ selectedAccount.profile.name }}</h4>
<p>Selected</p>
</div>
<Button v-tooltip="'Log out'" icon-only color="raised" @click="logout(selectedAccount.id)">
<Button
v-tooltip="'Log out'"
icon-only
color="raised"
@click="logout(selectedAccount.profile.id)"
>
<TrashIcon />
</Button>
</div>
Expand All @@ -44,12 +49,12 @@
</Button>
</div>
<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.profile.id" class="account-row">
<Button class="option account" @click="setAccount(account)">
<Avatar :src="`https://mc-heads.net/avatar/${account.id}/128`" class="icon" />
<p>{{ account.username }}</p>
<Avatar :src="`https://mc-heads.net/avatar/${account.profile.id}/128`" class="icon" />
<p>{{ account.profile.name }}</p>
</Button>
<Button v-tooltip="'Log out'" icon-only @click="logout(account.id)">
<Button v-tooltip="'Log out'" icon-only @click="logout(account.profile.id)">
<TrashIcon />
</Button>
</div>
Expand Down Expand Up @@ -101,16 +106,16 @@ defineExpose({
await refreshValues()

const displayAccounts = computed(() =>
accounts.value.filter((account) => defaultUser.value !== account.id),
accounts.value.filter((account) => defaultUser.value !== account.profile.id),
)

const selectedAccount = computed(() =>
accounts.value.find((account) => account.id === defaultUser.value),
accounts.value.find((account) => account.profile.id === defaultUser.value),
)

async function setAccount(account) {
defaultUser.value = account.id
await set_default_user(account.id).catch(handleError)
defaultUser.value = account.profile.id
await set_default_user(account.profile.id).catch(handleError)
emit('change')
}

Expand Down
2 changes: 1 addition & 1 deletion apps/app-frontend/src/components/ui/ErrorModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ async function loginMinecraft() {
const loggedIn = await login_flow()

if (loggedIn) {
await set_default_user(loggedIn.id).catch(handleError)
await set_default_user(loggedIn.profile.id).catch(handleError)
}

await trackEvent('AccountLogIn', { source: 'ErrorModal' })
Expand Down
5 changes: 4 additions & 1 deletion apps/app-playground/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ pub async fn authenticate_run() -> theseus::Result<Credentials> {

let credentials = minecraft_auth::finish_login(&input, login).await?;

println!("Logged in user {}.", credentials.username);
println!(
"Logged in user {}.",
credentials.maybe_online_profile().await.name
);
Ok(credentials)
}

Expand Down
1 change: 0 additions & 1 deletion apps/app/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ fn main() {
"profile_update_managed_modrinth_version",
"profile_repair_managed_modrinth",
"profile_run",
"profile_run_credentials",
"profile_kill",
"profile_edit",
"profile_edit_icon",
Expand Down
17 changes: 0 additions & 17 deletions apps/app/src/api/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
profile_update_managed_modrinth_version,
profile_repair_managed_modrinth,
profile_run,
profile_run_credentials,
profile_kill,
profile_edit,
profile_edit_icon,
Expand Down Expand Up @@ -256,22 +255,6 @@ pub async fn profile_run(path: &str) -> Result<ProcessMetadata> {
Ok(process)
}

// Run Minecraft using a profile using chosen credentials
// Returns the UUID, which can be used to poll
// for the actual Child in the state.
// invoke('plugin:profile|profile_run_credentials', {path, credentials})')
#[tauri::command]
pub async fn profile_run_credentials(
path: &str,
credentials: Credentials,
) -> Result<ProcessMetadata> {
let process =
profile::run_credentials(path, &credentials, &QuickPlayType::None)
.await?;

Ok(process)
}

#[tauri::command]
pub async fn profile_kill(path: &str) -> Result<()> {
profile::kill(path).await?;
Expand Down
1 change: 1 addition & 0 deletions packages/app-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ tracing-subscriber = { workspace = true, features = ["chrono", "env-filter"] }
tracing-error.workspace = true

paste.workspace = true
heck.workspace = true

tauri = { workspace = true, optional = true }
indicatif = { workspace = true, optional = true }
Expand Down
20 changes: 13 additions & 7 deletions packages/app-lib/src/api/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,27 @@ pub struct LatestLogCursor {
#[serde(transparent)]
pub struct CensoredString(String);
impl CensoredString {
pub fn censor(mut s: String, credentials_set: &Vec<Credentials>) -> Self {
pub fn censor(mut s: String, credentials_list: &[Credentials]) -> Self {
let username = whoami::username();
s = s
.replace(&format!("/{username}/"), "/{COMPUTER_USERNAME}/")
.replace(&format!("\\{username}\\"), "\\{COMPUTER_USERNAME}\\");
for credentials in credentials_set {
for credentials in credentials_list {
// Use the offline profile to guarantee that this function is does not cause
// Mojang API request, and is never delayed by a network request. The offline
// profile is optimistically updated on upsert from time to time anyway
s = s
.replace(&credentials.access_token, "{MINECRAFT_ACCESS_TOKEN}")
.replace(&credentials.username, "{MINECRAFT_USERNAME}")
.replace(
&credentials.id.as_simple().to_string(),
&credentials.offline_profile.name,
"{MINECRAFT_USERNAME}",
)
.replace(
&credentials.offline_profile.id.as_simple().to_string(),
"{MINECRAFT_UUID}",
)
.replace(
&credentials.id.as_hyphenated().to_string(),
&credentials.offline_profile.id.as_hyphenated().to_string(),
"{MINECRAFT_UUID}",
);
}
Expand Down Expand Up @@ -210,7 +216,7 @@ pub async fn get_output_by_filename(
.await?
.into_iter()
.map(|x| x.1)
.collect();
.collect::<Vec<_>>();

// Load .gz file into String
if let Some(ext) = path.extension() {
Expand Down Expand Up @@ -350,7 +356,7 @@ pub async fn get_generic_live_log_cursor(
.await?
.into_iter()
.map(|x| x.1)
.collect();
.collect::<Vec<_>>();
let output = CensoredString::censor(output, &credentials);
Ok(LatestLogCursor {
cursor,
Expand Down
4 changes: 2 additions & 2 deletions packages/app-lib/src/api/minecraft_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ pub async fn finish_login(
#[tracing::instrument]
pub async fn get_default_user() -> crate::Result<Option<uuid::Uuid>> {
let state = State::get().await?;
let users = Credentials::get_active(&state.pool).await?;
Ok(users.map(|x| x.id))
let user = Credentials::get_active(&state.pool).await?;
Ok(user.map(|user| user.offline_profile.id))
}

#[tracing::instrument]
Expand Down
3 changes: 1 addition & 2 deletions packages/app-lib/src/api/profile/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,10 +642,9 @@ pub async fn run(
}

/// Run Minecraft using a profile, and credentials for authentication
/// Returns Arc pointer to RwLock to Child
#[tracing::instrument(skip(credentials))]

pub async fn run_credentials(
async fn run_credentials(
path: &str,
credentials: &Credentials,
quick_play_type: &QuickPlayType,
Expand Down
17 changes: 10 additions & 7 deletions packages/app-lib/src/launcher/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ fn parse_jvm_argument(
}

#[allow(clippy::too_many_arguments)]
pub fn get_minecraft_arguments(
pub async fn get_minecraft_arguments(
arguments: Option<&[Argument]>,
legacy_arguments: Option<&str>,
credentials: &Credentials,
Expand All @@ -224,6 +224,9 @@ pub fn get_minecraft_arguments(
java_arch: &str,
quick_play_type: &QuickPlayType,
) -> crate::Result<Vec<String>> {
let access_token = credentials.access_token.clone();
let profile = credentials.maybe_online_profile().await;

if let Some(arguments) = arguments {
let mut parsed_arguments = Vec::new();

Expand All @@ -233,9 +236,9 @@ pub fn get_minecraft_arguments(
|arg| {
parse_minecraft_argument(
arg,
&credentials.access_token,
&credentials.username,
credentials.id,
&access_token,
&profile.name,
profile.id,
version,
asset_index_name,
game_directory,
Expand All @@ -255,9 +258,9 @@ pub fn get_minecraft_arguments(
for x in legacy_arguments.split(' ') {
parsed_arguments.push(parse_minecraft_argument(
&x.replace(' ', TEMPORARY_REPLACE_CHAR),
&credentials.access_token,
&credentials.username,
credentials.id,
&access_token,
&profile.name,
profile.id,
version,
asset_index_name,
game_directory,
Expand Down
31 changes: 3 additions & 28 deletions packages/app-lib/src/launcher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use daedalus::minecraft::{LoggingSide, RuleAction, VersionInfo};
use daedalus::modded::LoaderVersion;
use serde::Deserialize;
use st::Profile;
use std::collections::HashMap;
use std::path::PathBuf;
use tokio::process::Command;

Expand Down Expand Up @@ -644,7 +643,8 @@ pub async fn launch_minecraft(
*resolution,
&java_version.architecture,
quick_play_type,
)?
)
.await?
.into_iter()
.collect::<Vec<_>>(),
)
Expand All @@ -655,7 +655,7 @@ pub async fn launch_minecraft(
if std::env::var("CARGO").is_ok() {
command.env_remove("DYLD_FALLBACK_LIBRARY_PATH");
}
// Java options should be set in instance options (the existence of _JAVA_OPTIONS overwites them)
// Java options should be set in instance options (the existence of _JAVA_OPTIONS overwrites them)
command.env_remove("_JAVA_OPTIONS");

command.envs(env_args);
Expand Down Expand Up @@ -694,31 +694,6 @@ pub async fn launch_minecraft(
})
.await?;

let mut censor_strings = HashMap::new();
let username = whoami::username();
censor_strings
.insert(format!("/{username}/"), "/{COMPUTER_USERNAME}/".to_string());
censor_strings.insert(
format!("\\{username}\\"),
"\\{COMPUTER_USERNAME}\\".to_string(),
);
censor_strings.insert(
credentials.access_token.clone(),
"{MINECRAFT_ACCESS_TOKEN}".to_string(),
);
censor_strings.insert(
credentials.username.clone(),
"{MINECRAFT_USERNAME}".to_string(),
);
censor_strings.insert(
credentials.id.as_simple().to_string(),
"{MINECRAFT_UUID}".to_string(),
);
censor_strings.insert(
credentials.id.as_hyphenated().to_string(),
"{MINECRAFT_UUID}".to_string(),
);

// If in tauri, and the 'minimize on launch' setting is enabled, minimize the window
#[cfg(feature = "tauri")]
{
Expand Down
17 changes: 11 additions & 6 deletions packages/app-lib/src/state/legacy_converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ use std::path::PathBuf;
use tokio::sync::Semaphore;
use uuid::Uuid;

use super::MinecraftProfile;

pub async fn migrate_legacy_data<'a, E>(exec: E) -> crate::Result<()>
where
E: sqlx::Executor<'a, Database = sqlx::Sqlite> + Copy,
Expand Down Expand Up @@ -119,13 +121,16 @@ where
.await
{
let minecraft_users_len = minecraft_auth.users.len();
for (uuid, credential) in minecraft_auth.users {
for (uuid, legacy_credentials) in minecraft_auth.users {
Credentials {
id: credential.id,
username: credential.username,
access_token: credential.access_token,
refresh_token: credential.refresh_token,
expires: credential.expires,
offline_profile: MinecraftProfile {
id: legacy_credentials.id,
name: legacy_credentials.username,
..MinecraftProfile::default()
},
access_token: legacy_credentials.access_token,
refresh_token: legacy_credentials.refresh_token,
expires: legacy_credentials.expires,
active: minecraft_auth.default_user == Some(uuid)
|| minecraft_users_len == 1,
}
Expand Down
Loading
Loading