Commit 5c3d9980 authored by Melledy's avatar Melledy Committed by GitHub
Browse files

Merge pull request #868 from Grasscutters/plugin-auth

Refactor 'dispatch' server/Update plugin authentication API
parents a751e71d 6ec27cd1
package emu.grasscutter.server.http;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.utils.FileUtils;
import express.Express;
import express.http.MediaType;
import io.javalin.Javalin;
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.IOException;
import static emu.grasscutter.Configuration.*;
import static emu.grasscutter.utils.Language.translate;
/**
* Manages all HTTP-related classes.
* (including dispatch, announcements, gacha, etc.)
*/
public final class HttpServer {
private final Express express;
/**
* Configures the Express application.
*/
public HttpServer() {
this.express = new Express(config -> {
// Set the Express HTTP server.
config.server(HttpServer::createServer);
// Configure encryption/HTTPS/SSL.
config.enforceSsl = HTTP_ENCRYPTION.useEncryption;
// Configure HTTP policies.
if(HTTP_POLICIES.cors.enabled) {
var allowedOrigins = HTTP_POLICIES.cors.allowedOrigins;
if (allowedOrigins.length > 0)
config.enableCorsForOrigin(allowedOrigins);
else config.enableCorsForAllOrigins();
}
// Configure debug logging.
if(SERVER.debugLevel == ServerDebugMode.ALL)
config.enableDevLogging();
// Disable compression on static files.
config.precompressStaticFiles = false;
});
}
/**
* Creates an HTTP(S) server.
* @return A server instance.
*/
@SuppressWarnings("resource")
private static Server createServer() {
Server server = new Server();
ServerConnector serverConnector
= new ServerConnector(server);
if(HTTP_ENCRYPTION.useEncryption) {
var sslContextFactory = new SslContextFactory.Server();
var keystoreFile = new File(HTTP_ENCRYPTION.keystore);
if(!keystoreFile.exists()) {
HTTP_ENCRYPTION.useEncryption = false;
HTTP_ENCRYPTION.useInRouting = false;
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.no_keystore_error"));
} else try {
sslContextFactory.setKeyStorePath(keystoreFile.getPath());
sslContextFactory.setKeyStorePassword(HTTP_ENCRYPTION.keystorePassword);
} catch (Exception ignored) {
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.password_error"));
try {
sslContextFactory.setKeyStorePath(keystoreFile.getPath());
sslContextFactory.setKeyStorePassword("123456");
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.default_password"));
} catch (Exception exception) {
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.general_error"), exception);
}
} finally {
serverConnector = new ServerConnector(server, sslContextFactory);
}
}
serverConnector.setPort(HTTP_INFO.bindPort);
server.setConnectors(new ServerConnector[]{serverConnector});
return server;
}
/**
* Returns the handle for the Express application.
* @return A Javalin instance.
*/
public Javalin getHandle() {
return this.express.raw();
}
/**
* Initializes the provided class.
* @param router The router class.
* @return Method chaining.
*/
@SuppressWarnings("UnusedReturnValue")
public HttpServer addRouter(Class<? extends Router> router, Object... args) {
// Get all constructor parameters.
Class<?>[] types = new Class<?>[args.length];
for(var argument : args)
types[args.length - 1] = argument.getClass();
try { // Create a router instance & apply routes.
var constructor = router.getDeclaredConstructor(types); // Get the constructor.
var routerInstance = constructor.newInstance(args); // Create instance.
routerInstance.applyRoutes(this.express, this.getHandle()); // Apply routes.
} catch (Exception exception) {
Grasscutter.getLogger().warn(translate("messages.dispatch.router_error"), exception);
} return this;
}
/**
* Starts listening on the HTTP server.
*/
public void start() {
// Attempt to start the HTTP server.
this.express.listen(HTTP_INFO.bindAddress, HTTP_INFO.bindPort);
// Log bind information.
Grasscutter.getLogger().info(translate("messages.dispatch.port_bind", Integer.toString(this.express.raw().port())));
}
/**
* Handles the '/' (index) endpoint on the Express application.
*/
public static class DefaultRequestRouter implements Router {
@Override public void applyRoutes(Express express, Javalin handle) {
express.get("/", (request, response) -> {
File file = new File(HTTP_STATIC_FILES.errorFile);
if(!file.exists())
response.send("""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
</head>
<body>%s</body>
</html>
""".formatted(translate("messages.status.welcome")));
else {
final var filePath = file.getPath();
final MediaType fromExtension = MediaType.getByExtension(filePath.substring(filePath.lastIndexOf(".") + 1));
response.type((fromExtension != null) ? fromExtension.getMIME() : "text/plain")
.send(FileUtils.read(filePath));
}
});
}
}
/**
* Handles unhandled endpoints on the Express application.
*/
public static class UnhandledRequestRouter implements Router {
@Override public void applyRoutes(Express express, Javalin handle) {
handle.error(404, context -> {
if(SERVER.debugLevel == ServerDebugMode.MISSING)
Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", context.method(), context.url()));
context.contentType("text/html");
File file = new File(HTTP_STATIC_FILES.errorFile);
if(!file.exists())
context.result("""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
</head>
<body>
<img src="https://http.cat/404" />
</body>
</html>
""");
else {
final var filePath = file.getPath();
final MediaType fromExtension = MediaType.getByExtension(filePath.substring(filePath.lastIndexOf(".") + 1));
context.contentType((fromExtension != null) ? fromExtension.getMIME() : "text/plain")
.result(FileUtils.read(filePath));
}
});
}
}
}
package emu.grasscutter.server.http;
import express.Express;
import io.javalin.Javalin;
/**
* Defines routes for an {@link Express} instance.
*/
public interface Router {
/**
* Called when the router is initialized by Express.
* @param express An Express instance.
*/
void applyRoutes(Express express, Javalin handle);
}
package emu.grasscutter.server.http.dispatch;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.auth.AuthenticationSystem;
import emu.grasscutter.server.http.Router;
import emu.grasscutter.server.http.objects.*;
import emu.grasscutter.server.http.objects.ComboTokenReqJson.LoginTokenData;
import emu.grasscutter.utils.Utils;
import express.Express;
import express.http.Request;
import express.http.Response;
import io.javalin.Javalin;
import static emu.grasscutter.utils.Language.translate;
/**
* Handles requests related to authentication. (aka dispatch)
*/
public final class DispatchHandler implements Router {
@Override public void applyRoutes(Express express, Javalin handle) {
// Username & Password login (from client).
express.post("/hk4e_global/mdk/shield/api/login", DispatchHandler::clientLogin);
// Cached token login (from registry).
express.post("/hk4e_global/mdk/shield/api/verify", DispatchHandler::tokenLogin);
// Combo token login (from session key).
express.post("/hk4e_global/combo/granter/login/v2/login", DispatchHandler::sessionKeyLogin);
// External login (from other clients).
express.get("/authentication/type", (request, response) -> response.send(Grasscutter.getAuthenticationSystem().getClass().getSimpleName()));
express.post("/authentication/login", (request, response) -> Grasscutter.getAuthenticationSystem().getExternalAuthenticator()
.handleLogin(AuthenticationSystem.fromExternalRequest(request, response)));
express.post("/authentication/register", (request, response) -> Grasscutter.getAuthenticationSystem().getExternalAuthenticator()
.handleAccountCreation(AuthenticationSystem.fromExternalRequest(request, response)));
express.post("/authentication/change_password", (request, response) -> Grasscutter.getAuthenticationSystem().getExternalAuthenticator()
.handlePasswordReset(AuthenticationSystem.fromExternalRequest(request, response)));
}
/**
* @route /hk4e_global/mdk/shield/api/login
*/
private static void clientLogin(Request request, Response response) {
// Parse body data.
String rawBodyData = request.ctx().body();
var bodyData = Utils.jsonDecode(rawBodyData, LoginAccountRequestJson.class);
// Validate body data.
if(bodyData == null)
return;
// Pass data to authentication handler.
var responseData = Grasscutter.getAuthenticationSystem()
.getPasswordAuthenticator()
.authenticate(AuthenticationSystem.fromPasswordRequest(request, bodyData));
// Send response.
response.send(responseData);
// Log to console.
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", request.ip()));
}
/**
* @route /hk4e_global/mdk/shield/api/verify
*/
private static void tokenLogin(Request request, Response response) {
// Parse body data.
String rawBodyData = request.ctx().body();
var bodyData = Utils.jsonDecode(rawBodyData, LoginTokenRequestJson.class);
// Validate body data.
if(bodyData == null)
return;
// Pass data to authentication handler.
var responseData = Grasscutter.getAuthenticationSystem()
.getTokenAuthenticator()
.authenticate(AuthenticationSystem.fromTokenRequest(request, bodyData));
// Send response.
response.send(responseData);
// Log to console.
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", request.ip()));
}
/**
* @route /hk4e_global/combo/granter/login/v2/login
*/
private static void sessionKeyLogin(Request request, Response response) {
// Parse body data.
String rawBodyData = request.ctx().body();
var bodyData = Utils.jsonDecode(rawBodyData, ComboTokenReqJson.class);
// Validate body data.
if(bodyData == null || bodyData.data == null)
return;
// Decode additional body data.
var tokenData = Utils.jsonDecode(bodyData.data, LoginTokenData.class);
// Pass data to authentication handler.
var responseData = Grasscutter.getAuthenticationSystem()
.getSessionKeyAuthenticator()
.authenticate(AuthenticationSystem.fromComboTokenRequest(request, bodyData, tokenData));
// Send response.
response.send(responseData);
// Log to console.
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", request.ip()));
}
}
package emu.grasscutter.server.http.dispatch;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.Grasscutter.ServerRunMode;
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.*;
import emu.grasscutter.net.proto.RegionInfoOuterClass;
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo;
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
import emu.grasscutter.server.http.Router;
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;
import express.Express;
import express.http.Request;
import express.http.Response;
import io.javalin.Javalin;
import java.io.File;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static emu.grasscutter.Configuration.*;
import static emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.*;
/**
* Handles requests related to region queries.
*/
public final class RegionHandler implements Router {
private static final Map<String, RegionData> regions = new ConcurrentHashMap<>();
private static String regionListResponse;
public RegionHandler() {
try { // Read & initialize region data.
this.initialize();
} catch (Exception exception) {
Grasscutter.getLogger().error("Failed to initialize region data.", exception);
}
}
/**
* Configures region data according to configuration.
*/
private void initialize() {
String dispatchDomain = "http" + (HTTP_ENCRYPTION.useInRouting ? "s" : "") + "://"
+ lr(HTTP_INFO.accessAddress, HTTP_INFO.bindAddress) + ":"
+ lr(HTTP_INFO.accessPort, HTTP_INFO.bindPort);
// Create regions.
List<RegionSimpleInfo> servers = new ArrayList<>();
List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
var configuredRegions = new ArrayList<>(List.of(DISPATCH_INFO.regions));
if(SERVER.runMode != ServerRunMode.HYBRID && configuredRegions.size() == 0) {
Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
System.exit(1);
} else configuredRegions.add(new Region("os_usa", DISPATCH_INFO.defaultName,
lr(GAME_INFO.accessAddress, GAME_INFO.bindAddress),
lr(GAME_INFO.accessPort, GAME_INFO.bindPort)));
configuredRegions.forEach(region -> {
if (usedNames.contains(region.Name)) {
Grasscutter.getLogger().error("Region name already in use.");
return;
}
// Create a region identifier.
var identifier = RegionSimpleInfo.newBuilder()
.setName(region.Name).setTitle(region.Title).setType("DEV_PUBLIC")
.setDispatchUrl(dispatchDomain + "/query_cur_region/" + region.Name)
.build();
usedNames.add(region.Name); servers.add(identifier);
// Create a region info object.
var regionInfo = RegionInfo.newBuilder()
.setGateserverIp(region.Ip).setGateserverPort(region.Port)
.setSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
.build();
// Create an updated region query.
var updatedQuery = QueryCurrRegionHttpRsp.newBuilder().setRegionInfo(regionInfo).build();
regions.put(region.Name, new RegionData(updatedQuery, Utils.base64Encode(updatedQuery.toByteString().toByteArray())));
});
// Create a config object.
byte[] customConfig = "{\"sdkenv\":\"2\",\"checkdevice\":\"false\",\"loadPatch\":\"false\",\"showexception\":\"false\",\"regionConfig\":\"pm|fk|add\",\"downloadMode\":\"0\"}".getBytes();
Crypto.xor(customConfig, Crypto.DISPATCH_KEY); // XOR the config with the key.
// Create an updated region list.
QueryRegionListHttpRsp updatedRegionList = QueryRegionListHttpRsp.newBuilder()
.addAllRegionList(servers)
.setClientSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
.setClientCustomConfigEncrypted(ByteString.copyFrom(customConfig))
.setEnableLoginPc(true).build();
// Set the region list response.
regionListResponse = Utils.base64Encode(updatedRegionList.toByteString().toByteArray());
}
@Override public void applyRoutes(Express express, Javalin handle) {
express.get("/query_region_list", RegionHandler::queryRegionList);
express.get("/query_cur_region/:region", RegionHandler::queryCurrentRegion );
}
/**
* @route /query_region_list
*/
private static void queryRegionList(Request request, Response response) {
// Invoke event.
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse); event.call();
// Respond with event result.
response.send(event.getRegionList());
// Log to console.
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", request.ip()));
}
/**
* @route /query_cur_region/:region
*/
private static void queryCurrentRegion(Request request, Response response) {
// Get region to query.
String regionName = request.params("region");
// Get region data.
String regionData = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
if (request.query().values().size() > 0) {
var region = regions.get(regionName);
if(region != null) regionData = region.getBase64();
}
// Invoke event.
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData); event.call();
// Respond with event result.
response.send(event.getRegionInfo());
// Log to console.
Grasscutter.getLogger().info(String.format("Client %s request: query_cur_region/%s", request.ip(), regionName));
}
/**
* Region data container.
*/
public static class RegionData {
private final QueryCurrRegionHttpRsp regionQuery;
private final String base64;
public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
this.regionQuery = prq;
this.base64 = b64;
}
public QueryCurrRegionHttpRsp getRegionQuery() {
return this.regionQuery;
}
public String getBase64() {
return this.base64;
}
}
/**
* Gets the current region query.
* @return A {@link QueryCurrRegionHttpRsp} object.
*/
public static QueryCurrRegionHttpRsp getCurrentRegion() {
return SERVER.runMode == ServerRunMode.HYBRID ? regions.get("os_usa").getRegionQuery() : null;
}
}
package emu.grasscutter.server.http.handlers;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.server.http.objects.HttpJsonResponse;
import emu.grasscutter.server.http.Router;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;
import express.Express;
import express.http.Request;
import express.http.Response;
import io.javalin.Javalin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;
import static emu.grasscutter.Configuration.DATA;
/**
* Handles requests related to the announcements page.
*/
public final class AnnouncementsHandler implements Router {
private static String template, swjs, vue;
public AnnouncementsHandler() {
var templateFile = new File(Utils.toFilePath(DATA("/hk4e/announcement/index.html")));
var swjsFile = new File(Utils.toFilePath(DATA("/hk4e/announcement/sw.js")));
var vueFile = new File(Utils.toFilePath(DATA("/hk4e/announcement/vue.min.js")));
template = templateFile.exists() ? new String(FileUtils.read(template)) : null;
swjs = swjsFile.exists() ? new String(FileUtils.read(swjs)) : null;
vue = vueFile.exists() ? new String(FileUtils.read(vueFile)) : null;
}
@Override public void applyRoutes(Express express, Javalin handle) {
// hk4e-api-os.hoyoverse.com
express.all("/common/hk4e_global/announcement/api/getAlertPic", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
// hk4e-api-os.hoyoverse.com
express.all("/common/hk4e_global/announcement/api/getAlertAnn", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
// hk4e-api-os.hoyoverse.com
express.all("/common/hk4e_global/announcement/api/getAnnList", AnnouncementsHandler::getAnnouncement);
// hk4e-api-os-static.hoyoverse.com
express.all("/common/hk4e_global/announcement/api/getAnnContent", AnnouncementsHandler::getAnnouncement);
// hk4e-sdk-os.hoyoverse.com
express.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
express.get("/hk4e/announcement/*", AnnouncementsHandler::getPageResources);
express.get("/sw.js", AnnouncementsHandler::getPageResources);
express.get("/dora/lib/vue/2.6.11/vue.min.js", AnnouncementsHandler::getPageResources);
}
private static void getAnnouncement(Request request, Response response) {
if (Objects.equals(request.baseUrl(), "/common/hk4e_global/announcement/api/getAnnContent")) {
String data = readToString(Paths.get(DATA("GameAnnouncement.json")).toFile());
response.send("{\"retcode\":0,\"message\":\"OK\",\"data\":" + data + "}");
} else if (Objects.equals(request.baseUrl(), "/common/hk4e_global/announcement/api/getAnnList")) {
String data = readToString(Paths.get(DATA("GameAnnouncementList.json")).toFile())
.replace("System.currentTimeMillis()", String.valueOf(System.currentTimeMillis()));
response.send("{\"retcode\":0,\"message\":\"OK\",\"data\": " + data + "}");
}
}
private static void getPageResources(Request request, Response response) {
var path = request.path();
switch(path) {
case "/sw.js" -> response.send(swjs);
case "/hk4e/announcement/index.html" -> response.send(template);
case "/dora/lib/vue/2.6.11/vue.min.js" -> response.send(vue);
default -> {
File renderFile = new File(Utils.toFilePath(DATA(path)));
if(!renderFile.exists()) {
Grasscutter.getLogger().info("File not exist: " + path);
return;
}
String ext = path.substring(path.lastIndexOf(".") + 1);
if ("css".equals(ext)) {
response.type("text/css");
response.send(FileUtils.read(renderFile));
} else {
response.send(FileUtils.read(renderFile));
}
}
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static String readToString(File file) {
long length = file.length();
byte[] content = new byte[(int) length];
try {
FileInputStream in = new FileInputStream(file);
in.read(content); in.close();
} catch (IOException ignored) {
Grasscutter.getLogger().warn("File not found: " + file.getAbsolutePath());
}
return new String(content);
}
}
package emu.grasscutter.server.http.handlers;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.gacha.GachaBanner;
import emu.grasscutter.game.gacha.GachaManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.http.Router;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;
import express.Express;
import express.http.Request;
import express.http.Response;
import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import static emu.grasscutter.Configuration.DATA;
import static emu.grasscutter.utils.Language.translate;
/**
* Handles all gacha-related HTTP requests.
*/
public final class GachaHandler implements Router {
private final String gachaMappings;
private static String recordsTemplate = "";
private static String detailsTemplate = "";
public GachaHandler() {
this.gachaMappings = Utils.toFilePath(DATA("/gacha_mappings.js"));
if(!(new File(this.gachaMappings).exists())) {
try {
Tools.createGachaMapping(this.gachaMappings);
} catch (Exception exception) {
Grasscutter.getLogger().warn("Failed to create gacha mappings.", exception);
}
}
var templateFile = new File(DATA("/gacha_records.html"));
recordsTemplate = templateFile.exists() ? new String(FileUtils.read(templateFile)) : "{{REPLACE_RECORD}}";
templateFile = new File(Utils.toFilePath(DATA("/gacha_details.html")));
detailsTemplate = templateFile.exists() ? new String(FileUtils.read(templateFile)) : null;
}
@Override public void applyRoutes(Express express, Javalin handle) {
express.get("/gacha", GachaHandler::gachaRecords);
express.get("/gacha/details", GachaHandler::gachaDetails);
express.useStaticFallback("/gacha/mappings", this.gachaMappings, Location.EXTERNAL);
}
private static void gachaRecords(Request request, Response response) {
var sessionKey = request.query("s");
int page = 0, gachaType = 0;
if(request.query("p") != null)
page = Integer.parseInt(request.query("p"));
if(request.query("gachaType") != null)
gachaType = Integer.parseInt(request.query("gachaType"));
// Get account from session key.
var account = DatabaseHelper.getAccountBySessionKey(sessionKey);
if(account == null) // Send response.
response.status(404).send("Unable to find account.");
else {
String records = DatabaseHelper.getGachaRecords(account.getPlayerUid(), gachaType, page).toString();
long maxPage = DatabaseHelper.getGachaRecordsMaxPage(account.getPlayerUid(), page, gachaType);
response.send(recordsTemplate
.replace("{{REPLACE_RECORD}}", records)
.replace("{{REPLACE_MAXPAGE}}", String.valueOf(maxPage)));
}
}
private static void gachaDetails(Request request, Response response) {
String template = detailsTemplate;
// Get player info (for langauge).
String sessionKey = request.query("s");
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
Player player = Grasscutter.getGameServer().getPlayerByUid(account.getPlayerUid());
// If the template was not loaded, return an error.
if (detailsTemplate == null) {
response.send(translate(player, "gacha.details.template_missing"));
return;
}
// Add translated title etc. to the page.
template = template.replace("{{TITLE}}", translate(player, "gacha.details.title"))
.replace("{{AVAILABLE_FIVE_STARS}}", translate(player, "gacha.details.available_five_stars"))
.replace("{{AVAILABLE_FOUR_STARS}}", translate(player, "gacha.details.available_four_stars"))
.replace("{{AVAILABLE_THREE_STARS}}", translate(player, "gacha.details.available_three_stars"))
.replace("{{LANGUAGE}}", Utils.getLanguageCode(account.getLocale()));
// Get the banner info for the banner we want.
int gachaType = Integer.parseInt(request.query("gachaType"));
GachaManager manager = Grasscutter.getGameServer().getGachaManager();
GachaBanner banner = manager.getGachaBanners().get(gachaType);
// Add 5-star items.
Set<String> fiveStarItems = new LinkedHashSet<>();
Arrays.stream(banner.getRateUpItems5()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
Arrays.stream(banner.getFallbackItems5Pool1()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
Arrays.stream(banner.getFallbackItems5Pool2()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
template = template.replace("{{FIVE_STARS}}", "[" + String.join(",", fiveStarItems) + "]");
// Add 4-star items.
Set<String> fourStarItems = new LinkedHashSet<>();
Arrays.stream(banner.getRateUpItems4()).forEach(i -> fourStarItems.add(Integer.toString(i)));
Arrays.stream(banner.getFallbackItems4Pool1()).forEach(i -> fourStarItems.add(Integer.toString(i)));
Arrays.stream(banner.getFallbackItems4Pool2()).forEach(i -> fourStarItems.add(Integer.toString(i)));
template = template.replace("{{FOUR_STARS}}", "[" + String.join(",", fourStarItems) + "]");
// Add 3-star items.
Set<String> threeStarItems = new LinkedHashSet<>();
Arrays.stream(banner.getFallbackItems3()).forEach(i -> threeStarItems.add(Integer.toString(i)));
template = template.replace("{{THREE_STARS}}", "[" + String.join(",", threeStarItems) + "]");
// Done.
response.send(template);
}
}
package emu.grasscutter.server.http.handlers;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.server.http.objects.HttpJsonResponse;
import emu.grasscutter.server.http.Router;
import express.Express;
import express.http.Request;
import express.http.Response;
import io.javalin.Javalin;
/**
* Handles all generic, hard-coded responses.
*/
public final class GenericHandler implements Router {
@Override public void applyRoutes(Express express, Javalin handle) {
// hk4e-sdk-os.hoyoverse.com
express.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
// hk4e-sdk-os.hoyoverse.com
// this could be either GET or POST based on the observation of different clients
express.all("/hk4e_global/combo/granter/api/compareProtocolVersion", new HttpJsonResponse("{\"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\":\"\"}}}"));
// api-account-os.hoyoverse.com
express.post("/account/risky/api/check", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}"));
// sdk-os-static.hoyoverse.com
express.get("/combo/box/api/config/sdk/combo", new HttpJsonResponse("{\"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
express.get("/hk4e_global/combo/granter/api/getConfig", new HttpJsonResponse("{\"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
express.get("/hk4e_global/mdk/shield/api/loadConfig", new HttpJsonResponse("{\"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
express.post("/data_abtest_api/config/experiment/list", new HttpJsonResponse("{\"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
express.all("/log/sdk/upload", new HttpJsonResponse("{\"code\":0}"));
express.all("/sdk/upload", new HttpJsonResponse("{\"code\":0}"));
express.post("/sdk/dataUpload", new HttpJsonResponse("{\"code\":0}"));
// /perf/config/verify?device_id=xxx&platform=x&name=xxx
express.all("/perf/config/verify", new HttpJsonResponse("{\"code\":0}"));
// webstatic-sea.hoyoverse.com
express.get("/admin/mi18n/plat_oversea/m202003048/m202003048-version.json", new HttpJsonResponse("{\"version\":51}"));
express.get("/status/server", GenericHandler::serverStatus);
}
private static void serverStatus(Request request, Response response) {
int playerCount = Grasscutter.getGameServer().getPlayers().size();
String version = GameConstants.VERSION;
response.send("{\"retcode\":0,\"status\":{\"playerCount\":" + playerCount + ",\"version\":\"" + version + "\"}}");
}
}
package emu.grasscutter.server.http.handlers;
import emu.grasscutter.server.http.Router;
import express.Express;
import express.http.Request;
import express.http.Response;
import io.javalin.Javalin;
/**
* Handles logging requests made to the server.
*/
public final class LogHandler implements Router {
@Override public void applyRoutes(Express express, Javalin handle) {
// overseauspider.yuanshen.com
express.post("/log", LogHandler::log);
// log-upload-os.mihoyo.com
express.post("/crash/dataUpload", LogHandler::log);
}
private static void log(Request request, Response response) {
// TODO: Figure out how to dump request body and log to file.
response.send("{\"code\":0}");
}
}
package emu.grasscutter.server.dispatch.json;
package emu.grasscutter.server.http.objects;
public class ComboTokenReqJson {
public int app_id;
......
package emu.grasscutter.server.dispatch.json;
package emu.grasscutter.server.http.objects;
public class ComboTokenResJson {
public String message;
......
package emu.grasscutter.server.dispatch;
package emu.grasscutter.server.http.objects;
import java.io.IOException;
import java.util.Arrays;
......@@ -13,7 +13,7 @@ import express.http.Response;
import static emu.grasscutter.utils.Language.translate;
import static emu.grasscutter.Configuration.*;
public final class DispatchHttpJsonHandler implements HttpContextHandler {
public final class HttpJsonResponse implements HttpContextHandler {
private final String response;
private final String[] missingRoutes = { // TODO: When http requests for theses routes are found please remove it from this list and update the route request type in the DispatchServer
"/common/hk4e_global/announcement/api/getAlertPic",
......@@ -28,7 +28,7 @@ public final class DispatchHttpJsonHandler implements HttpContextHandler {
"/crash/dataUpload"
};
public DispatchHttpJsonHandler(String response) {
public HttpJsonResponse(String response) {
this.response = response;
}
......
package emu.grasscutter.server.dispatch.json;
package emu.grasscutter.server.http.objects;
public class LoginAccountRequestJson {
public String account;
......
package emu.grasscutter.server.dispatch.json;
package emu.grasscutter.server.http.objects;
public class LoginResultJson {
public String message;
......
package emu.grasscutter.server.dispatch.json;
package emu.grasscutter.server.http.objects;
public class LoginTokenRequestJson {
public String uid;
......
......@@ -9,11 +9,13 @@ import emu.grasscutter.net.proto.PlayerLoginRspOuterClass.PlayerLoginRsp;
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass;
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.http.dispatch.RegionHandler;
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.FileUtils;
import java.io.File;
import java.util.Base64;
import java.util.Objects;
import static emu.grasscutter.Configuration.*;
......@@ -46,7 +48,7 @@ public class PacketPlayerLoginRsp extends BasePacket {
info = regionCache.getRegionInfo();
} else {
info = Grasscutter.getDispatchServer().getCurrRegion().getRegionInfo();
info = Objects.requireNonNull(RegionHandler.getCurrentRegion()).getRegionInfo();
}
PlayerLoginRsp p = PlayerLoginRsp.newBuilder()
......
......@@ -17,7 +17,7 @@ import static emu.grasscutter.Grasscutter.config;
*/
public class ConfigContainer {
private static int version() {
return 2;
return 3;
}
/**
......@@ -96,8 +96,10 @@ public class ConfigContainer {
public ServerDebugMode debugLevel = ServerDebugMode.NONE;
public ServerRunMode runMode = ServerRunMode.HYBRID;
public Dispatch dispatch = new Dispatch();
public HTTP http = new HTTP();
public Game game = new Game();
public Dispatch dispatch = new Dispatch();
}
public static class Language {
......@@ -112,7 +114,7 @@ public class ConfigContainer {
/* Server options. */
public static class Dispatch {
public static class HTTP {
public String bindAddress = "0.0.0.0";
/* This is the address used in URLs. */
public String accessAddress = "127.0.0.1";
......@@ -123,9 +125,7 @@ public class ConfigContainer {
public Encryption encryption = new Encryption();
public Policies policies = new Policies();
public Region[] regions = {};
public String defaultName = "Grasscutter";
public Files files = new Files();
}
public static class Game {
......@@ -144,6 +144,12 @@ public class ConfigContainer {
/* Data containers. */
public static class Dispatch {
public Region[] regions = {};
public String defaultName = "Grasscutter";
}
public static class Encryption {
public boolean useEncryption = true;
/* Should 'https' be appended to URLs? */
......@@ -223,9 +229,26 @@ public class ConfigContainer {
public String signature = "Welcome to Grasscutter!";
}
public static class Files {
public String indexFile = "./index.html";
public String errorFile = "./404.html";
}
/* Objects. */
public static class Region {
public Region() { }
public Region(
String name, String title,
String address, int port
) {
this.Name = name;
this.Title = title;
this.Ip = address;
this.Port = port;
}
public String Name = "os_usa";
public String Title = "Grasscutter";
public String Ip = "127.0.0.1";
......
......@@ -6,10 +6,7 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Locale;
import java.util.*;
import emu.grasscutter.Grasscutter;
import io.netty.buffer.ByteBuf;
......@@ -309,13 +306,6 @@ public final class Utils {
return map;
}
/**
* get language code from Locale
*/
public static String getLanguageCode(Locale locale) {
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
/**
* Performs a linear interpolation using a table of fixed points to create an effective piecewise f(x) = y function.
* @param x
......@@ -380,4 +370,44 @@ public final class Utils {
}
return temp.toIntArray();
}
/**
* Gets the language code from a given locale.
* @param locale A locale.
* @return A string in the format of 'XX-XX'.
*/
public static String getLanguageCode(Locale locale) {
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
/**
* Base64 encodes a given byte array.
* @param toEncode An array of bytes.
* @return A base64 encoded string.
*/
public static String base64Encode(byte[] toEncode) {
return Base64.getEncoder().encodeToString(toEncode);
}
/**
* Base64 decodes a given string.
* @param toDecode A base64 encoded string.
* @return An array of bytes.
*/
public static byte[] base64Decode(String toDecode) {
return Base64.getDecoder().decode(toDecode);
}
/**
* Safely JSON decodes a given string.
* @param jsonData The JSON-encoded data.
* @return JSON decoded data, or null if an exception occurred.
*/
public static <T> T jsonDecode(String jsonData, Class<T> classType) {
try {
return Grasscutter.getGsonFactory().fromJson(jsonData, classType);
} catch (Exception ignored) {
return null;
}
}
}
......@@ -36,7 +36,8 @@
"session_key_error": "Wrong session key.",
"username_error": "Username not found.",
"username_create_error": "Username not found, create failed."
}
},
"router_error": "[Dispatch] Unable to attach router."
},
"status": {
"free_software": "Grasscutter is FREE software. If you have paid for this, you may have been scammed. Homepage: https://github.com/Grasscutters/Grasscutter",
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment