From f46c8e0977b3216b5777ff2ab6e5097f0ba0c7ca Mon Sep 17 00:00:00 2001 From: muhammadeko Date: Sun, 1 May 2022 06:42:28 +0700 Subject: [PATCH] [BREAKING] support new dispatch server mechanism --- .../7.2/executionHistory/executionHistory.bin | Bin 79473 -> 79473 bytes .../executionHistory/executionHistory.lock | Bin 17 -> 17 bytes .gradle/7.2/fileHashes/fileHashes.bin | Bin 20147 -> 20297 bytes .gradle/7.2/fileHashes/fileHashes.lock | Bin 17 -> 17 bytes .../7.2/fileHashes/resourceHashesCache.bin | Bin 19211 -> 20061 bytes .../buildOutputCleanup.lock | Bin 17 -> 17 bytes build.gradle | 4 +- src/main/java/me/exzork/gcauth/GCAuth.java | 262 +++++++++++++++++- .../gcauth/handler/AbstractHandler.java | 23 -- .../gcauth/handler/AuthStatusHandler.java | 10 +- .../gcauth/handler/ChangePasswordHandler.java | 16 +- .../gcauth/handler/ClientLoginHandler.java | 32 ++- .../exzork/gcauth/handler/LoginHandler.java | 14 +- .../gcauth/handler/RegisterHandler.java | 14 +- 14 files changed, 303 insertions(+), 72 deletions(-) delete mode 100644 src/main/java/me/exzork/gcauth/handler/AbstractHandler.java diff --git a/.gradle/7.2/executionHistory/executionHistory.bin b/.gradle/7.2/executionHistory/executionHistory.bin index 975c16d46a703098b7dc8b38765e82f53511556a..59e19fa8375b5445f1acd484c5cab6404d8a9ef6 100644 GIT binary patch delta 1291 zcmezPhUMcMmJOQgRmFT~m!xK-XO^esYn-4fPE4jCE5|%k;7miEks?V78NhAA9VVHB~QXxhQnKn+rFm zdHVwcMoFg0cXt*{epj+n$l}z;CEq8d=F3aS-DPjs|AcYwlXe4hV}2g zu31(IZ2vl$abJ^AiTj$Ipe*gJ>Gvhq+!O1($GC2CVVCA+gXPPaCZ`@u7Wn4+%G|!y z>hPESBC&PH!s{pBtM1NSa(>O@c7sM{#u@I;j-@3TDnY5~nfZAxi6x18$vME#W)Mg# z-)eg^D0rds=8b<=O+T^j?(@CR+6{Wx8G9jGVCp z7#TV;67y1WQi~?rua*`M`S5M(wTQ#=tJQyPo3D`O^a!l%)8xX{3Q~;>FVbc`UitO# z?47qNYq*y`2g}_MW1I;J90@N5fdgW?>swa(CTSP&pEius*!%{pVwWo8WS{)>%sdZ> zMKC8R`2W}IL1S&h&lY>V&zNzi?b9K26g-gn?6AiXu9czUqydE zy*prUD)DH;lW&`WLbg1~d+Ky1ezv^1NM6=vK^ahJ=KKim)Ozj{{(9REel`EU8YmP# zna|tVsB}xr7>S!ZBH|h4S#B*) zc5O(V7veSd^^6xcS!TZgMc?E@tSpQS3}R86{pwvAML69yo5X#6z#FFbZ^>pUxx6!L z53ksK_1J?TmDL3EDWm-4LXXXr`{UIkX8##1xPM2qA zEEPacBa<(7_F<%p$q(D5Co3!$*q+P5IE4ix#J3CbGFI~F{5OcZyLj%7)Q4Btp3T;A aIJ5f|D5#G;?O+6jwakuogE>2(>>~inzd6YO delta 638 zcmezPhUMcMmJOQgnZ!3v7LHP4JhVA5yPSFRvDv0fn!xmENlR7EN3gp6 zij!y77_oc+t#Xab%8k@qKwlfC%zS({BE_7^aQZbJyB)`f$J|0mU%7be9Sg?jmB~P zX{M9c*BY=)0?JSJUt`QQ8LaRaGtj1m?9R}(G3x8gCf6SpNS_Z@ zI6)C;qUnWSMSnlNJ78}r@o2-7Z<~Qasj3n^N?*AnSSQ!67WfqU5hxV;$C_>PZv7m_ ziJb>yj76-0Le}$n%&u%dt->uG7wYftT?Z8U+N85AaBgkm>H8j;LLO{In;Rn18AUkV zHk-tKeZU*0_ixE&DY?8|K+88@J@z0-W&7;J67!P6tdx|Zv{aL#?D9jB9k3G928i#XasB# zTzGZ$f)(QTX9@3OU|?*hIj_S7(c{EEd7+1k!mpW1TQ;`uf0OX{n0}+h&y8S383xJ_ zMcieZSv?gP?P{{smq0`q8-cW*F_6#%Vnq-Z@Yu9wcJajDT!r%^LnveK|+P;nFYkTSQBOjrvKR{G-wM;$^R9%y;Q9Jpg zmmY}GI9b^n%xIn*3SqQPZui!+t2tl%AEHTM0+2>?6w9sU$*v8l^FqAlzMk>oCJV%x z5^1mw#zf)Csy=FyC4HXNhkW=p^;*PX`PJ&bw#`>abAr0(5yWVgPnbqGGQ3Ee^?2pi z!?SnZs;uE&4%P7-qJujEQ-|ZuoByYu*UjH8>p9U(zGyyF#}}Z=dLZTk1_HYKU+KI! zX6|+_<=M0!a);hjuLWz#^2`LP1Olc_Kmy&zQ;K<(X4P~pmi+u_&!r7sP#sBN4GcWm zm^vyie6Xp1&|$09y{PO8cdX$`u$I(5XbR+BkE!LqLEPQNb9baZyu$WuwvNLYh)+tb z!Imf)9mCX7_CLeTZ3`FAUK!RUHT>ZzU>&R1@qu+P2-b^WYB?aLyS`(k8$%{#tkMCf{MM@%D!y9@^~Es7epv!h#2vYr)l-4du4vW$hY%6QMj)+c3?wvxSP_H;R9F4FaxbB=wd+4KG=-ki*3ya{tax2g@Oefp%8}X9U}l#Sr5cq z_b|2WIlg4;LAhh!x^GvBJM<+6fVJ3aC;(Lg0aF5yK=bj15A9RWTRi+$xaZK`Wv5u} z!8+`Dyg=$17?FZ{%;GTr3g06D(}H2?qr diff --git a/.gradle/7.2/fileHashes/resourceHashesCache.bin b/.gradle/7.2/fileHashes/resourceHashesCache.bin index 924b83adc03799f882659f0a69c09b3f64d4a130..ad5a03d9c692c318dd61f41db0eb808a21c1e339 100644 GIT binary patch delta 1471 zcmeC4#&~xQ;|3E6PrZi!?r(k0@$F^+1E0nJp`d-i%sq*_7R-Z+KZl8TrJLLqnBv{tJ=4nBpI|*lus4h) z=AP^;X(1pR@{1+%_*`zNVBzFiNrecNLZf|gg}l}fL7$^A6SVRVPLs{M{s^krA0}>a zaO?9%zU?&-aX(3zxZy{Qdj;;Nf}rYkCr_0O5OA`-^GvvS<~E3+@8-#OB`xaHjs}V= zYF>N>RXG`ELXOkr7om#tVd6z!J-$5aYi);!`^3Y&8@(V3-;))A^&iw)d&pGKC^gB1SXgQFKp4%BNe$eWr%h@0%qq2eKPYNvDKe(cPN~ znpI_7&pG4PKEYHG#k(^9;Fd(aG>g3|t$)vnVX6o!h~8e9<-q^9^`h^zt-sG;s;KP> zV*h)h{(j#Mah+dWt;L|QMRSP#L)I<)2Mp`qdtI}v64?F~Q$>mUnw+34?XBteCD+^& z>%2F4p_g#|_iZhkH|AriusHQ`$@fXA`SKESci9{EgHtB}d&=k9+O?ABqsMt8BD$kqeo2 a!Sf#q7#Ns1H!A)R-)JBpw%O6+6cYevGagX@ diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock index a1fa19257c3d572e805eb701b3959c471db74947..dfc7a6e5b6cea2ff1edcf314de252c046aa4885c 100644 GIT binary patch literal 17 VcmZR67&qfZ+-7G^1~6b`1^_nu1S9|e literal 17 UcmZR67&qfZ+-7G^1_)>c05^LCr2qf` diff --git a/build.gradle b/build.gradle index 02da314..797dc6c 100644 --- a/build.gradle +++ b/build.gradle @@ -10,14 +10,14 @@ sourceCompatibility = 17 targetCompatibility = 17 group 'me.exzork.gcauth' -version '1.0-SNAPSHOT' +version '2.0.0' repositories { mavenCentral() } dependencies { - implementation group: 'tech.xigam', name: 'grasscutter', version: '1.0.2-dev' + implementation files('lib/grasscutter-1.0.3-dev.jar') implementation 'org.springframework.security:spring-security-crypto:5.6.3' implementation 'commons-logging:commons-logging:1.2' implementation 'com.auth0:java-jwt:3.19.1' diff --git a/src/main/java/me/exzork/gcauth/GCAuth.java b/src/main/java/me/exzork/gcauth/GCAuth.java index 892d88a..da845d3 100644 --- a/src/main/java/me/exzork/gcauth/GCAuth.java +++ b/src/main/java/me/exzork/gcauth/GCAuth.java @@ -2,10 +2,24 @@ package me.exzork.gcauth; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.sun.net.httpserver.HttpServer; import emu.grasscutter.Grasscutter; +import emu.grasscutter.database.DatabaseHelper; +import emu.grasscutter.game.Account; +import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass; import emu.grasscutter.plugin.Plugin; +import emu.grasscutter.server.dispatch.DispatchHttpJsonHandler; +import emu.grasscutter.server.dispatch.json.ComboTokenReqJson; +import emu.grasscutter.server.dispatch.json.ComboTokenResJson; +import emu.grasscutter.server.dispatch.json.LoginResultJson; +import emu.grasscutter.server.dispatch.json.LoginTokenRequestJson; +import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent; +import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent; +import express.Express; import me.exzork.gcauth.handler.*; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.util.ssl.SslContextFactory; import java.io.File; import java.io.FileReader; @@ -13,6 +27,7 @@ import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; + public class GCAuth extends Plugin { private static Config config; private static final File configFile = new File(Grasscutter.getConfig().PLUGINS_FOLDER+"GCAuth/config.json"); @@ -31,13 +46,234 @@ public class GCAuth extends Plugin { @Override public void onEnable() { - HttpServer server = Grasscutter.getDispatchServer().getServer(); - server.createContext("/grasscutter/auth_status",new AuthStatusHandler()); - server.createContext("/grasscutter/login", new LoginHandler()); - server.createContext("/grasscutter/register", new RegisterHandler()); - server.createContext("/grasscutter/change_password", new ChangePasswordHandler()); - server.removeContext("/hk4e_global/mdk/shield/api/login"); - server.createContext("/hk4e_global/mdk/shield/api/login", new ClientLoginHandler()); + + Express httpServer = new Express(config -> { + config.server(() -> { + Server server = new Server(); + ServerConnector serverConnector; + + if(Grasscutter.getConfig().getDispatchOptions().UseSSL) { + SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); + File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath); + + if(keystoreFile.exists()) { + try { + sslContextFactory.setKeyStorePath(keystoreFile.getPath()); + sslContextFactory.setKeyStorePassword(Grasscutter.getConfig().getDispatchOptions().KeystorePassword); + } catch (Exception e) { + e.printStackTrace(); + Grasscutter.getLogger().warn("[Dispatch] Unable to load keystore. Trying default keystore password..."); + + try { + sslContextFactory.setKeyStorePath(keystoreFile.getPath()); + sslContextFactory.setKeyStorePassword("123456"); + Grasscutter.getLogger().warn("[Dispatch] The default keystore password was loaded successfully. Please consider setting the password to 123456 in config.json."); + } catch (Exception e2) { + Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!"); + e2.printStackTrace(); + } + } + + serverConnector = new ServerConnector(server, sslContextFactory); + } else { + Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server."); + Grasscutter.getConfig().getDispatchOptions().UseSSL = false; + + serverConnector = new ServerConnector(server); + } + } else { + serverConnector = new ServerConnector(server); + } + + serverConnector.setPort(Grasscutter.getConfig().getDispatchOptions().Port); + server.setConnectors(new Connector[]{serverConnector}); + return server; + }); + + config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL; + if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("ALL")) { + config.enableDevLogging(); + } + }); + + httpServer.get("/grasscutter/auth_status",new AuthStatusHandler()); + httpServer.post("/grasscutter/login", new LoginHandler()); + httpServer.post("/grasscutter/register", new RegisterHandler()); + httpServer.post("/grasscutter/change_password", new ChangePasswordHandler()); + httpServer.post("/hk4e_global/mdk/shield/api/login", new ClientLoginHandler()); + + httpServer.get("/", (req, res) -> res.send("Welcome to Grasscutter")); + + httpServer.raw().error(404, ctx -> { + if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("MISSING")) { + Grasscutter.getLogger().info(String.format("[Dispatch] Potential unhandled %s request: %s", ctx.method(), ctx.url())); + } + ctx.contentType("text/html"); + ctx.result(""); // I'm like 70% sure this won't break anything. + }); + + // Dispatch + httpServer.get("/query_region_list", (req, res) -> { + // Log + Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip())); + + // Invoke event. + QueryAllRegionsEvent event = new QueryAllRegionsEvent(Grasscutter.getDispatchServer().regionListBase64); event.call(); + // Respond with event result. + res.send(event.getRegionList()); + }); + + httpServer.get("/query_cur_region/:id", (req, res) -> { + String regionName = req.params("id"); + // Log + Grasscutter.getLogger().info( + String.format("Client %s request: query_cur_region/%s", req.ip(), regionName)); + // Create a response form the request query parameters + String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw=="; + if (req.query().values().size() > 0) { + response = Grasscutter.getDispatchServer().regions.get(regionName).getBase64(); + } + + // Invoke event. + QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call(); + // Respond with event result. + res.send(event.getRegionInfo()); + }); + + + // Login via token + httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> { + // Get post data + LoginTokenRequestJson requestData = null; + try { + String body = req.ctx().body(); + requestData = Grasscutter.getGsonFactory().fromJson(body, LoginTokenRequestJson.class); + } catch (Exception ignored) { + } + + // Create response json + if (requestData == null) { + return; + } + LoginResultJson responseData = new LoginResultJson(); + Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in via token", req.ip())); + + // Login + Account account = DatabaseHelper.getAccountById(requestData.uid); + + // Test + if (account == null || !account.getSessionKey().equals(requestData.token)) { + responseData.retcode = -111; + responseData.message = "Game account cache information error"; + + Grasscutter.getLogger() + .info(String.format("[Dispatch] Client %s failed to log in via token", req.ip())); + } else { + responseData.message = "OK"; + responseData.data.account.uid = requestData.uid; + responseData.data.account.token = requestData.token; + responseData.data.account.email = account.getEmail(); + + Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in via token as %s", + req.ip(), responseData.data.account.uid)); + } + + res.send(responseData); + }); + + // Exchange for combo token + httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> { + // Get post data + ComboTokenReqJson requestData = null; + try { + String body = req.ctx().body(); + requestData = Grasscutter.getGsonFactory().fromJson(body, ComboTokenReqJson.class); + } catch (Exception ignored) { + } + + // Create response json + if (requestData == null || requestData.data == null) { + return; + } + ComboTokenReqJson.LoginTokenData loginData = Grasscutter.getGsonFactory().fromJson(requestData.data, ComboTokenReqJson.LoginTokenData.class); // Get login + // data + ComboTokenResJson responseData = new ComboTokenResJson(); + + // Login + Account account = DatabaseHelper.getAccountById(loginData.uid); + + // Test + if (account == null || !account.getSessionKey().equals(loginData.token)) { + responseData.retcode = -201; + responseData.message = "Wrong session key."; + + Grasscutter.getLogger().info( + String.format("[Dispatch] Client %s failed to exchange combo token", req.ip())); + } else { + responseData.message = "OK"; + responseData.data.open_id = loginData.uid; + responseData.data.combo_id = "157795300"; + responseData.data.combo_token = account.generateLoginToken(); + + Grasscutter.getLogger().info( + String.format("[Dispatch] Client %s succeed to exchange combo token", req.ip())); + } + + res.send(responseData); + }); + + // TODO: There are some missing route request types here (You can tell if they are missing if they are .all and not anything else) + // When http requests for theses routes are found please remove it from the list in DispatchHttpJsonHandler and update the route request types here + + // Agreement and Protocol + // hk4e-sdk-os.hoyoverse.com + httpServer.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}")); + // hk4e-sdk-os.hoyoverse.com + httpServer.post("/hk4e_global/combo/granter/api/compareProtocolVersion", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}")); + + // Game data + // hk4e-api-os.hoyoverse.com + httpServer.all("/common/hk4e_global/announcement/api/getAlertPic", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}")); + // hk4e-api-os.hoyoverse.com + httpServer.all("/common/hk4e_global/announcement/api/getAlertAnn", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}")); + // hk4e-api-os.hoyoverse.com + httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0,\"type_list\":[],\"alert\":false,\"alert_id\":0,\"timezone\":0,\"t\":\"" + System.currentTimeMillis() + "\"}}")); + // hk4e-api-os-static.hoyoverse.com + httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}")); + // hk4e-sdk-os.hoyoverse.com + httpServer.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}")); + + // Captcha + // api-account-os.hoyoverse.com + httpServer.post("/account/risky/api/check", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}")); + + // Config + // sdk-os-static.hoyoverse.com + httpServer.get("/combo/box/api/config/sdk/combo", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}")); + // hk4e-sdk-os-static.hoyoverse.com + httpServer.get("/hk4e_global/combo/granter/api/getConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}")); + // hk4e-sdk-os-static.hoyoverse.com + httpServer.get("/hk4e_global/mdk/shield/api/loadConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}")); + // Test api? + // abtest-api-data-sg.hoyoverse.com + httpServer.post("/data_abtest_api/config/experiment/list", new DispatchHttpJsonHandler("{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}")); + + // log-upload-os.mihoyo.com + httpServer.all("/log/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}")); + httpServer.all("/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}")); + httpServer.post("/sdk/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}")); + // /perf/config/verify?device_id=xxx&platform=x&name=xxx + httpServer.all("/perf/config/verify", new DispatchHttpJsonHandler("{\"code\":0}")); + + // Logging servers + // overseauspider.yuanshen.com + httpServer.all("/log", new DispatchHttpJsonHandler("{\"code\":0}")); + // log-upload-os.mihoyo.com + httpServer.all("/crash/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}")); + + httpServer.get("/gacha", (req, res) -> res.send("Gacha")); + + Grasscutter.getDispatchServer().setHttpServer(httpServer); } @Override @@ -63,5 +299,15 @@ public class GCAuth extends Plugin { } } + + public static class RegionData { + QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp parsedRegionQuery; + String Base64; + + public RegionData(QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp prq, String b64) { + this.parsedRegionQuery = prq; + this.Base64 = b64; + } + } public static Config getConfig() {return config;} } diff --git a/src/main/java/me/exzork/gcauth/handler/AbstractHandler.java b/src/main/java/me/exzork/gcauth/handler/AbstractHandler.java deleted file mode 100644 index 19841fa..0000000 --- a/src/main/java/me/exzork/gcauth/handler/AbstractHandler.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.exzork.gcauth.handler; - -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.httpserver.HttpHandler; -import emu.grasscutter.Grasscutter; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collections; - -public abstract class AbstractHandler implements HttpHandler { - void responseJSON(HttpExchange t, Object data) throws IOException { - // Create a response - String response = Grasscutter.getGsonFactory().toJson(data); - // Set the response header status and length - t.getResponseHeaders().put("Content-Type", Collections.singletonList("application/json")); - t.sendResponseHeaders(200, response.getBytes().length); - // Write the response string - OutputStream os = t.getResponseBody(); - os.write(response.getBytes()); - os.close(); - } -} diff --git a/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java b/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java index 4349c36..f7c83c9 100644 --- a/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java @@ -1,18 +1,20 @@ package me.exzork.gcauth.handler; -import com.sun.net.httpserver.HttpExchange; +import express.http.HttpContextHandler; +import express.http.Request; +import express.http.Response; import me.exzork.gcauth.GCAuth; import me.exzork.gcauth.json.AuthResponseJson; import java.io.IOException; -public class AuthStatusHandler extends AbstractHandler{ +public class AuthStatusHandler implements HttpContextHandler { @Override - public void handle(HttpExchange t) throws IOException { + public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); authResponse.success = true; authResponse.message = GCAuth.getConfig().Enable ? "AUTH_ENABLED" : "AUTH_DISABLED"; authResponse.jwt = ""; - responseJSON(t, authResponse); + response.send(authResponse); } } diff --git a/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java b/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java index 42a36be..b5d2983 100644 --- a/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java @@ -1,10 +1,11 @@ package me.exzork.gcauth.handler; import com.google.gson.Gson; -import com.sun.net.httpserver.HttpExchange; import emu.grasscutter.Grasscutter; import emu.grasscutter.game.Account; -import emu.grasscutter.utils.Utils; +import express.http.HttpContextHandler; +import express.http.Request; +import express.http.Response; import me.exzork.gcauth.GCAuth; import me.exzork.gcauth.json.AuthResponseJson; import me.exzork.gcauth.json.ChangePasswordAccount; @@ -12,14 +13,14 @@ import me.exzork.gcauth.utils.Authentication; import java.io.IOException; -public class ChangePasswordHandler extends AbstractHandler{ +public class ChangePasswordHandler implements HttpContextHandler { @Override - public void handle(HttpExchange t) throws IOException { + public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); if (GCAuth.getConfig().Enable) { try { - String requestBody = Utils.toString(t.getRequestBody()); + String requestBody = request.ctx().body(); if (requestBody.isEmpty()) { authResponse.success = false; authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" @@ -51,14 +52,13 @@ public class ChangePasswordHandler extends AbstractHandler{ authResponse.jwt = ""; Grasscutter.getLogger().error("[Dispatch] Error while changing user password."); e.printStackTrace(); - responseJSON(t, authResponse); + response.send(authResponse); } } else { authResponse.success = false; authResponse.message = "AUTH_DISABLED"; // ENG = "Authentication is not required for this server..." authResponse.jwt = ""; } - - responseJSON(t, authResponse); + response.send(authResponse); } } diff --git a/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java b/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java index df42e3a..20aa7b6 100644 --- a/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java @@ -1,24 +1,26 @@ package me.exzork.gcauth.handler; -import com.sun.net.httpserver.HttpExchange; import emu.grasscutter.Grasscutter; import emu.grasscutter.database.DatabaseHelper; import emu.grasscutter.game.Account; import emu.grasscutter.server.dispatch.json.LoginAccountRequestJson; import emu.grasscutter.server.dispatch.json.LoginResultJson; -import emu.grasscutter.utils.Utils; +import express.http.HttpContextHandler; +import express.http.Request; +import express.http.Response; import me.exzork.gcauth.GCAuth; import me.exzork.gcauth.utils.Authentication; import java.io.IOException; -public class ClientLoginHandler extends AbstractHandler{ +public class ClientLoginHandler implements HttpContextHandler { @Override - public void handle(HttpExchange t) throws IOException { + public void handle(Request request, Response response) throws IOException { LoginAccountRequestJson requestData = null; try { - String body = Utils.toString(t.getRequestBody()); + String body = request.ctx().body(); + Grasscutter.getLogger().info("Received login request: " + body); requestData = Grasscutter.getGsonFactory().fromJson(body, LoginAccountRequestJson.class); } catch (Exception ignored) { } @@ -30,18 +32,18 @@ public class ClientLoginHandler extends AbstractHandler{ LoginResultJson responseData = new LoginResultJson(); Grasscutter.getLogger() - .info(String.format("[Dispatch] Client %s is trying to log in", t.getRemoteAddress())); + .info(String.format("[Dispatch] Client %s is trying to log in", request.ip())); // Login Account account = null; if(GCAuth.getConfig().Enable){ account = Authentication.getAccountByOneTimeToken(requestData.account); if(account == null) { + Grasscutter.getLogger().info("[Dispatch] Client " + request.ip() + " failed to log in"); responseData.retcode = -201; responseData.message = "Token is invalid"; - responseJSON(t, responseData); + response.send(responseData); } - ; }else{ account = DatabaseHelper.getAccountByName(requestData.account); } @@ -55,6 +57,10 @@ public class ClientLoginHandler extends AbstractHandler{ // added. account = DatabaseHelper.createAccountWithId(requestData.account, 0); + for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) { + account.addPermission(permission); + } + if (account != null) { responseData.message = "OK"; responseData.data.account.uid = account.getId(); @@ -63,20 +69,20 @@ public class ClientLoginHandler extends AbstractHandler{ Grasscutter.getLogger() .info(String.format("[Dispatch] Client %s failed to log in: Account %s created", - t.getRemoteAddress(), responseData.data.account.uid)); + request.ip(), responseData.data.account.uid)); } else { responseData.retcode = -201; responseData.message = "Username not found, create failed."; Grasscutter.getLogger().info(String.format( - "[Dispatch] Client %s failed to log in: Account create failed", t.getRemoteAddress())); + "[Dispatch] Client %s failed to log in: Account create failed", request.ip())); } } else { responseData.retcode = -201; responseData.message = "Username not found."; Grasscutter.getLogger().info(String - .format("[Dispatch] Client %s failed to log in: Account no found", t.getRemoteAddress())); + .format("[Dispatch] Client %s failed to log in: Account no found", request.ip())); } } else { // Account was found, log the player in @@ -85,10 +91,10 @@ public class ClientLoginHandler extends AbstractHandler{ responseData.data.account.token = account.generateSessionKey(); responseData.data.account.email = account.getEmail(); - Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", t.getRemoteAddress(), + Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", request.ip(), responseData.data.account.uid)); } - responseJSON(t, responseData); + response.send(responseData); } } diff --git a/src/main/java/me/exzork/gcauth/handler/LoginHandler.java b/src/main/java/me/exzork/gcauth/handler/LoginHandler.java index 53906b3..6593cf9 100644 --- a/src/main/java/me/exzork/gcauth/handler/LoginHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/LoginHandler.java @@ -1,10 +1,11 @@ package me.exzork.gcauth.handler; import com.google.gson.Gson; -import com.sun.net.httpserver.HttpExchange; import emu.grasscutter.Grasscutter; import emu.grasscutter.game.Account; -import emu.grasscutter.utils.Utils; +import express.http.HttpContextHandler; +import express.http.Request; +import express.http.Response; import me.exzork.gcauth.GCAuth; import me.exzork.gcauth.json.AuthResponseJson; import me.exzork.gcauth.json.LoginGenerateToken; @@ -12,14 +13,14 @@ import me.exzork.gcauth.utils.Authentication; import java.io.IOException; -public class LoginHandler extends AbstractHandler{ +public class LoginHandler implements HttpContextHandler { @Override - public void handle(HttpExchange t) throws IOException { + public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); if (GCAuth.getConfig().Enable) { try { - String requestBody = Utils.toString(t.getRequestBody()); + String requestBody = request.ctx().body(); if (requestBody.isEmpty()) { authResponse.success = false; authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" @@ -55,7 +56,6 @@ public class LoginHandler extends AbstractHandler{ authResponse.message = "AUTH_DISABLED"; // ENG = "Authentication is not required for this server..." authResponse.jwt = ""; } - - responseJSON(t, authResponse); + response.send(authResponse); } } diff --git a/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java b/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java index 96da451..fa89f34 100644 --- a/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java @@ -1,11 +1,12 @@ package me.exzork.gcauth.handler; import com.google.gson.Gson; -import com.sun.net.httpserver.HttpExchange; import emu.grasscutter.Grasscutter; import emu.grasscutter.database.DatabaseHelper; import emu.grasscutter.game.Account; -import emu.grasscutter.utils.Utils; +import express.http.HttpContextHandler; +import express.http.Request; +import express.http.Response; import me.exzork.gcauth.GCAuth; import me.exzork.gcauth.json.AuthResponseJson; import me.exzork.gcauth.json.RegisterAccount; @@ -13,14 +14,14 @@ import me.exzork.gcauth.utils.Authentication; import java.io.IOException; -public class RegisterHandler extends AbstractHandler{ +public class RegisterHandler implements HttpContextHandler { @Override - public void handle(HttpExchange t) throws IOException { + public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); if (GCAuth.getConfig().Enable) { try { - String requestBody = Utils.toString(t.getRequestBody()); + String requestBody = request.ctx().body(); if (requestBody.isEmpty()) { authResponse.success = false; authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" @@ -57,7 +58,6 @@ public class RegisterHandler extends AbstractHandler{ authResponse.message = "AUTH_DISABLED"; // ENG = "Authentication is not required for this server..." authResponse.jwt = ""; } - - responseJSON(t, authResponse); + response.send(authResponse); } }