| 1 | package net.minecraft.client.multiplayer;
|
| 2 |
|
| 3 | import com.google.common.base.Strings;
|
| 4 | import com.mojang.authlib.exceptions.MinecraftClientException;
|
| 5 | import com.mojang.authlib.minecraft.UserApiService;
|
| 6 | import com.mojang.authlib.minecraft.InsecurePublicKeyException.MissingException;
|
| 7 | import com.mojang.authlib.services.response.KeyPairResponse;
|
| 8 | import com.mojang.authlib.services.response.KeyPairResponse.KeyPair;
|
| 9 | import com.mojang.logging.LogUtils;
|
| 10 | import com.mojang.serialization.JsonOps;
|
| 11 | import java.io.BufferedReader;
|
| 12 | import java.io.IOException;
|
| 13 | import java.nio.ByteBuffer;
|
| 14 | import java.nio.file.Files;
|
| 15 | import java.nio.file.Path;
|
| 16 | import java.security.PublicKey;
|
| 17 | import java.time.DateTimeException;
|
| 18 | import java.time.Duration;
|
| 19 | import java.time.Instant;
|
| 20 | import java.util.Optional;
|
| 21 | import java.util.UUID;
|
| 22 | import java.util.concurrent.CompletableFuture;
|
| 23 | import net.fabricmc.api.EnvType;
|
| 24 | import net.fabricmc.api.Environment;
|
| 25 | import net.minecraft.SharedConstants;
|
| 26 | import net.minecraft.util.Crypt;
|
| 27 | import net.minecraft.util.CryptException;
|
| 28 | import net.minecraft.util.StrictJsonParser;
|
| 29 | import net.minecraft.util.Util;
|
| 30 | import net.minecraft.world.entity.player.ProfileKeyPair;
|
| 31 | import net.minecraft.world.entity.player.ProfilePublicKey;
|
| 32 | import net.minecraft.world.entity.player.ProfilePublicKey.Data;
|
| 33 | import org.jspecify.annotations.Nullable;
|
| 34 | import org.slf4j.Logger;
|
| 35 |
|
| 36 | @Environment(EnvType.CLIENT)
|
| 37 | public class AccountProfileKeyPairManager implements ProfileKeyPairManager {
|
| 38 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 39 | private static final Duration MINIMUM_PROFILE_KEY_REFRESH_INTERVAL = Duration.ofHours(1L);
|
| 40 | private static final Path PROFILE_KEY_PAIR_DIR = Path.of("profilekeys");
|
| 41 | private final UserApiService userApiService;
|
| 42 | private final Path profileKeyPairPath;
|
| 43 | private CompletableFuture<Optional<ProfileKeyPair>> keyPair = CompletableFuture.completedFuture(Optional.empty());
|
| 44 | private Instant nextProfileKeyRefreshTime = Instant.EPOCH;
|
| 45 |
|
| 46 | public AccountProfileKeyPairManager(final UserApiService userApiService, final UUID profileId, final Path gameDirectory) {
|
| 47 | this.userApiService = userApiService;
|
| 48 | this.profileKeyPairPath = gameDirectory.resolve(PROFILE_KEY_PAIR_DIR).resolve(profileId + ".json");
|
| 49 | }
|
| 50 |
|
| 51 | @Override
|
| 52 | public CompletableFuture<Optional<ProfileKeyPair>> prepareKeyPair() {
|
| 53 | this.nextProfileKeyRefreshTime = Instant.now().plus(MINIMUM_PROFILE_KEY_REFRESH_INTERVAL);
|
| 54 | this.keyPair = this.keyPair.thenCompose(this::readOrFetchProfileKeyPair);
|
| 55 | return this.keyPair;
|
| 56 | }
|
| 57 |
|
| 58 | @Override
|
| 59 | public boolean shouldRefreshKeyPair() {
|
| 60 | return this.keyPair.isDone() && Instant.now().isAfter(this.nextProfileKeyRefreshTime)
|
| 61 | ? this.keyPair.join().map(ProfileKeyPair::dueRefresh).orElse(true)
|
| 62 | : false;
|
| 63 | }
|
| 64 |
|
| 65 | private CompletableFuture<Optional<ProfileKeyPair>> readOrFetchProfileKeyPair(final Optional<ProfileKeyPair> cachedKeyPair) {
|
| 66 | return CompletableFuture.supplyAsync(() -> {
|
| 67 | if (cachedKeyPair.isPresent() && !cachedKeyPair.get().dueRefresh()) {
|
| 68 | if (!SharedConstants.IS_RUNNING_IN_IDE) {
|
| 69 | this.writeProfileKeyPair(null);
|
| 70 | }
|
| 71 |
|
| 72 | return cachedKeyPair;
|
| 73 | } else {
|
| 74 | try {
|
| 75 | ProfileKeyPair fetchedKeyPair = this.fetchProfileKeyPair(this.userApiService);
|
| 76 | this.writeProfileKeyPair(fetchedKeyPair);
|
| 77 | return Optional.ofNullable(fetchedKeyPair);
|
| 78 | } catch (IOException | CryptException | MinecraftClientException e) {
|
| 79 | LOGGER.error("Failed to retrieve profile key pair", e);
|
| 80 | this.writeProfileKeyPair(null);
|
| 81 | return cachedKeyPair;
|
| 82 | }
|
| 83 | }
|
| 84 | }, Util.nonCriticalIoPool());
|
| 85 | }
|
| 86 |
|
| 87 | private Optional<ProfileKeyPair> readProfileKeyPair() {
|
| 88 | if (Files.notExists(this.profileKeyPairPath)) {
|
| 89 | return Optional.empty();
|
| 90 | }
|
| 91 |
|
| 92 | try (BufferedReader bufferedReader = Files.newBufferedReader(this.profileKeyPairPath)) {
|
| 93 | return ProfileKeyPair.CODEC.parse(JsonOps.INSTANCE, StrictJsonParser.parse(bufferedReader)).result();
|
| 94 | } catch (Exception e) {
|
| 95 | LOGGER.error("Failed to read profile key pair file {}", this.profileKeyPairPath, e);
|
| 96 | return Optional.empty();
|
| 97 | }
|
| 98 | }
|
| 99 |
|
| 100 | private void writeProfileKeyPair(final @Nullable ProfileKeyPair profileKeyPair) {
|
| 101 | try {
|
| 102 | Files.deleteIfExists(this.profileKeyPairPath);
|
| 103 | } catch (IOException e) {
|
| 104 | LOGGER.error("Failed to delete profile key pair file {}", this.profileKeyPairPath, e);
|
| 105 | }
|
| 106 |
|
| 107 | if (profileKeyPair != null) {
|
| 108 | if (SharedConstants.IS_RUNNING_IN_IDE) {
|
| 109 | ProfileKeyPair.CODEC.encodeStart(JsonOps.INSTANCE, profileKeyPair).ifSuccess(jsonStr -> {
|
| 110 | try {
|
| 111 | Files.createDirectories(this.profileKeyPairPath.getParent());
|
| 112 | Files.writeString(this.profileKeyPairPath, jsonStr.toString());
|
| 113 | } catch (Exception e) {
|
| 114 | LOGGER.error("Failed to write profile key pair file {}", this.profileKeyPairPath, e);
|
| 115 | }
|
| 116 | });
|
| 117 | }
|
| 118 | }
|
| 119 | }
|
| 120 |
|
| 121 | private @Nullable ProfileKeyPair fetchProfileKeyPair(final UserApiService userApiService) throws CryptException, IOException {
|
| 122 | KeyPairResponse keyPair = userApiService.getKeyPair();
|
| 123 | if (keyPair != null) {
|
| 124 | Data publicKeyData = parsePublicKey(keyPair);
|
| 125 | return new ProfileKeyPair(
|
| 126 | Crypt.stringToPemRsaPrivateKey(keyPair.keyPair().privateKey()), new ProfilePublicKey(publicKeyData), Instant.parse(keyPair.refreshedAfter())
|
| 127 | );
|
| 128 | } else {
|
| 129 | return null;
|
| 130 | }
|
| 131 | }
|
| 132 |
|
| 133 | private static Data parsePublicKey(final KeyPairResponse response) throws CryptException {
|
| 134 | KeyPair keyPair = response.keyPair();
|
| 135 | if (keyPair != null
|
| 136 | && !Strings.isNullOrEmpty(keyPair.publicKey())
|
| 137 | && response.publicKeySignature() != null
|
| 138 | && response.publicKeySignature().array().length != 0) {
|
| 139 | try {
|
| 140 | Instant expiresAt = Instant.parse(response.expiresAt());
|
| 141 | PublicKey key = Crypt.stringToRsaPublicKey(keyPair.publicKey());
|
| 142 | ByteBuffer signature = response.publicKeySignature();
|
| 143 | return new Data(expiresAt, key, signature.array());
|
| 144 | } catch (DateTimeException | IllegalArgumentException e) {
|
| 145 | throw new CryptException(e);
|
| 146 | }
|
| 147 | } else {
|
| 148 | throw new CryptException(new MissingException("Missing public key"));
|
| 149 | }
|
| 150 | }
|
| 151 | }
|
| 152 |
|