Skip to content
Closed
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
24 changes: 24 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,27 @@ out/

temp/
tmp/

# Downloaded libraries
/libraries/

# SQLite database
*.sqlite
*.sqlite-journal

# Secrets
secret-key.bin

# Minecraft runtime data
/minecraft/.fabric/
/minecraft/config/viafabricplus/
/minecraft/data/
/minecraft/downloads/
/minecraft/mods/

# Spark profiling tmp
/config/spark/

# MC Downloads
/mc-downloads/
/logs
Binary file added builder.txt
Binary file not shown.
21 changes: 13 additions & 8 deletions javadoc/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,7 @@ dependencies {
}
}

// Configure mod compile classpath - mod project is already evaluated due to evaluationDependsOn
val javadocTask = tasks.named<Javadoc>("javadoc")
val modCompileClasspath = project(":mod").extensions
.getByType<SourceSetContainer>()["main"].compileClasspath

javadocTask.configure {
classpath = classpath.plus(modCompileClasspath)
}
val modCompileClasspath = project(":mod").configurations.named("compileClasspath")

val usedJavadocTool: Provider<JavadocTool> = javaToolchains.javadocToolFor {
languageVersion = JavaLanguageVersion.of(25)
Expand All @@ -51,6 +44,18 @@ tasks {
opts.addBooleanOption("-enable-preview", true)
opts.source = "25"

rootProject.subprojects.forEach { subproject ->
if (subproject.name != "javadoc" && subproject.name != "data-generator" && subproject.plugins.hasPlugin("java")) {
val delombokTask = subproject.tasks.findByName("delombok")
if (delombokTask != null) {
dependsOn(delombokTask)
}
}
}

notCompatibleWithConfigurationCache("Uses cross-project classpaths")

classpath = classpath.plus(modCompileClasspath.get())
javadocTool = usedJavadocTool
}

Expand Down
49 changes: 36 additions & 13 deletions mod/src/main/java/com/soulfiremc/server/InstanceManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -249,13 +249,22 @@ private void refreshExpiredAccounts() {
log.info("Refreshing expired accounts");
}

accounts.add(authService.refresh(
account,
settingsSource.get(AccountSettings.USE_PROXIES_FOR_ACCOUNT_AUTH)
? SFHelpers.getRandomEntry(settingsSource.proxies()) : null,
scheduler
).join());
refreshed++;
try {
accounts.add(authService.refresh(
account,
settingsSource.get(AccountSettings.USE_PROXIES_FOR_ACCOUNT_AUTH)
? SFHelpers.getRandomEntry(settingsSource.proxies()) : null,
scheduler
).join());
refreshed++;
} catch (CompletionException e) {
if (e.getCause() instanceof UnsupportedOperationException) {
log.warn("Account {} cannot be refreshed: {}", account.lastKnownName(), e.getCause().getMessage());
accounts.add(account);
} else {
throw e;
}
}
} else {
accounts.add(account);
}
Expand Down Expand Up @@ -288,12 +297,21 @@ private MinecraftAccount refreshAccount(MinecraftAccount account) {
}

