aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/kr/syeyoung/dungeonsguide/auth
diff options
context:
space:
mode:
authorEryk Ruta <70776766+kingstefan26@users.noreply.github.com>2022-11-01 15:51:30 +0100
committerGitHub <noreply@github.com>2022-11-01 23:51:30 +0900
commit292fbd05e13271ca3ad99ebe00ae4302e04848f3 (patch)
tree2a7aeb12ab95ff688479a4727f76e3e4152c30b5 /src/main/java/kr/syeyoung/dungeonsguide/auth
parentdd7a4209752715db544b2fef804da9762c532cdc (diff)
downloadSkyblock-Dungeons-Guide-292fbd05e13271ca3ad99ebe00ae4302e04848f3.tar.gz
Skyblock-Dungeons-Guide-292fbd05e13271ca3ad99ebe00ae4302e04848f3.tar.bz2
Skyblock-Dungeons-Guide-292fbd05e13271ca3ad99ebe00ae4302e04848f3.zip
3rd time is the charm (#70)
* Updated some dependencies, used my crusty skytils forgegradle fork + removed the IRRELEVANT hytils fixes. generally made the thing build * made the logs less annoying * temp fix so it doesn't throw an exception * FAT REFACTOR General refactor on Authenticator.java DungeonsGuide.java Main.java removed unnecessary imports where not needed to be removed DGInterface.java (no real reason to exist) in DungeonsGuide.java made the retry stomp a singe-thread executor, so it doesn't leak when offline added an "offline mode" so it doesn't just error when server down TODO: move auth to DungeonsGuide.java and make it retry when network down on launch * New auth implementation that should replace the old one: does all the things the old one did removed progressBar cuz it would make the impl 3x more complicated in the name of a splash screen added a token changed event (so now it supports re-logging with a different account) code is (should) be more readable / extensible TODO: surgically replace Authenticator.java with new impl AND support re-logging * Made the chat processor logger name less obnoxious * implemented my implementation of an implementation of auth can and is very buggy, essentially the loading of the remote classes but the mod works so idk TODO: MAKE STOMP NOT DO STUFF TILL STOMPCONNECTED IS EMITTED * fix for stomp client null bc forge events not going tru on pre-init TODO: make work and test the web loadable classes, then make all the stuff that relies on stomp not throw exceptions when stomp is not connected * move the create auth method into AuthProvider interface, so we don't clutter AuthManager with implementation details * Decouple AuthProviderUtil and DgAuth, move some stuff around and make it more readable * moved AuthUtil to make more sense * de-clutter the tree a little bit * Inline StompClientStatus.java / refactor * inline the useless interface * refactoringgg * fix ahUtils exeption spam * small StompClient refactor * fix GLCursors exeption spam + logger * make sure we are authenticated when downloading resources * new .destination("value") instead of .header("destination", "value") * StompMessageHandler -> StompMessageSubscription * Introduced StompManager * fix dungeon map not showing ppl heads * ehhh * wip (commit cuz im chekig out) * fix player profile not never loading in chat * remove this specific line * fix player profile not never loading in chat * cut out hychat like a cancer * ApiFetchur now caches whole players not single profiles, added a switch profile button in gui * ugh git * Revert "cut out hychat like a cancer" This reverts commit 2ee11afa * ugh git x2 * I tried, good luck maintaining this * forgot to uncomment hychat fix * make my new party ready work and look ok * change the look and add some "somewhere" locations * make stomp connection "null safe" * i hate git * introduce callbacks on parameter change for cleaner code add one example * impl new system, half way done * now shows which profile is now selected put button on top a lil refactor * fix player profile sometimes not loading * add players knowing who is using dg (try to) * announcing that we are a dg user will get reworked in the future * update deps * make it not spam logs * sanity check for premium features so it doesn't 403 * add YoMamaOutdated that checks if you are using outdated dg * hychat?? anyone * try catch in FeatureRegistry * added Ether transmission ability * chat shredder borken, disabled for now * party deserves its own folder * dungeon stuff in dungeon folder * events folders moved * fix score data collection hanging forever if stomp is not connected * fix stomp never connecting * re-add the removed * fix wonky rendering * server side implementation is not ready, canning this for a future release * attempt to fix heads loading on main thread * discord * me when sonar lint * new consumer based stomp subscriptions * replace old with new subscriptions * remove the remains of StompSubscription and replace CloseListener with a forge event * StompSubscription is now a functional interface * remove unnecessary event message chains, feature logic should be in the feature * fix events being set up wrongly * Revert "fix events being set up wrongly" This reverts commit e6ea7efa557a5f5c8a3ea33be998717bc024b8cb. * Revert "remove unnecessary event message chains," This reverts commit 96f508bae85b33cdcef6be19226c00fc52a1439b. * fix stomp client sending payload object instead of the actual payload * fix null pointer on empty party * fix players with cosmetics name being white in tab * added message when not connected to dg changed YoMamaOutdated to use CloudFlare workers added client sided message queue * the mod doesn't init when outdated * mcmod.info * dont busy wait in authmenager * test pepole crusty tests * chill out the authmanager * name the thread pool in auth manager * clear most compiler warnings * make outdated check allow to play without the mod initialized * make first startup VERY noticeable, move config creation to main * major dungeon package refactor * refactor checkpoint * refactor checkpoint #1 * final refactor checkpoint #2 * remove the player if from version check, made the version check not nesssery for playing Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * remove trap room fix that didnt fix anything Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * make secret beacons optional Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * make the checkmarks on map align with the rest of everyone Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * removed debug function Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move the menus to make more sense + make destination text on secrets optional Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * improve dungeonMap performance by ~90% temporarly disabled 9 slot map player location due to bugs fix DungeonContext not getting player from ScoreBoard Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * add epic countdown on dungeon start (still wip) Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * added a option to cache blockstaes Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * added TabListUtil Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * fixed epic countdown Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * (i want to sleep) made all the dungeon room detection async TODO: fix ol the bugs i created by doing that Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * stuff still broken but almost playable, unlike last commit Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * upload build jar to discord Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * cache the deps for the love of god Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * who needs linux and 32bit windows anyway Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * only upload to discord on beta branch Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * added "kick" when a member joins party Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move stuff that sends chat to player into a separate class Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * use our chat queue instead of calling `thePlayer.addChatMessage` to proxy ourselves from 1.8 code Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * Added and implemented MortDetector2000.java Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * extract duplicate + make more readable Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * added dummy support in FeatureDebugTrap Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * gradle now puts version in mcmod.info Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * remove side effects from DgAuth.java Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move debug commands into debug CommandDgDebug.java Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * fix key being wrong Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move epic countdown to dungeon huds, clean up Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * Revert "who needs linux and 32bit windows anyway" This reverts commit 0f3c2d544a70fc799cd3215dad5e997c0c8b6c06. * make FeatureRegistry not static initialise to get rid of "ClassNotDefined" errors Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * null check on Exception since it threw NullPointers Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * finish up progress bar in DungeonsGuide.java Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * warn about null features Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move stuff around in SkyblockStatus, move the stuff that updates status into SkyblockStatus from DungeonListener Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * rename DungeonGodObject.java to DungeonFacade.java Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * add cleanChat clause in FeatureEpicCountdown Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * implement getPreRequisites and isComplete in ActionBreakWithSuperBoom Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * clean up FeatureParameter Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * eliminate possible state inconsistency in DungeonListener Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move percentage from DungeonFacade to DungeonContext Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move `purge` and `partymax` back into CommandDungeonsGuide Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * stop repeating ReceiveChatQueue in ChatTransmitter Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * Clean up DungeonsGuide Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move `sendDebugChat` to `ChatTransmitter.java` Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * change CommandDgDebug into a `else if` from an `switch` because some bigot decided its better Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * duplicate code since it currently doesn't make sense, to be reworked Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * fix typo Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * remove the trycatch so we fail fast Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * fix null pointer when trying to get fontRenderer before minecraft is initialised Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * broken checkpoint 0 Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * broken checkpoint 1 Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * Revert "broken checkpoint 1" This reverts commit 64985e6287c7b5650b509668e42b9803e25c419c. * Revert "broken checkpoint 0" This reverts commit 5f62e1345d9c8e7f66f1e5792004a05027913d92. * Revert "fix null pointer when trying to get fontRenderer before minecraft is initialised" This reverts commit 57d92a78d31c410f699b58c8995c94055d57e2a4. * Revert "remove the trycatch so we fail fast" This reverts commit 12772255ed575e411fb99edf37ec16d0e5f42924. * Revert "fix typo" This reverts commit aa96cc2436d3ead42d53ead78f3334fac5100713. * Revert "duplicate code since it currently doesn't make sense, to be reworked" This reverts commit 6d71b88e3102d23bcfd90d85e8996327776fd52f. * Revert "change CommandDgDebug into a `else if` from an `switch` because some bigot decided its better" This reverts commit ffea84d9b5fd4adbe034a88249bc920eafa7c53a. * Revert "move `sendDebugChat` to `ChatTransmitter.java`" This reverts commit 5b8b2e22fff33768134a01c15c7650100ebb9257. * Revert "Clean up DungeonsGuide" This reverts commit 2069ad3ebc4344eb1e778954dc1d8f6c9303de69. * fix typo Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> (cherry picked from commit aa96cc2436d3ead42d53ead78f3334fac5100713) * duplicate code since it currently doesn't make sense, to be reworked Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> (cherry picked from commit 6d71b88e3102d23bcfd90d85e8996327776fd52f) * change CommandDgDebug into a `else if` from an `switch` because some bigot decided its better Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> (cherry picked from commit ffea84d9b5fd4adbe034a88249bc920eafa7c53a) * move debug chat into ChatTransmitter Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * null pointer in SkyblockStatus bc context was not initialised yet Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move dungeon starting door detection up the tree since it was a duplicate in both children, inline MortDetector2000 Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move dungeon name to DungeonContext Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * clean up Main Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * separate the "loader" and "mod" Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * separate DungeonsGuide and Main even more Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * change singleton implementation of DungeonsGuide Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move classes since their paths are hardcoded into roomdatas Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * create CatacombsDataProvider.java and implement it Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * remove unnecessary `DungeonsGuide.getDungeonsGuide();` (IntelliJ refactor bug) Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * move `help` text in commands Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * a certain someone hates switch statements Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * remove my version check, since we have to wait for out lord and savior to make his own Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * make `Main` and `DungeonsGuide` compatible with supported jar classloading Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * make the beta upload action run on push since it didnt get the secret on pull request and failed anyway, TODO: make the jar name not hardcoded Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> * upload all jar Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> Signed-off-by: kingstefan26 <70776766+kingstefan26@users.noreply.github.com> Co-authored-by: syeyoung <42869671+cyoung06@users.noreply.github.com>
Diffstat (limited to 'src/main/java/kr/syeyoung/dungeonsguide/auth')
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/AuthManager.java150
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/AuthUtil.java70
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/InvalidDungeonsGuideCredentialsException.java8
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/ResourceManager.java164
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/AuthProvider.java16
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuth.java46
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuthUtil.java88
-rw-r--r--src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/NullAuth.java62
8 files changed, 604 insertions, 0 deletions
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/AuthManager.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/AuthManager.java
new file mode 100644
index 00000000..5588a4a2
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/AuthManager.java
@@ -0,0 +1,150 @@
+package kr.syeyoung.dungeonsguide.auth;
+
+import com.google.common.base.Throwables;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import com.google.gson.JsonObject;
+import com.mojang.authlib.exceptions.AuthenticationException;
+import kr.syeyoung.dungeonsguide.auth.authprovider.AuthProvider;
+import kr.syeyoung.dungeonsguide.auth.authprovider.DgAuth.DgAuth;
+import kr.syeyoung.dungeonsguide.auth.authprovider.DgAuth.DgAuthUtil;
+import kr.syeyoung.dungeonsguide.mod.chat.ChatTransmitter;
+import kr.syeyoung.dungeonsguide.mod.events.impl.AuthChangedEvent;
+import kr.syeyoung.dungeonsguide.mod.stomp.StompManager;
+import lombok.Setter;
+import net.minecraft.client.Minecraft;
+import net.minecraftforge.common.MinecraftForge;
+import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
+import net.minecraftforge.fml.common.gameevent.TickEvent;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.IOException;
+import java.security.KeyPair;
+import java.security.NoSuchAlgorithmException;
+import java.util.Objects;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+
+public class AuthManager {
+ Logger logger = LogManager.getLogger("AuthManger");
+
+ private static AuthManager instance;
+
+ public static AuthManager getInstance() {
+ if(instance == null) instance = new AuthManager();
+ return instance;
+ }
+
+
+ @Setter
+ private String baseserverurl = "https://dungeons.guide";
+
+ private AuthProvider currentProvider;
+
+ public String getToken() {
+ if (currentProvider != null && currentProvider.getToken() != null) {
+ return currentProvider.getToken();
+ }
+ return null;
+ }
+
+ public KeyPair getKeyPair(){
+ if (currentProvider != null && currentProvider.getToken() != null) {
+ return currentProvider.getRsaKey();
+ }
+ return null;
+ }
+
+
+ boolean initlock = false;
+
+ public void init() {
+ if (initlock) {
+ logger.info("Cannot init AuthManger twice");
+ return;
+ }
+
+ reauth();
+
+ initlock = true;
+
+
+ MinecraftForge.EVENT_BUS.register(this);
+
+ ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("DgAuth Pool").build();
+ final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, namedThreadFactory);
+ scheduler.scheduleAtFixedRate(() -> {
+ if (getToken() != null) {
+ JsonObject obj = DgAuthUtil.getJwtPayload(getToken());
+ if (!obj.get("uuid").getAsString().replace("-", "").equals(Minecraft.getMinecraft().getSession().getPlayerID())) {
+ shouldReAuth = true;
+ }
+ }
+ }, 10,2000, TimeUnit.MILLISECONDS);
+ }
+
+ boolean shouldReAuth = true;
+ int tickCounter;
+
+ @SubscribeEvent
+ public void onTickClientTick(TickEvent.ClientTickEvent event) {
+ if (event.phase != TickEvent.Phase.START) return;
+
+ if (tickCounter % 200 == 0) {
+ tickCounter = 0;
+ reauth();
+ }
+ tickCounter++;
+
+ }
+
+ public boolean isPlebUser(){
+ return Objects.equals(getInstance().getPlanType(), "OPENSOURCE");
+ }
+
+ public String getPlanType(){
+ if(getToken() == null) return null;
+
+
+ JsonObject jwt = DgAuthUtil.getJwtPayload(getToken());
+
+ if(!jwt.has("plan")) return null;
+
+ return jwt.get("plan").getAsString();
+
+ }
+
+ void reauth() {
+ if (!shouldReAuth) return;
+
+ shouldReAuth = false;
+
+ currentProvider = null;
+ try {
+ currentProvider = new DgAuth(baseserverurl).createAuthProvider();
+ if (currentProvider.getToken() == null) {
+ shouldReAuth = true;
+ currentProvider = null;
+ ChatTransmitter.addToQueue("§eDungeons Guide §7:: §r§cDG auth failed, trying again in ten seconds", true);
+ logger.info("DG auth failed, trying again in a second");
+ } else {
+ // RE-AUTHed SUCCESSFULLY HOORAY
+ // for some reason the forge events don't work in pre init, so I call the callback directly
+ StompManager.getInstance().init();
+ MinecraftForge.EVENT_BUS.post(new AuthChangedEvent());
+ }
+ } catch (NoSuchAlgorithmException | AuthenticationException | IOException e) {
+
+ shouldReAuth = true;
+ currentProvider = null;
+ ChatTransmitter.addToQueue("§eDungeons Guide §7:: §r§cDG auth failed, trying again in ten seconds", true);
+ logger.error("Re-auth failed with message {}, trying again in a ten seconds", String.valueOf(Throwables.getRootCause(e)));
+ }
+
+ }
+
+
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/AuthUtil.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/AuthUtil.java
new file mode 100644
index 00000000..d96b054d
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/AuthUtil.java
@@ -0,0 +1,70 @@
+package kr.syeyoung.dungeonsguide.auth;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+
+import javax.crypto.*;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import javax.net.ssl.HttpsURLConnection;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.security.*;
+
+public class AuthUtil {
+ private AuthUtil() {}
+
+ public static KeyPair getKeyPair() throws NoSuchAlgorithmException {
+ KeyPairGenerator a = null;
+ a = KeyPairGenerator.getInstance("RSA");
+ a.initialize(1024);
+ return a.generateKeyPair();
+ }
+
+
+ public static JsonElement getJsonSecured(String u) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException{
+
+ int length = 0;
+ CipherInputStream cipherInputStream = null;
+
+ HttpsURLConnection httpsURLConnection = (HttpsURLConnection) new URL(u).openConnection();
+ httpsURLConnection.setRequestProperty("User-Agent", "DungeonsGuide/1.0");
+ httpsURLConnection.setRequestProperty("Content-Type", "application/json");
+ httpsURLConnection.setRequestMethod("GET");
+ httpsURLConnection.setRequestProperty("Authorization", AuthManager.getInstance().getToken());
+ httpsURLConnection.setDoInput(true);
+ httpsURLConnection.setDoOutput(true);
+
+ InputStream inputStream = httpsURLConnection.getInputStream();
+ byte[] lengthPayload = new byte[4];
+ inputStream.read(lengthPayload);
+ length = ((lengthPayload[0] & 0xFF) << 24) |
+ ((lengthPayload[1] & 0xFF) << 16) |
+ ((lengthPayload[2] & 0xFF) << 8) |
+ ((lengthPayload[3] & 0xFF));
+ while (inputStream.available() < length) ;
+ byte[] keyPayload = new byte[length];
+ inputStream.read(keyPayload);
+
+ Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
+ cipher.init(Cipher.DECRYPT_MODE, AuthManager.getInstance().getKeyPair().getPrivate());
+ byte[] AESKey = cipher.doFinal(keyPayload);
+
+ cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ SecretKeySpec secretKeySpec = new SecretKeySpec(AESKey, "AES");
+ IvParameterSpec ivParameterSpec = new IvParameterSpec(AESKey);
+ cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
+ cipherInputStream = new CipherInputStream(inputStream, cipher);
+ cipherInputStream.read(lengthPayload);
+ length = ((lengthPayload[0] & 0xFF) << 24) |
+ ((lengthPayload[1] & 0xFF) << 16) |
+ ((lengthPayload[2] & 0xFF) << 8) |
+ ((lengthPayload[3] & 0xFF));
+
+ httpsURLConnection.disconnect();
+
+ return new JsonParser().parse(new InputStreamReader(cipherInputStream));
+ }
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/InvalidDungeonsGuideCredentialsException.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/InvalidDungeonsGuideCredentialsException.java
new file mode 100644
index 00000000..98caa049
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/InvalidDungeonsGuideCredentialsException.java
@@ -0,0 +1,8 @@
+package kr.syeyoung.dungeonsguide.auth;
+
+public class InvalidDungeonsGuideCredentialsException extends Throwable {
+
+ public InvalidDungeonsGuideCredentialsException(String message) {
+ super(message);
+ }
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/ResourceManager.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/ResourceManager.java
new file mode 100644
index 00000000..56d46aea
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/ResourceManager.java
@@ -0,0 +1,164 @@
+package kr.syeyoung.dungeonsguide.auth;
+
+import lombok.Setter;
+import net.minecraftforge.common.MinecraftForge;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import javax.crypto.*;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import javax.net.ssl.HttpsURLConnection;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.*;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+public class ResourceManager {
+
+ Logger logger = LogManager.getLogger("ResourceManager");
+
+ @Setter
+ private String baseUrl;
+ @Setter
+ private String BASE64_X509ENCODEDKEYSPEC;
+ private final HashMap<String, byte[]> loadedResources = new HashMap<>();
+
+
+ private static ResourceManager instance;
+ public static ResourceManager getInstance() {
+ if(instance == null) {
+ instance = new ResourceManager();
+ MinecraftForge.EVENT_BUS.register(instance);
+ }
+ return instance;
+ }
+
+ private ResourceManager() {
+ }
+
+ public Map<String, byte[]> getResources() {
+ return loadedResources;
+ }
+
+
+ public void downloadAssets(String version) throws InvalidDungeonsGuideCredentialsException {
+ if(AuthManager.getInstance().getToken() == null) throw new InvalidDungeonsGuideCredentialsException("Not Authenticated while downloading assets");
+ try {
+ // version not being null indicates that the user is "premium"
+ // so we download the special version
+ if (version != null)
+ downloadSafe( baseUrl + "/resource/version?v=" + version, true);
+
+ if(!AuthManager.getInstance().isPlebUser()){
+ downloadSafe(baseUrl + "/resource/roomdata", false);
+ } else {
+ logger.error("The current User is a pleb not downloading user data");
+ }
+
+ } catch (Exception t) {
+ t.printStackTrace();
+ }
+
+ }
+
+ private void downloadSafe(String url, boolean isValidateSignature) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, SignatureException, InvalidKeySpecException {
+ HttpsURLConnection dgConnection = (HttpsURLConnection) new URL(url).openConnection();
+ dgConnection.setRequestProperty("User-Agent", "DungeonsGuide/1.0");
+ dgConnection.setRequestProperty("Content-Type", "application/json");
+ dgConnection.setRequestMethod("GET");
+ dgConnection.setRequestProperty("Authorization", AuthManager.getInstance().getToken());
+ dgConnection.setDoInput(true);
+ dgConnection.setDoOutput(true);
+
+ InputStream inputStream = dgConnection.getInputStream();
+ byte[] lengthBytes = new byte[4];
+ inputStream.read(lengthBytes);
+ int length = ((lengthBytes[0] & 0xFF) << 24) |
+ ((lengthBytes[1] & 0xFF) << 16) |
+ ((lengthBytes[2] & 0xFF) << 8) |
+ ((lengthBytes[3] & 0xFF));
+ while (inputStream.available() < length) ;
+ byte[] keyPayload = new byte[length];
+ inputStream.read(keyPayload);
+
+ Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
+ cipher.init(Cipher.DECRYPT_MODE, AuthManager.getInstance().getKeyPair().getPrivate());
+ byte[] h = cipher.doFinal(keyPayload);
+
+ cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ SecretKeySpec keySpec = new SecretKeySpec(h, "AES");
+ IvParameterSpec ivSpec = new IvParameterSpec(h);
+ cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
+ CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
+
+ cipherInputStream.read(lengthBytes);
+ length = ((lengthBytes[0] & 0xFF) << 24) |
+ ((lengthBytes[1] & 0xFF) << 16) |
+ ((lengthBytes[2] & 0xFF) << 8) |
+ ((lengthBytes[3] & 0xFF));
+
+ int totalLen = length;
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ byte[] buff = new byte[256];
+ while (totalLen > 0) {
+ int len = cipherInputStream.read(buff, 0, Math.min(buff.length, totalLen));
+ totalLen -= len;
+ bos.write(buff, 0, len);
+ }
+ byte[] body = bos.toByteArray();
+
+ byte[] signed;
+ if (isValidateSignature) {
+ cipherInputStream.read(lengthBytes,0 , 4);
+ length = ((lengthBytes[0] & 0xFF) << 24) |
+ ((lengthBytes[1] & 0xFF) << 16) |
+ ((lengthBytes[2] & 0xFF) << 8) |
+ ((lengthBytes[3] & 0xFF));
+
+ totalLen = length;
+ bos = new ByteArrayOutputStream();
+ while (totalLen > 0) {
+ int len = cipherInputStream.read(buff, 0, Math.min(buff.length, totalLen));
+ totalLen -= len;
+ bos.write(buff, 0, len);
+ }
+ signed = bos.toByteArray();
+
+ Signature sign = Signature.getInstance("SHA512withRSA");
+ sign.initVerify(getPublicKey(BASE64_X509ENCODEDKEYSPEC));
+ sign.update(body);
+ boolean truth = sign.verify(signed);
+ if (!truth) throw new SignatureException("DG SIGNATURE FORGED");
+ }
+
+ ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(body));
+ ZipEntry zipEntry;
+ while ((zipEntry=zipInputStream.getNextEntry()) != null) {
+ byte[] buffer = new byte[256];
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ int p;
+ while((p = zipInputStream.read(buffer)) > 0) {
+ byteArrayOutputStream.write(buffer, 0, p);
+ }
+ this.loadedResources.put(zipEntry.getName(), byteArrayOutputStream.toByteArray());
+ }
+ }
+
+
+ public static PublicKey getPublicKey(String base64X509EncodedKeySpec) throws NoSuchAlgorithmException, InvalidKeySpecException {
+ X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(base64X509EncodedKeySpec));
+
+ return KeyFactory.getInstance("RSA").generatePublic(spec);
+ }
+
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/AuthProvider.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/AuthProvider.java
new file mode 100644
index 00000000..ba42574e
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/AuthProvider.java
@@ -0,0 +1,16 @@
+package kr.syeyoung.dungeonsguide.auth.authprovider;
+
+import com.mojang.authlib.exceptions.AuthenticationException;
+
+import java.io.IOException;
+import java.security.KeyPair;
+import java.security.NoSuchAlgorithmException;
+
+public interface AuthProvider {
+ String getToken();
+
+ KeyPair getRsaKey();
+
+
+ AuthProvider createAuthProvider() throws NoSuchAlgorithmException, AuthenticationException, IOException;
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuth.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuth.java
new file mode 100644
index 00000000..0e7a05f6
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuth.java
@@ -0,0 +1,46 @@
+package kr.syeyoung.dungeonsguide.auth.authprovider.DgAuth;
+
+import com.mojang.authlib.exceptions.AuthenticationException;
+import kr.syeyoung.dungeonsguide.auth.AuthUtil;
+import kr.syeyoung.dungeonsguide.auth.authprovider.AuthProvider;
+
+import java.io.IOException;
+import java.security.KeyPair;
+import java.security.NoSuchAlgorithmException;
+
+public class DgAuth implements AuthProvider {
+
+ private final String authServerUrl;
+
+ public DgAuth(String authServerUrl){
+ this.authServerUrl = authServerUrl;
+ }
+
+ private String token;
+ private KeyPair rsaKey;
+
+ @Override
+ public String getToken() {
+ return token;
+ }
+
+ @Override
+ public KeyPair getRsaKey() {
+ return rsaKey;
+ }
+
+
+ @Override
+ public AuthProvider createAuthProvider() throws NoSuchAlgorithmException, AuthenticationException, IOException {
+ this.rsaKey = AuthUtil.getKeyPair();
+
+ String tempToken = DgAuthUtil.requestAuth(this.authServerUrl);
+
+ DgAuthUtil.checkSessionAuthenticity(tempToken);
+
+ this.token = DgAuthUtil.verifyAuth(tempToken, rsaKey.getPublic(), authServerUrl);
+
+ return this;
+ }
+
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuthUtil.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuthUtil.java
new file mode 100644
index 00000000..b01fba50
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/DgAuth/DgAuthUtil.java
@@ -0,0 +1,88 @@
+package kr.syeyoung.dungeonsguide.auth.authprovider.DgAuth;
+
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.mojang.authlib.GameProfile;
+import com.mojang.authlib.exceptions.AuthenticationException;
+import com.mojang.authlib.minecraft.MinecraftSessionService;
+import net.minecraft.client.Minecraft;
+import net.minecraft.util.Session;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.IOUtils;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.URL;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.PublicKey;
+
+public class DgAuthUtil {
+ private DgAuthUtil(){}
+
+ public static String requestAuth(String baseurl) throws IOException {
+ GameProfile profile = Minecraft.getMinecraft().getSession().getProfile();
+
+ HttpsURLConnection connection = (HttpsURLConnection) new URL(baseurl + "/auth/requestAuth").openConnection();
+ connection.setRequestProperty("User-Agent", "DungeonsGuide/1.0");
+ connection.setRequestProperty("Content-Type", "application/json");
+ connection.setRequestMethod("POST");
+ connection.setDoInput(true);
+ connection.setDoOutput(true);
+
+ connection.getOutputStream().write(("{\"uuid\":\""+profile.getId().toString()+"\",\"nickname\":\""+profile.getName()+"\"}").getBytes());
+ String payload = String.join("\n", IOUtils.readLines(connection.getErrorStream() == null ? connection.getInputStream() : connection.getErrorStream()));
+
+ JsonObject json = (JsonObject) new JsonParser().parse(payload);
+
+ if (!"ok".equals(json.get("status").getAsString())) {
+ return null;
+ }
+ return json.get("data").getAsString();
+ }
+
+ public static void checkSessionAuthenticity(String tempToken) throws NoSuchAlgorithmException, AuthenticationException {
+ JsonObject d = getJwtPayload(tempToken);
+ byte[] sharedSecret = Base64.decodeBase64(d.get("sharedSecret").getAsString());
+ byte[] publicKey =Base64.decodeBase64(d.get("publicKey").getAsString());
+ String hash = calculateServerHash(sharedSecret, publicKey);
+
+ Session session = Minecraft.getMinecraft().getSession();
+ MinecraftSessionService yggdrasilMinecraftSessionService = Minecraft.getMinecraft().getSessionService();
+ yggdrasilMinecraftSessionService.joinServer(session.getProfile(), session.getToken(), hash);
+ }
+
+ public static String verifyAuth(String tempToken, PublicKey clientKey, String baseurl) throws IOException {
+ HttpsURLConnection urlConnection = (HttpsURLConnection) new URL(baseurl + "/auth/authenticate").openConnection();
+ urlConnection.setRequestMethod("POST");
+ urlConnection.setRequestProperty("User-Agent", "DungeonsGuide/1.0");
+ urlConnection.setRequestProperty("Content-Type", "application/json");
+ urlConnection.setDoInput(true);
+ urlConnection.setDoOutput(true);
+
+ urlConnection.getOutputStream().write(("{\"jwt\":\""+tempToken+"\",\"publicKey\":\""+Base64.encodeBase64URLSafeString(clientKey.getEncoded())+"\"}").getBytes());
+ String payload = String.join("\n", IOUtils.readLines(urlConnection.getErrorStream() == null ? urlConnection.getInputStream() : urlConnection.getErrorStream()));
+
+ JsonObject jsonObject = (JsonObject) new JsonParser().parse(payload);
+ if (!"ok".equals(jsonObject.get("status").getAsString())) {
+ return null;
+ }
+ return jsonObject.get("data").getAsString();
+ }
+
+ public static JsonObject getJwtPayload(String jwt) {
+ String midPart = jwt.split("\\.")[1].replace("+", "-").replace("/", "_");
+ String base64Decode = new String(Base64.decodeBase64(midPart)); // padding
+ return (JsonObject) new JsonParser().parse(base64Decode);
+ }
+
+ public static String calculateServerHash(byte[] a, byte[] b) throws NoSuchAlgorithmException {
+ MessageDigest c = MessageDigest.getInstance("SHA-1");
+ c.update("".getBytes());
+ c.update(a);
+ c.update(b);
+ byte[] d = c.digest();
+ return new BigInteger(d).toString(16);
+ }
+}
diff --git a/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/NullAuth.java b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/NullAuth.java
new file mode 100644
index 00000000..ec7e9aed
--- /dev/null
+++ b/src/main/java/kr/syeyoung/dungeonsguide/auth/authprovider/NullAuth.java
@@ -0,0 +1,62 @@
+package kr.syeyoung.dungeonsguide.auth.authprovider;
+
+import com.mojang.authlib.exceptions.AuthenticationException;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.IOException;
+import java.security.KeyPair;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+
+public class NullAuth implements AuthProvider {
+
+ Logger logger = LogManager.getLogger("NullAuth");
+
+ @Override
+ public String getToken() {
+ return "TOKEN";
+ }
+
+ @Override
+ public KeyPair getRsaKey() {
+ return new KeyPair(new PublicKey() {
+ @Override
+ public String getAlgorithm() {
+ return null;
+ }
+
+ @Override
+ public String getFormat() {
+ return null;
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ return new byte[0];
+ }
+ }, new PrivateKey() {
+ @Override
+ public String getAlgorithm() {
+ return null;
+ }
+
+ @Override
+ public String getFormat() {
+ return null;
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ return new byte[0];
+ }
+ });
+ }
+
+ @Override
+ public AuthProvider createAuthProvider() throws NoSuchAlgorithmException, AuthenticationException, IOException {
+ return new NullAuth();
+ }
+
+}