From cff1b4a22bb47c8bcf064d5e8da8c7d7ef67ea52 Mon Sep 17 00:00:00 2001 From: mdxd44 Date: Fri, 17 Dec 2021 19:31:55 +0900 Subject: Split projects. --- .github/ISSUE_TEMPLATE/bug_report.md | 30 ++ .github/workflows/build.yml | 32 ++ .github/workflows/test.yml | 32 ++ .gitignore | 120 +++++++ HEADER.txt | 14 + VERSION | 1 + build.gradle | 115 ++++++ config/checkstyle/checkstyle.xml | 369 +++++++++++++++++++ config/checkstyle/suppressions.xml | 16 + config/spotbugs/suppressions.xml | 7 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 59536 bytes gradle/wrapper/gradle-wrapper.properties | 5 + gradlew | 234 ++++++++++++ gradlew.bat | 89 +++++ settings.gradle | 1 + .../java/net/elytrium/limboauth/LimboAuth.java | 371 +++++++++++++++++++ src/main/java/net/elytrium/limboauth/Settings.java | 196 +++++++++++ .../limboauth/command/ChangePasswordCommand.java | 101 ++++++ .../limboauth/command/DestroySessionCommand.java | 60 ++++ .../limboauth/command/ForceUnregisterCommand.java | 106 ++++++ .../limboauth/command/LimboAuthCommand.java | 95 +++++ .../elytrium/limboauth/command/TotpCommand.java | 204 +++++++++++ .../limboauth/command/UnregisterCommand.java | 97 +++++ .../java/net/elytrium/limboauth/config/Config.java | 392 +++++++++++++++++++++ .../limboauth/handler/AuthSessionHandler.java | 297 ++++++++++++++++ .../elytrium/limboauth/listener/AuthListener.java | 114 ++++++ .../limboauth/migration/MigrationHash.java | 54 +++ .../limboauth/migration/MigrationHashVerifier.java | 23 ++ .../elytrium/limboauth/model/RegisteredPlayer.java | 130 +++++++ .../elytrium/limboauth/utils/UpdatesChecker.java | 75 ++++ .../net/elytrium/limboauth/BuildConstants.java | 24 ++ 31 files changed, 3404 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 HEADER.txt create mode 100644 VERSION create mode 100644 build.gradle create mode 100644 config/checkstyle/checkstyle.xml create mode 100644 config/checkstyle/suppressions.xml create mode 100644 config/spotbugs/suppressions.xml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/java/net/elytrium/limboauth/LimboAuth.java create mode 100644 src/main/java/net/elytrium/limboauth/Settings.java create mode 100644 src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java create mode 100644 src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java create mode 100644 src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java create mode 100644 src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java create mode 100644 src/main/java/net/elytrium/limboauth/command/TotpCommand.java create mode 100644 src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java create mode 100644 src/main/java/net/elytrium/limboauth/config/Config.java create mode 100644 src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java create mode 100644 src/main/java/net/elytrium/limboauth/listener/AuthListener.java create mode 100644 src/main/java/net/elytrium/limboauth/migration/MigrationHash.java create mode 100644 src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java create mode 100644 src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java create mode 100644 src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java create mode 100644 src/main/templates/net/elytrium/limboauth/BuildConstants.java diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..68093ca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,30 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG] " +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Set '...' in config to '...' +2. Do in game '....' +3. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Server Info (please complete the following information):** + - LimboAPI Version [e.g. 1.0.1-rc2, downloaded from https://github.com/Elytrium/LimboAPI/actions/runs/1354021163] + - /velocity dump link [e.g. https://dump.velocitypowered.com/dotihadufu.json] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..40d732e --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,32 @@ +name: Java CI with Gradle + +on: [ push ] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 11, 16 ] + fail-fast: true + steps: + - name: Checkout + uses: actions/checkout@v2.3.5 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v2.3.1 + with: + distribution: adopt + java-version: ${{ matrix.java }} + - name: Cache Gradle + uses: actions/cache@v2.1.6 + with: + path: ~/.gradle + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: ${{ runner.os }}-gradle- + - name: Build LimboAuth + run: ./gradlew build + - name: Upload LimboAuth + uses: actions/upload-artifact@v2.2.4 + with: + name: LimboAuth Built On ${{ matrix.java }} JDK + path: "build/libs/limboauth*.jar" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..6259d74 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,32 @@ +name: Java CI with Gradle [PR tests] + +on: [ pull_request ] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 11, 16 ] + fail-fast: true + steps: + - name: Checkout + uses: actions/checkout@v2.3.5 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v2.3.1 + with: + distribution: adopt + java-version: ${{ matrix.java }} + - name: Cache Gradle + uses: actions/cache@v2.1.6 + with: + path: ~/.gradle + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: ${{ runner.os }}-gradle- + - name: Build LimboAuth + run: ./gradlew build + - name: Upload LimboAuth + uses: actions/upload-artifact@v2.2.4 + with: + name: LimboAuth Built On ${{ matrix.java }} JDK + path: "build/libs/limboauth*.jar" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..442df48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,120 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# Virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# Temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Gradle +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +# Gradle Patch +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar diff --git a/HEADER.txt b/HEADER.txt new file mode 100644 index 0000000..f52ff2f --- /dev/null +++ b/HEADER.txt @@ -0,0 +1,14 @@ +Copyright (C) 2021 Elytrium + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6d7de6e --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +1.0.2 diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ac00097 --- /dev/null +++ b/build.gradle @@ -0,0 +1,115 @@ +//file:noinspection GroovyAssignabilityCheck + +plugins { + id("java") + id("checkstyle") + id("com.github.spotbugs").version("5.0.3") + id("org.cadixdev.licenser").version("0.6.1") + id("com.github.johnrengelman.shadow").version("7.1.0") +} + +setGroup("net.elytrium") +setVersion("1.0.3-SNAPSHOT") + +compileJava { + getOptions().setEncoding("UTF-8") +} + +java { + setSourceCompatibility(JavaVersion.VERSION_11) + setTargetCompatibility(JavaVersion.VERSION_11) +} + +repositories { + mavenCentral() + + maven { + setName("velocitypowered-repo") + setUrl("https://nexus.velocitypowered.com/repository/maven-public/") + } + maven { + setName("elytrium-repo") + setUrl("https://maven.elytrium.net/repo/") + } +} + +dependencies { + compileOnly("net.elytrium:limboapi-api:1.0.3-SNAPSHOT") + + compileOnly("com.velocitypowered:velocity-api:3.1.0") + annotationProcessor("com.velocitypowered:velocity-api:3.1.0") + + implementation("at.favre.lib:bcrypt:0.9.0") + implementation("dev.samstevens.totp:totp:1.7.1") + + implementation("com.j256.ormlite:ormlite-jdbc:5.7") + + implementation("com.h2database:h2:2.0.202") + implementation("mysql:mysql-connector-java:8.0.27") + implementation("org.postgresql:postgresql:42.3.1") + + compileOnly("com.github.spotbugs:spotbugs-annotations:4.5.2") +} + +shadowJar { + getArchiveClassifier().set("") + + exclude("META-INF/maven/**") + exclude("META-INF/INFO_BIN") + exclude("META-INF/INFO_SRC") + exclude("google/protobuf/**") + exclude("com/google/protobuf/**") + exclude("com/mysql/cj/x/**") + exclude("com/mysql/cj/xdevapi/**") + exclude("org/apache/commons/codec/language/**") + exclude("org/checkerframework/**") + exclude("**/package-info.class") + + minimize() + + relocate("at.favre.lib", "net.elytrium.limboauth.thirdparty.at.favre.lib") + relocate("com.j256.ormlite", "net.elytrium.limboauth.thirdparty.com.j256.ormlite") + relocate("com.mysql", "net.elytrium.limboauth.thirdparty.com.mysql") + relocate("dev.samstevens.totp", "net.elytrium.limboauth.thirdparty.dev.samstevens.totp") + relocate("org.apache.commons.codec", "net.elytrium.limboauth.thirdparty.org.apache.commons.codec") + relocate("org.h2", "net.elytrium.limboauth.thirdparty.org.h2") + relocate("org.postgresql", "net.elytrium.limboauth.thirdparty.org.postgresql") +} + +license { + setHeader(file("HEADER.txt")) +} + +checkstyle { + setToolVersion("9.2") + setConfigFile(file("${this.getRootDir()}/config/checkstyle/checkstyle.xml")) + setConfigProperties("configDirectory": "${this.getRootDir()}/config/checkstyle") + + // The build should immediately fail if we have errors. + setMaxErrors(0) + setMaxWarnings(0) +} + +spotbugsMain { + setExcludeFilter(file("${this.getRootDir()}/config/spotbugs/suppressions.xml")) + + reports { + html { + getRequired().set(true) + getOutputLocation().set(file("${this.getBuildDir()}/reports/spotbugs/main/spotbugs.html")) + setStylesheet("fancy-hist.xsl") + } + } +} + +sourceSets.main.getJava().srcDir(getTasks().register("generateTemplates", Copy) { task -> + task.getInputs().properties("version": getVersion()) + + task.from(file("src/main/templates")) + .into(getLayout().getBuildDirectory().dir("generated/sources/templates")) + .expand("version": getVersion()) +}.map { + it.getOutputs() +}) + +assemble.dependsOn(shadowJar) diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000..f6a501f --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,369 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000..caae7d8 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/config/spotbugs/suppressions.xml b/config/spotbugs/suppressions.xml new file mode 100644 index 0000000..3b4b6f6 --- /dev/null +++ b/config/spotbugs/suppressions.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 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..84d1f85 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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 \ + "$@" + +# 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..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..bbe3302 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +getRootProject().setName("limboauth") diff --git a/src/main/java/net/elytrium/limboauth/LimboAuth.java b/src/main/java/net/elytrium/limboauth/LimboAuth.java new file mode 100644 index 0000000..a901bc2 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/LimboAuth.java @@ -0,0 +1,371 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package net.elytrium.limboauth; + +import com.google.inject.Inject; +import com.google.inject.name.Named; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.field.FieldType; +import com.j256.ormlite.jdbc.JdbcPooledConnectionSource; +import com.j256.ormlite.table.TableUtils; +import com.velocitypowered.api.command.CommandManager; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.plugin.Dependency; +import com.velocitypowered.api.plugin.Plugin; +import com.velocitypowered.api.plugin.PluginContainer; +import com.velocitypowered.api.plugin.annotation.DataDirectory; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Path; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import net.elytrium.limboapi.api.Limbo; +import net.elytrium.limboapi.api.LimboFactory; +import net.elytrium.limboapi.api.chunk.Dimension; +import net.elytrium.limboapi.api.chunk.VirtualWorld; +import net.elytrium.limboapi.api.file.SchematicFile; +import net.elytrium.limboapi.api.file.WorldFile; +import net.elytrium.limboauth.command.ChangePasswordCommand; +import net.elytrium.limboauth.command.DestroySessionCommand; +import net.elytrium.limboauth.command.ForceUnregisterCommand; +import net.elytrium.limboauth.command.LimboAuthCommand; +import net.elytrium.limboauth.command.TotpCommand; +import net.elytrium.limboauth.command.UnregisterCommand; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.listener.AuthListener; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.elytrium.limboauth.utils.UpdatesChecker; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.slf4j.Logger; + +@Plugin( + id = "limboauth", + name = "LimboAuth", + version = BuildConstants.AUTH_VERSION, + url = "https://elytrium.net/", + authors = {"hevav", "mdxd44"}, + dependencies = {@Dependency(id = "limboapi")} +) +public class LimboAuth { + + private static LimboAuth instance; + + private final HttpClient client = HttpClient.newHttpClient(); + private final Path dataDirectory; + private final Logger logger; + private final ProxyServer server; + private final LimboFactory factory; + + private Dao playerDao; + private Limbo authServer; + private Map cachedAuthChecks; + private Component nicknameInvalid; + private Pattern nicknameValidationPattern; + + @Inject + @SuppressWarnings("OptionalGetWithoutIsPresent") + public LimboAuth(ProxyServer server, Logger logger, @Named("limboapi") PluginContainer factory, @DataDirectory Path dataDirectory) { + setInstance(this); + + this.server = server; + this.logger = logger; + this.dataDirectory = dataDirectory; + this.factory = (LimboFactory) factory.getInstance().get(); + } + + @Subscribe + public void onProxyInitialization(ProxyInitializeEvent event) throws SQLException { + System.setProperty("com.j256.simplelogging.level", "ERROR"); + + this.reload(); + + UpdatesChecker.checkForUpdates(this.getLogger()); + } + + @SuppressWarnings("SwitchStatementWithTooFewBranches") + public void reload() throws SQLException { + Settings.IMP.reload(new File(this.dataDirectory.toFile().getAbsoluteFile(), "config.yml")); + + this.cachedAuthChecks = new ConcurrentHashMap<>(); + + Settings.DATABASE dbConfig = Settings.IMP.DATABASE; + + JdbcPooledConnectionSource connectionSource; + // requireNonNull prevents the shade plugin from excluding the drivers in minimized jar. + switch (dbConfig.STORAGE_TYPE.toLowerCase(Locale.ROOT)) { + case "h2": { + Objects.requireNonNull(org.h2.Driver.class); + Objects.requireNonNull(org.h2.engine.Engine.class); + connectionSource = new JdbcPooledConnectionSource("jdbc:h2:" + this.dataDirectory.toFile().getAbsoluteFile() + "/" + "limboauth"); + break; + } + case "mysql": { + Objects.requireNonNull(com.mysql.cj.jdbc.Driver.class); + Objects.requireNonNull(com.mysql.cj.conf.url.SingleConnectionUrl.class); + connectionSource = new JdbcPooledConnectionSource( + "jdbc:mysql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD + ); + break; + } + case "postgresql": { + Objects.requireNonNull(org.postgresql.Driver.class); + connectionSource = new JdbcPooledConnectionSource( + "jdbc:postgresql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD + ); + break; + } + default: { + this.getLogger().error("WRONG DATABASE TYPE."); + this.server.shutdown(); + return; + } + } + + TableUtils.createTableIfNotExists(connectionSource, RegisteredPlayer.class); + this.playerDao = DaoManager.createDao(connectionSource, RegisteredPlayer.class); + this.nicknameValidationPattern = Pattern.compile(Settings.IMP.MAIN.ALLOWED_NICKNAME_REGEX); + + this.migrateDb(this.playerDao); + + CommandManager manager = this.server.getCommandManager(); + manager.unregister("unregister"); + manager.unregister("forceunregister"); + manager.unregister("changepassword"); + manager.unregister("destroysession"); + manager.unregister("2fa"); + manager.unregister("limboauth"); + + manager.register("unregister", new UnregisterCommand(this, this.playerDao), "unreg"); + manager.register("forceunregister", new ForceUnregisterCommand(this, this.server, this.playerDao), "forceunreg"); + manager.register("changepassword", new ChangePasswordCommand(this.playerDao), "changepass"); + manager.register("destroysession", new DestroySessionCommand(this)); + if (Settings.IMP.MAIN.ENABLE_TOTP) { + manager.register("2fa", new TotpCommand(this.playerDao), "totp"); + } + manager.register("limboauth", new LimboAuthCommand(), "la", "auth", "lauth"); + + Settings.MAIN.AUTH_COORDS authCoords = Settings.IMP.MAIN.AUTH_COORDS; + VirtualWorld authWorld = this.factory.createVirtualWorld( + Dimension.valueOf(Settings.IMP.MAIN.DIMENSION), + authCoords.X, authCoords.Y, authCoords.Z, + (float) authCoords.YAW, (float) authCoords.PITCH + ); + + if (Settings.IMP.MAIN.LOAD_WORLD) { + try { + Path path = this.dataDirectory.resolve(Settings.IMP.MAIN.WORLD_FILE_PATH); + WorldFile file; + switch (Settings.IMP.MAIN.WORLD_FILE_TYPE) { + case "schematic": { + file = new SchematicFile(path); + break; + } + default: { + this.getLogger().error("Incorrect world file type."); + this.server.shutdown(); + return; + } + } + + Settings.MAIN.WORLD_COORDS coords = Settings.IMP.MAIN.WORLD_COORDS; + file.toWorld(this.factory, authWorld, coords.X, coords.Y, coords.Z); + } catch (IOException e) { + e.printStackTrace(); + } + } + + this.authServer = this.factory.createLimbo(authWorld); + + this.nicknameInvalid = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NICKNAME_INVALID); + + this.server.getEventManager().unregisterListeners(this); + this.server.getEventManager().register(this, new AuthListener(this.playerDao)); + + Executors.newScheduledThreadPool(1, task -> new Thread(task, "purge-cache")).scheduleAtFixedRate(() -> + this.checkCache(this.cachedAuthChecks, Settings.IMP.MAIN.PURGE_CACHE_MILLIS), + Settings.IMP.MAIN.PURGE_CACHE_MILLIS, + Settings.IMP.MAIN.PURGE_CACHE_MILLIS, + TimeUnit.MILLISECONDS + ); + } + + public void migrateDb(Dao playerDao) { + Set tables = new HashSet<>(); + Collections.addAll(tables, playerDao.getTableInfo().getFieldTypes()); + + String findSql; + switch (Settings.IMP.DATABASE.STORAGE_TYPE) { + case "h2": { + findSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + + playerDao.getTableInfo().getTableName() + "';"; + break; + } + case "postgresql": + case "mysql": { + findSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" + Settings.IMP.DATABASE.DATABASE + + "' AND TABLE_NAME = '" + playerDao.getTableInfo().getTableName() + "';"; + break; + } + default: { + this.getLogger().error("WRONG DATABASE TYPE."); + this.server.shutdown(); + return; + } + } + + try { + playerDao.queryRaw(findSql).forEach(e -> tables.removeIf(q -> q.getColumnName().equalsIgnoreCase(e[0]))); + + tables.forEach(t -> { + try { + String columnDefinition = t.getColumnDefinition(); + StringBuilder builder = new StringBuilder("ALTER TABLE `auth` ADD "); + List dummy = new ArrayList<>(); + if (columnDefinition == null) { + playerDao.getConnectionSource().getDatabaseType().appendColumnArg(t.getTableName(), builder, t, dummy, dummy, dummy, dummy); + } else { + playerDao.getConnectionSource().getDatabaseType().appendEscapedEntityName(builder, t.getColumnName()); + builder.append(" ").append(columnDefinition).append(" "); + } + + playerDao.executeRawNoArgs(builder.toString()); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void cacheAuthUser(Player player) { + String username = player.getUsername(); + this.cachedAuthChecks.remove(username); + this.cachedAuthChecks.put(username, new CachedUser(player.getRemoteAddress().getAddress(), System.currentTimeMillis())); + } + + public void removePlayerFromCache(Player player) { + this.cachedAuthChecks.remove(player.getUsername()); + } + + public boolean needAuth(Player player) { + String username = player.getUsername(); + + if (!this.cachedAuthChecks.containsKey(username)) { + return true; + } + + return !this.cachedAuthChecks.get(username).getInetAddress().equals(player.getRemoteAddress().getAddress()); + } + + public void authPlayer(Player player) { + String nickname = player.getUsername(); + if (!this.nicknameValidationPattern.matcher(nickname).matches()) { + player.disconnect(this.nicknameInvalid); + return; + } + + if (!Settings.IMP.MAIN.ONLINE_MODE_NEED_AUTH && player.isOnlineMode()) { + RegisteredPlayer registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, player.getUsername()); + + if (registeredPlayer == null || registeredPlayer.getHash().isEmpty()) { + this.factory.passLoginLimbo(player); + return; + } + } + + // Send player to auth virtual server. + try { + this.authServer.spawnPlayer(player, new AuthSessionHandler(this.playerDao, player, nickname)); + } catch (Throwable t) { + this.getLogger().error("Error", t); + } + } + + public boolean isPremium(String nickname) { + try { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(String.format(Settings.IMP.MAIN.ISPREMIUM_AUTH_URL, nickname))) + .build(); + HttpResponse response = this.client.send(request, HttpResponse.BodyHandlers.ofString()); + return response.statusCode() == 200; + } catch (IOException | InterruptedException e) { + this.getLogger().error("Unable to authenticate with Mojang", e); + return true; + } + } + + public Logger getLogger() { + return this.logger; + } + + private void checkCache(Map userMap, long time) { + userMap.entrySet().stream() + .filter(u -> u.getValue().getCheckTime() + time <= System.currentTimeMillis()) + .map(Map.Entry::getKey) + .forEach(userMap::remove); + } + + private static void setInstance(LimboAuth instance) { + LimboAuth.instance = instance; + } + + public static LimboAuth getInstance() { + return instance; + } + + private static class CachedUser { + + private final InetAddress inetAddress; + private final long checkTime; + + public CachedUser(InetAddress inetAddress, long checkTime) { + this.inetAddress = inetAddress; + this.checkTime = checkTime; + } + + public InetAddress getInetAddress() { + return this.inetAddress; + } + + public long getCheckTime() { + return this.checkTime; + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/Settings.java b/src/main/java/net/elytrium/limboauth/Settings.java new file mode 100644 index 0000000..9e59830 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/Settings.java @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package net.elytrium.limboauth; + +import java.io.File; +import net.elytrium.limboauth.config.Config; + +public class Settings extends Config { + + @Ignore + public static final Settings IMP = new Settings(); + + @Final + public String VERSION = BuildConstants.AUTH_VERSION; + + public String PREFIX = "LimboAuth &6>>&f"; + + @Create + public MAIN MAIN; + + public static class MAIN { + + public boolean ENABLE_BOSSBAR = true; + public boolean ONLINE_MODE_NEED_AUTH = true; + public boolean FORCE_OFFLINE_UUID = false; + @Comment({ + "Forcibly set player's UUID to the value from the database", + "If the player had the cracked account, and switched to the premium account, the cracked UUID will be used." + }) + public boolean SAVE_UUID = true; + public boolean ENABLE_TOTP = true; + public boolean TOTP_NEED_PASSWORD = true; + public boolean REGISTER_NEED_REPEAT_PASSWORD = true; + public boolean CHANGE_PASSWORD_NEED_OLD_PASSWORD = true; + @Comment({ + "If you want to migrate your database from another plugin, which is not using BCrypt", + "You can set an old hash algorithm to migrate from. Currently, only AUTHME is supported yet" + }) + public String MIGRATION_HASH = ""; + @Comment("Available dimensions: OVERWORLD, NETHER, THE_END") + public String DIMENSION = "THE_END"; + public long PURGE_CACHE_MILLIS = 3600000; + @Comment("QR Generator URL, set {data} placeholder") + public String QR_GENERATOR_URL = "https://api.qrserver.com/v1/create-qr-code/?data={data}&size=200x200&ecc=M&margin=30"; + public String TOTP_ISSUER = "LimboAuth by Elytrium"; + public int BCRYPT_COST = 10; + public int LOGIN_ATTEMPTS = 3; + public int IP_LIMIT_REGISTRATIONS = 3; + public int TOTP_RECOVERY_CODES_AMOUNT = 16; + @Comment("Time in milliseconds, when ip limit works, set to 0 for disable") + public long IP_LIMIT_VALID_TIME = 21600000; + @Comment({ + "Regex of allowed nicknames", + "^ means the start of the line, $ means the end of the line", + "[A-Za-z0-9_] is a character set of A-Z, a-z, 0-9 and _", + "{3,16} means that allowed length is from 3 to 16 chars" + }) + public String ALLO