log.info("Account {} is expired, refreshing before connecting", account.lastKnownName());
var refreshedAccount = authService.refresh(
account,
settingsSource.get(AccountSettings.USE_PROXIES_FOR_ACCOUNT_AUTH)
? SFHelpers.getRandomEntry(settingsSource.proxies()) : null,
scheduler
).join();
MinecraftAccount refreshedAccount;
try {
refreshedAccount = authService.refresh(
account,
settingsSource.get(AccountSettings.USE_PROXIES_FOR_ACCOUNT_AUTH)
? SFHelpers.getRandomEntry(settingsSource.proxies()) : null,
scheduler
).join();
} catch (CompletionException e) {
if (e.getCause() instanceof UnsupportedOperationException) {
log.warn("Account {} cannot be refreshed: {}", account.lastKnownName(), e.getCause().getMessage());
return account;
}
throw e;
}
var accounts = new ArrayList<>(settingsSource.accounts().values());
accounts.replaceAll(a -> a.authType().equals(refreshedAccount.authType())
&& a.profileId().equals(refreshedAccount.profileId()) ? refreshedAccount : a);
Expand Down Expand Up @@ -427,6 +445,11 @@ private void start() {
var factories = new ArrayBlockingQueue<BotConnectionFactory>(botAmount);
while (!accountQueue.isEmpty()) {
var minecraftAccount = refreshAccount(accountQueue.poll());
var postRefreshAuthService = MCAuthService.convertService(minecraftAccount.authType());
if (postRefreshAuthService.isExpired(minecraftAccount)) {
log.warn("Skipping account {} because its authentication is expired and cannot be refreshed", minecraftAccount.lastKnownName());
continue;
}
var lastAccountObject = new AtomicReference<>(minecraftAccount);
var proxyData = getProxy(proxies).orElse(null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public enum AuthType {
MICROSOFT_JAVA_DEVICE_CODE("Microsoft Java Device Code", OnlineChainJavaData.class),
MICROSOFT_BEDROCK_DEVICE_CODE("Microsoft Bedrock Device Code", BedrockData.class),
MICROSOFT_JAVA_REFRESH_TOKEN("Microsoft Java Refresh Token", OnlineChainJavaData.class),
MICROSOFT_JAVA_ACCESS_TOKEN("Microsoft Java Access Token", OnlineChainJavaData.class),
OFFLINE("Offline", OfflineJavaData.class);

private final String displayName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@
import java.util.function.Consumer;

public sealed interface MCAuthService<I, T>
permits MSBedrockCredentialsAuthService, MSBedrockDeviceCodeAuthService, MSJavaCredentialsAuthService, MSJavaDeviceCodeAuthService, MSJavaRefreshTokenAuthService, OfflineAuthService {
permits MSBedrockCredentialsAuthService, MSBedrockDeviceCodeAuthService, MSJavaAccessTokenAuthService, MSJavaCookiesAuthService, MSJavaCredentialsAuthService, MSJavaDeviceCodeAuthService, MSJavaRefreshTokenAuthService, OfflineAuthService {
static MCAuthService<String, ?> convertService(AccountTypeCredentials service) {
return switch (service) {
case MICROSOFT_JAVA_CREDENTIALS -> MSJavaCredentialsAuthService.INSTANCE;
case MICROSOFT_BEDROCK_CREDENTIALS -> MSBedrockCredentialsAuthService.INSTANCE;
case OFFLINE -> OfflineAuthService.INSTANCE;
case MICROSOFT_JAVA_REFRESH_TOKEN -> MSJavaRefreshTokenAuthService.INSTANCE;
case MICROSOFT_JAVA_ACCESS_TOKEN -> MSJavaAccessTokenAuthService.INSTANCE;
case MICROSOFT_JAVA_COOKIES -> MSJavaCookiesAuthService.INSTANCE;
case UNRECOGNIZED -> throw new IllegalArgumentException("Unrecognized service");
};
}
Expand All @@ -56,6 +58,7 @@ public sealed interface MCAuthService<I, T>
case MICROSOFT_JAVA_DEVICE_CODE -> MSJavaDeviceCodeAuthService.INSTANCE;
case MICROSOFT_BEDROCK_DEVICE_CODE -> MSBedrockDeviceCodeAuthService.INSTANCE;
case MICROSOFT_JAVA_REFRESH_TOKEN -> MSJavaRefreshTokenAuthService.INSTANCE;
case MICROSOFT_JAVA_ACCESS_TOKEN -> MSJavaAccessTokenAuthService.INSTANCE;
case UNRECOGNIZED -> throw new IllegalArgumentException("Unrecognized service");
};
}
Expand All @@ -68,6 +71,7 @@ public sealed interface MCAuthService<I, T>
case MICROSOFT_BEDROCK_DEVICE_CODE -> MSBedrockDeviceCodeAuthService.INSTANCE;
case OFFLINE -> OfflineAuthService.INSTANCE;
case MICROSOFT_JAVA_REFRESH_TOKEN -> MSJavaRefreshTokenAuthService.INSTANCE;
case MICROSOFT_JAVA_ACCESS_TOKEN -> MSJavaAccessTokenAuthService.INSTANCE;
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* SoulFire
* Copyright (C) 2026 AlexProgrammerDE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.soulfiremc.server.account;

import com.google.gson.JsonObject;
import com.soulfiremc.server.account.service.OnlineChainJavaData;
import com.soulfiremc.server.proxy.SFProxy;
import com.soulfiremc.server.util.structs.GsonInstance;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

public final class MSJavaAccessTokenAuthService
implements MCAuthService<String, MSJavaAccessTokenAuthService.MSJavaAccessTokenAuthData> {
public static final MSJavaAccessTokenAuthService INSTANCE = new MSJavaAccessTokenAuthService();
private static final String PROFILE_URL = "https://api.minecraftservices.com/minecraft/profile";
private static final long EXPIRY_SKEW_SECONDS = 30;

private MSJavaAccessTokenAuthService() {}

@Override
public CompletableFuture<MinecraftAccount> login(MSJavaAccessTokenAuthData data, @Nullable SFProxy proxyData, Executor executor) {
return CompletableFuture.supplyAsync(() -> {
try {
var profileJson = fetchProfile(data.accessToken);
Comment on lines +47 to +51
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

proxyData is accepted by login(...) but never used (the profile request uses a raw HttpURLConnection). This breaks the existing "use proxies for account auth" behavior for access-token imports; consider using the project’s HTTP helpers (e.g., ReactorHttpHelper/LenniHttpHelper) so proxy settings and shared defaults are honored.

Suggested change
@Override
public CompletableFuture<MinecraftAccount> login(MSJavaAccessTokenAuthData data, @Nullable SFProxy proxyData, Executor executor) {
return CompletableFuture.supplyAsync(() -> {
try {
var profileJson = fetchProfile(data.accessToken);
private JsonObject fetchProfile(String accessToken, @Nullable SFProxy proxyData) throws Exception {
// Delegate to the existing implementation for now; proxyData is threaded through
// so that proxy-aware logic can be implemented here without changing callers.
return fetchProfile(accessToken);
}
@Override
public CompletableFuture<MinecraftAccount> login(MSJavaAccessTokenAuthData data, @Nullable SFProxy proxyData, Executor executor) {
return CompletableFuture.supplyAsync(() -> {
try {
var profileJson = fetchProfile(data.accessToken, proxyData);

Copilot uses AI. Check for mistakes.

var id = profileJson.get("id").getAsString();
// Convert from undashed to dashed UUID format
var profileId = UUID.fromString(
id.replaceFirst("(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)",
"$1-$2-$3-$4-$5"));
var name = profileJson.get("name").getAsString();

// We don't have a full auth chain, so we store minimal data.
// The access token is stored so it can be used for server joining.
var authChain = new JsonObject();
authChain.addProperty("_saveVersion", 1);
authChain.addProperty("_accessToken", data.accessToken);
authChain.addProperty("_profileId", profileId.toString());
authChain.addProperty("_profileName", name);
authChain.addProperty("_accessTokenOnly", true);

return new MinecraftAccount(
AuthType.MICROSOFT_JAVA_ACCESS_TOKEN,
profileId,
name,
new OnlineChainJavaData(authChain),
Map.of(),
Map.of());
} catch (Exception e) {
throw new CompletionException(e);
}
}, executor);
}

private JsonObject fetchProfile(String accessToken) throws Exception {
var url = URI.create(PROFILE_URL).toURL();
var connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Accept", "application/json");
connection.setConnectTimeout(10_000);
connection.setReadTimeout(10_000);

var statusCode = connection.getResponseCode();
if (statusCode != 200) {
// Try to read error body for better diagnostics
var errorStream = connection.getErrorStream();
var errorBody = "";
if (errorStream != null) {
try (var reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8))) {
errorBody = reader.lines().collect(Collectors.joining("\n"));
}
}
throw new IllegalStateException("Failed to fetch Minecraft profile: HTTP " + statusCode + " " + errorBody);
}

try (var reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
var body = reader.lines().collect(Collectors.joining("\n"));
return GsonInstance.GSON.fromJson(body, JsonObject.class);
Comment on lines +91 to +106
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connection.disconnect() is only executed on the success path; if statusCode != 200 this method throws before reaching the finally, leaving the HttpURLConnection open. Wrap the whole request/response handling in a try/finally (or disconnect in the error branch) so the connection is always cleaned up.

Suggested change
var statusCode = connection.getResponseCode();
if (statusCode != 200) {
// Try to read error body for better diagnostics
var errorStream = connection.getErrorStream();
var errorBody = "";
if (errorStream != null) {
try (var reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8))) {
errorBody = reader.lines().collect(Collectors.joining("\n"));
}
}
throw new IllegalStateException("Failed to fetch Minecraft profile: HTTP " + statusCode + " " + errorBody);
}
try (var reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
var body = reader.lines().collect(Collectors.joining("\n"));
return GsonInstance.GSON.fromJson(body, JsonObject.class);
try {
var statusCode = connection.getResponseCode();
if (statusCode != 200) {
// Try to read error body for better diagnostics
var errorStream = connection.getErrorStream();
var errorBody = "";
if (errorStream != null) {
try (var reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8))) {
errorBody = reader.lines().collect(Collectors.joining("\n"));
}
}
throw new IllegalStateException("Failed to fetch Minecraft profile: HTTP " + statusCode + " " + errorBody);
}
try (var reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
var body = reader.lines().collect(Collectors.joining("\n"));
return GsonInstance.GSON.fromJson(body, JsonObject.class);
}

Copilot uses AI. Check for mistakes.
} finally {
connection.disconnect();
}
}

@Override
public MSJavaAccessTokenAuthData createData(String data) {
return new MSJavaAccessTokenAuthData(data.strip());
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

createData accepts an empty/blank access token (after strip()), which will later fail with a less actionable HTTP error. Consider validating non-empty input (and possibly rejecting obvious cookie/refresh-token formats) to give callers a clear IllegalArgumentException early.

Suggested change
return new MSJavaAccessTokenAuthData(data.strip());
var stripped = data.strip();
if (stripped.isEmpty()) {
throw new IllegalArgumentException("Access token must not be empty or blank");
}
return new MSJavaAccessTokenAuthData(stripped);

Copilot uses AI. Check for mistakes.
}

@Override
public CompletableFuture<MinecraftAccount> refresh(MinecraftAccount account, @Nullable SFProxy proxyData, Executor executor) {
return CompletableFuture.failedFuture(
new UnsupportedOperationException("Access token accounts cannot be refreshed. Please re-import the account with a new access token."));
}

@Override
public boolean isExpired(MinecraftAccount account) {
var accessToken = ((OnlineChainJavaData) account.accountData()).getAccessToken(null);
var expSeconds = getJwtExpSeconds(accessToken);
if (expSeconds == null) {
return false;
}
var nowSeconds = System.currentTimeMillis() / 1000;
return nowSeconds >= (expSeconds - EXPIRY_SKEW_SECONDS);
}

private static @Nullable Long getJwtExpSeconds(String accessToken) {
var parts = accessToken.split("\\.");
if (parts.length < 2) {
return null;
}

try {
var payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
var payload = GsonInstance.GSON.fromJson(payloadJson, JsonObject.class);
if (payload == null || !payload.has("exp")) {
return null;
}
return payload.get("exp").getAsLong();
} catch (Exception _) {
return null;
}
}

public record MSJavaAccessTokenAuthData(String accessToken) {}
}
Loading