commit 6ddd24bfad31366802cbb27164da6ba9bb17bf88 Author: flashwave Date: Wed Aug 23 01:43:53 2023 +0200 Initial import diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9141329 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +indent_style = space +indent_size = 4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c476faf --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ + +# java + +hs_err_*.log +replay_*.log +*.hprof +*.jfr diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..44772e8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2023, flashwave +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted (subject to the limitations in the disclaimer +below) provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY +THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..aa95b99 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# Flashii Minecraft Extensions +This is a [Fabric](https://fabricmc.net/) mod that can run on both clients and servers. +Because the mod is relatively simple, Fabric API is not required and just having Fabric Loader works fine. + +On servers it functions as an authentication provider while running on Offline Mode by RPCing with the [Mince](https://git.flash.moe/flashii/mince) project. +On clients it enables skins while the server connected to is running in Offline Mode, it is not required but strongly recommended. + +This mod is not meant to enable or otherwise facilitate piracy, rather as an alternative for players who have previously purchased the game and are dissatisfied with Microsoft's handling of the property. + +## Compiling +``` +gradlew downloadAssets +gradlew genSources +gradlew build +``` + +## Known issues + - UniversalGraves doesn't seem to load skins properly. In true Java fashion, its codebase is a mystery to me and I feel like I'm going in circles. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..e6afdb5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,47 @@ +plugins { + id 'fabric-loom' version '1.3-SNAPSHOT' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories {} + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + implementation 'com.google.code.gson:gson:2.10.1' +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.encoding = "UTF-8" + it.options.release = 17 + it.options.compilerArgs += ['-Xlint:deprecation', '-Xlint:unchecked'] +} + +java { + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +jar { + from("LICENSE") { + rename { "${it}_${project.base.archivesName.get()}"} + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6898acc --- /dev/null +++ b/gradle.properties @@ -0,0 +1,14 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true + +# Fabric Properties +# check these on https://fabricmc.net/develop +minecraft_version=1.20.1 +yarn_mappings=1.20.1+build.10 +loader_version=0.14.22 + +# Mod Properties +mod_version=1.0.0 +maven_group=net.flashii.mcexts +archives_base_name=flashii-extensions diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f4197d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..fcb6fca --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..dfacbd1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} diff --git a/src/main/java/net/flashii/mcexts/Config.java b/src/main/java/net/flashii/mcexts/Config.java new file mode 100644 index 0000000..6a13893 --- /dev/null +++ b/src/main/java/net/flashii/mcexts/Config.java @@ -0,0 +1,71 @@ +package net.flashii.mcexts; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import net.fabricmc.loader.api.FabricLoader; + +public class Config { + static class ConfigCache { + private static final long CACHE_TIMEOUT = 300000; + + public long readTime; + public String contents; + + public ConfigCache(String contents) { + this.readTime = System.currentTimeMillis(); + this.contents = contents; + } + + public boolean needsRefresh() { + return readTime < System.currentTimeMillis() - CACHE_TIMEOUT; + } + } + + private static Path configPath = null; + private static HashMap cache = new HashMap<>(); + + private static Path getConfigPath() { + if(configPath == null) + configPath = FabricLoader.getInstance().getGameDir().resolve("config").resolve("fiiexts"); + return configPath; + } + + private static Path getConfigPath(String name) { + return getConfigPath().resolve(name); + } + + public static String getValue(String name) { + return getValue(name, null); + } + + public static String getValue(String name, String fallback) { + return getFileContentsCached(getConfigPath(name), fallback); + } + + private static String getFileContentsCached(Path path, String fallback) { + String output = null; + + String pathStr = path.toString(); + if(cache.containsKey(pathStr)) { + ConfigCache cached = cache.get(pathStr); + if(!cached.needsRefresh()) + output = cached.contents; + } + + if(output == null) { + try { + output = Files.exists(path) ? Files.readString(path).trim() : fallback; + } catch(IOException ex) { + ex.printStackTrace(); + output = fallback; + } + + cache.put(pathStr, new ConfigCache(output)); + } + + return output; + } +} diff --git a/src/main/java/net/flashii/mcexts/HMAC.java b/src/main/java/net/flashii/mcexts/HMAC.java new file mode 100644 index 0000000..493767a --- /dev/null +++ b/src/main/java/net/flashii/mcexts/HMAC.java @@ -0,0 +1,32 @@ +package net.flashii.mcexts; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +public class HMAC { + public static final String SHA256 = "HmacSHA256"; + + public static byte[] calculate(String method, String secret, String data) + throws GeneralSecurityException { + return calculate(method, secret.getBytes(StandardCharsets.UTF_8), data.getBytes(StandardCharsets.UTF_8)); + } + + public static byte[] calculate(String method, byte[] secret, String data) + throws GeneralSecurityException { + return calculate(method, secret, data.getBytes(StandardCharsets.UTF_8)); + } + + public static byte[] calculate(String method, String secret, byte[] data) + throws GeneralSecurityException { + return calculate(method, secret.getBytes(StandardCharsets.UTF_8), data); + } + + public static byte[] calculate(String method, byte[] secret, byte[] data) + throws GeneralSecurityException { + Mac hmac = Mac.getInstance(method); + hmac.init(new SecretKeySpec(secret, method)); + return hmac.doFinal(data); + } +} diff --git a/src/main/java/net/flashii/mcexts/RPC.java b/src/main/java/net/flashii/mcexts/RPC.java new file mode 100644 index 0000000..1ee64fa --- /dev/null +++ b/src/main/java/net/flashii/mcexts/RPC.java @@ -0,0 +1,128 @@ +package net.flashii.mcexts; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class RPC { + private static final String DEFAULT_SECRET = "meow"; + + private static Gson gson = null; + + public static Gson getGson() { + if(gson == null) + gson = new GsonBuilder() + .registerTypeAdapter(RPCPayload.class, new RPCPayloadDeserialiser()) + .create(); + return gson; + } + + public static String getSecretKey() { + return Config.getValue("RPCSecretKey.txt", DEFAULT_SECRET); + } + + public static String getRequestTimestamp() { + return Long.toString(System.currentTimeMillis() / 1000); + } + + public static String createParamString(Map params) { + StringBuilder sb = new StringBuilder(); + + params.forEach((key, value) -> { + sb.append(key); + sb.append('='); + sb.append(URLEncoder.encode(value.toString(), StandardCharsets.UTF_8)); + sb.append('&'); + }); + + // remove the trailing ampersand + int length = sb.length(); + if(length > 0) + sb.setLength(length - 1); + + return sb.toString(); + } + + public static String createRequestSignature(String time, String path, String params) + throws GeneralSecurityException { + return Base64.getEncoder().encodeToString(HMAC.calculate( + HMAC.SHA256, getSecretKey(), String.format("%s#%s?%s", time, path, params) + )); + } + + // sigStr and bodyStr because sigStr must also include the query params if those are present + public static RPCPayload callRpc(String path, String sigStr, String bodyStr) + throws GeneralSecurityException, IOException { + boolean hasBody = bodyStr != null; + String time = getRequestTimestamp(); + String hash = createRequestSignature(time, URLs.getRpcPath(path), sigStr); + + HttpURLConnection conn = (HttpURLConnection)(new URL(URLs.getRpcUrl(path))).openConnection(); + conn.setRequestMethod(hasBody ? "POST" : "GET"); + conn.setRequestProperty("X-Mince-Time", time); + conn.setRequestProperty("X-Mince-Hash", hash); + + if(hasBody) { + conn.setDoOutput(true); + conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + try(OutputStream stream = conn.getOutputStream()) { + byte[] input = bodyStr.getBytes(StandardCharsets.UTF_8); + stream.write(input, 0, input.length); + } + } + + StringBuilder sb = new StringBuilder(); + try(BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { + String line; + while((line = br.readLine()) != null) + sb.append(line); + } + + return getGson().fromJson(sb.toString(), RPCPayload.class); + } + + public static RPCPayload callRpc(String path, String paramStr) + throws GeneralSecurityException, IOException { + return callRpc(path, paramStr, paramStr); + } + + public static RPCPayload callRpc(String path, Map params) + throws GeneralSecurityException, IOException { + return callRpc(path, createParamString(params)); + } + + public static RPCPayload postAuth(UUID id, String name, InetAddress remoteAddr) + throws GeneralSecurityException, IOException { + HashMap params = new HashMap<>(); + params.put("id", id); + params.put("name", name); + params.put("ip", remoteAddr.getHostAddress()); + + return callRpc("/auth", params); + } + + public static RPCPayload postAuth(UUID id, String name, SocketAddress sockAddr) + throws GeneralSecurityException, IOException { + InetAddress remoteAddr = sockAddr instanceof InetSocketAddress + ? ((InetSocketAddress)sockAddr).getAddress() + : InetAddress.getLoopbackAddress(); + + return postAuth(id, name, remoteAddr); + } +} diff --git a/src/main/java/net/flashii/mcexts/RPCPayload.java b/src/main/java/net/flashii/mcexts/RPCPayload.java new file mode 100644 index 0000000..8bbf0b1 --- /dev/null +++ b/src/main/java/net/flashii/mcexts/RPCPayload.java @@ -0,0 +1,37 @@ +package net.flashii.mcexts; + +import java.util.Map; + +public class RPCPayload { + private final String name; + private final Map attrs; + + public RPCPayload(String name, Map attrs) { + this.name = name; + this.attrs = attrs; + } + + public String getName() { + return name; + } + + public boolean is(String name) { + return this.name.equals(name); + } + + public boolean hasAttr(String name) { + return attrs.containsKey(name); + } + + public Object getAttr(String name) { + return attrs.get(name); + } + + public String getAttrStr(String name) { + return String.valueOf(attrs.get(name)); + } + + public int getAttrInt(String name) { + return (int)attrs.get(name); + } +} diff --git a/src/main/java/net/flashii/mcexts/RPCPayloadDeserialiser.java b/src/main/java/net/flashii/mcexts/RPCPayloadDeserialiser.java new file mode 100644 index 0000000..e40431f --- /dev/null +++ b/src/main/java/net/flashii/mcexts/RPCPayloadDeserialiser.java @@ -0,0 +1,41 @@ +package net.flashii.mcexts; + +import java.lang.reflect.Type; +import java.util.HashMap; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; + +public class RPCPayloadDeserialiser implements JsonDeserializer { + @Override + public RPCPayload deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + JsonObject obj = json.getAsJsonObject(); + + String name = obj.get("name").getAsString(); + JsonArray attrElems = obj.get("attrs").getAsJsonArray(); + + HashMap attrs = new HashMap<>(); + for(JsonElement attrElem : attrElems) { + JsonObject attrObj = attrElem.getAsJsonObject(); + JsonPrimitive attrValuePrimitive = attrObj.get("value").getAsJsonPrimitive(); + Object attrValue = null; + + if(attrValuePrimitive.isBoolean()) + attrValue = attrValuePrimitive.getAsBoolean(); + else if(attrValuePrimitive.isString()) + attrValue = attrValuePrimitive.getAsString(); + else if(attrValuePrimitive.isNumber()) // there's gotta be a better way of doing this + attrValue = attrValuePrimitive.getAsInt(); + + if(attrValue != null) + attrs.put(attrObj.get("name").getAsString(), attrValue); + } + + return new RPCPayload(name, attrs); + } +} diff --git a/src/main/java/net/flashii/mcexts/URLs.java b/src/main/java/net/flashii/mcexts/URLs.java new file mode 100644 index 0000000..db3735a --- /dev/null +++ b/src/main/java/net/flashii/mcexts/URLs.java @@ -0,0 +1,26 @@ +package net.flashii.mcexts; + +public class URLs { + private static final String DEFAULT_HOST = "https://mc.flashii.net"; + private static final String RPC_PATH = "/rpc"; + + public static String getBaseUrl() { + return Config.getValue("BaseURL.txt", DEFAULT_HOST); + } + + public static String getSessionHost() { + return getBaseUrl(); + } + + public static String getTexturesHostPrefix() { + return getSessionHost() + "/"; + } + + public static String getRpcUrl(String path) { + return getBaseUrl() + getRpcPath(path); + } + + public static String getRpcPath(String path) { + return RPC_PATH + path; + } +} diff --git a/src/main/java/net/flashii/mcexts/mixin/EnvironmentMixin.java b/src/main/java/net/flashii/mcexts/mixin/EnvironmentMixin.java new file mode 100644 index 0000000..2deaadf --- /dev/null +++ b/src/main/java/net/flashii/mcexts/mixin/EnvironmentMixin.java @@ -0,0 +1,16 @@ +package net.flashii.mcexts.mixin; + +import net.flashii.mcexts.URLs; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(targets = "com.mojang.authlib.Environment$1") +public abstract class EnvironmentMixin { + @Inject(method = "getSessionHost()Ljava/lang/String;", at = @At("HEAD"), cancellable = true, remap = false) + private void getSessionHost(CallbackInfoReturnable cir) { + cir.setReturnValue(URLs.getSessionHost()); + cir.cancel(); + } +} diff --git a/src/main/java/net/flashii/mcexts/mixin/PlayerListHudMixin.java b/src/main/java/net/flashii/mcexts/mixin/PlayerListHudMixin.java new file mode 100644 index 0000000..ef407fc --- /dev/null +++ b/src/main/java/net/flashii/mcexts/mixin/PlayerListHudMixin.java @@ -0,0 +1,16 @@ +package net.flashii.mcexts.mixin; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.hud.PlayerListHud; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(PlayerListHud.class) +public abstract class PlayerListHudMixin { + @Redirect(method = "render(Lnet/minecraft/client/gui/DrawContext;ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreboardObjective;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;isInSingleplayer()Z")) + public boolean redirectIsInSinglePlayer(MinecraftClient client) { + // always enable BL + return true; + } +} diff --git a/src/main/java/net/flashii/mcexts/mixin/PlayerManagerMixin.java b/src/main/java/net/flashii/mcexts/mixin/PlayerManagerMixin.java new file mode 100644 index 0000000..a734995 --- /dev/null +++ b/src/main/java/net/flashii/mcexts/mixin/PlayerManagerMixin.java @@ -0,0 +1,70 @@ +package net.flashii.mcexts.mixin; + +import java.io.IOException; +import java.net.SocketAddress; +import java.security.GeneralSecurityException; +import com.mojang.authlib.GameProfile; +import net.flashii.mcexts.RPC; +import net.flashii.mcexts.RPCPayload; +import net.minecraft.server.PlayerManager; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(PlayerManager.class) +public abstract class PlayerManagerMixin { + @Inject(method = "checkCanJoin(Ljava/net/SocketAddress;Lcom/mojang/authlib/GameProfile;)Lnet/minecraft/text/Text;", at = @At("HEAD"), cancellable = true) + private void checkCanJoin(SocketAddress sockAddr, GameProfile profile, CallbackInfoReturnable cir) { + Text authText = null; + + try { + RPCPayload payload = RPC.postAuth(profile.getId(), profile.getName(), sockAddr); + + if(!payload.is("auth:ok")) { + if(payload.is("error")) { + authText = Text.literal( + payload.getAttrStr(payload.hasAttr("text") ? "text" : "code") + ).formatted(Formatting.RED); + } else if(payload.is("auth:authorise")) { + String userName = payload.getAttrStr("user_name"); + int userColour = payload.hasAttr("user_colour") ? payload.getAttrInt("user_colour") : 0xFFFFFF; + String url = payload.getAttrStr("url"); + + authText = Text.literal("Welcome back, ") + .append(Text.literal(userName).styled(style -> style.withColor(userColour).withBold(true))) + .append(Text.literal("!\n\n")) + .append(Text.literal("Please go to ")) + .append(Text.literal(url).formatted(Formatting.BLUE)) + .append(Text.literal(" in your web browser to verify that it is actually you that is connecting.\n\n")) + .append(Text.literal("After you've approved the attempt, connect to the server again and you should be good to go.")); + } else if(payload.is("auth:link")) { + String code = payload.getAttrStr("code"); + String url = payload.getAttrStr("url"); + + authText = Text.literal("This seems to be the first time you're connecting!\n") + .append(Text.literal("Visit ")) + .append(Text.literal(url).formatted(Formatting.BLUE)) + .append(Text.literal(" in your web browser to connect your Flashii ID.\n\nYour link code is: ")) + .append(Text.literal(code).formatted(Formatting.LIGHT_PURPLE)) + .append(Text.literal("\n\nAfter you've approved the attempt, connect to the server again and you should be good to go.")); + } else { + authText = Text.literal("Flashii authentication server returned an unknown response, yell at flashwave about this.").formatted(Formatting.RED); + } + } + } catch(IOException ex) { + authText = Text.literal("Flashii authentication server failed to respond, yell at flashwave about this.").formatted(Formatting.RED); + ex.printStackTrace(); + } catch(GeneralSecurityException ex) { + authText = Text.literal("Problem with request verification, yell at flashwave about this.").formatted(Formatting.RED); + ex.printStackTrace(); + } + + if(authText != null) { + cir.setReturnValue(authText); + cir.cancel(); + } + } +} diff --git a/src/main/java/net/flashii/mcexts/mixin/TextureUrlCheckerMixin.java b/src/main/java/net/flashii/mcexts/mixin/TextureUrlCheckerMixin.java new file mode 100644 index 0000000..3ce19fa --- /dev/null +++ b/src/main/java/net/flashii/mcexts/mixin/TextureUrlCheckerMixin.java @@ -0,0 +1,19 @@ +package net.flashii.mcexts.mixin; + +import com.mojang.authlib.yggdrasil.TextureUrlChecker; +import net.flashii.mcexts.URLs; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(TextureUrlChecker.class) +public abstract class TextureUrlCheckerMixin { + @Inject(method = "isAllowedTextureDomain(Ljava/lang/String;)Z", at = @At("HEAD"), cancellable = true, remap = false) + private static void isAllowedTextureDomain(String url, CallbackInfoReturnable cir) { + if(url == null || url.startsWith(URLs.getTexturesHostPrefix())) { + cir.setReturnValue(true); + cir.cancel(); + } + } +} diff --git a/src/main/java/net/flashii/mcexts/mixin/YggdrasilMinecraftSessionServiceMixin.java b/src/main/java/net/flashii/mcexts/mixin/YggdrasilMinecraftSessionServiceMixin.java new file mode 100644 index 0000000..42eeca6 --- /dev/null +++ b/src/main/java/net/flashii/mcexts/mixin/YggdrasilMinecraftSessionServiceMixin.java @@ -0,0 +1,24 @@ +package net.flashii.mcexts.mixin; + +import com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(YggdrasilMinecraftSessionService.class) +public abstract class YggdrasilMinecraftSessionServiceMixin { + @ModifyVariable(method = "getTextures(Lcom/mojang/authlib/GameProfile;Z)Ljava/util/Map;", at = @At("HEAD"), argsOnly = true, remap = false) + private boolean interceptGetTexturesRequireSecure(boolean requireSecure) { + return false; + } + + @ModifyVariable(method = "fillProfileProperties(Lcom/mojang/authlib/GameProfile;Z)Lcom/mojang/authlib/GameProfile;", at = @At("HEAD"), argsOnly = true, remap = false) + private boolean interceptFillProfilePropertiesRequireSecure(boolean requireSecure) { + return true; + } + + @ModifyVariable(method = "fillGameProfile(Lcom/mojang/authlib/GameProfile;Z)Lcom/mojang/authlib/GameProfile;", at = @At("HEAD"), argsOnly = true, remap = false) + private boolean interceptFillGameProfileRequireSecure(boolean requireSecure) { + return false; + } +} diff --git a/src/main/resources/assets/flashii-extensions/icon.png b/src/main/resources/assets/flashii-extensions/icon.png new file mode 100644 index 0000000..5d9e472 Binary files /dev/null and b/src/main/resources/assets/flashii-extensions/icon.png differ diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..f4fcb95 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,25 @@ +{ + "schemaVersion": 1, + "id": "flashii-extensions", + "version": "${version}", + "name": "Flashii Extensions", + "description": "This mod provides extensions for the Flashii.net Minecraft servers.", + "authors": [ + "flashwave" + ], + "contact": { + "homepage": "https://mc.flashii.net/", + "sources": "https://git.flash.moe/flashii/mcexts" + }, + "license": "BSD-3-Clause-Clear", + "icon": "assets/flashii-extensions/icon.png", + "environment": "*", + "mixins": [ + "flashii-extensions.mixins.json" + ], + "depends": { + "fabricloader": ">=0.14.22", + "minecraft": "~1.20.1", + "java": ">=17" + } +} diff --git a/src/main/resources/flashii-extensions.mixins.json b/src/main/resources/flashii-extensions.mixins.json new file mode 100644 index 0000000..e52792b --- /dev/null +++ b/src/main/resources/flashii-extensions.mixins.json @@ -0,0 +1,17 @@ +{ + "required": true, + "package": "net.flashii.mcexts.mixin", + "compatibilityLevel": "JAVA_17", + "mixins": [ + "EnvironmentMixin", + "PlayerListHudMixin", + "TextureUrlCheckerMixin", + "YggdrasilMinecraftSessionServiceMixin" + ], + "server": [ + "PlayerManagerMixin" + ], + "injectors": { + "defaultRequire": 1 + } +}