diff options
31 files changed, 3404 insertions, 0 deletions
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 <http://www.gnu.org/licenses/>. @@ -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 @@ +<?xml version="1.0"?> +<!DOCTYPE module PUBLIC + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> + +<!-- + Checkstyle configuration that checks the Google coding conventions from Google Java Style + that can be found at https://google.github.io/styleguide/javaguide.html + Checkstyle is very configurable. Be sure to read the documentation at + http://checkstyle.org (or in your downloaded distribution). + To completely disable a check, just comment it out or delete it from the file. + To suppress certain violations please review suppression filters. + Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov. + --> + +<module name="Checker"> + <property name="charset" value="UTF-8"/> + + <property name="severity" value="warning"/> + + <property name="fileExtensions" value="java, properties, xml"/> + <!-- Excludes all 'module-info.java' files --> + <!-- See https://checkstyle.org/config_filefilters.html --> + <module name="BeforeExecutionExclusionFileFilter"> + <property name="fileNamePattern" value="module\-info\.java$"/> + </module> + <!-- https://checkstyle.org/config_filters.html#SuppressionFilter --> + <module name="SuppressionFilter"> + <property name="file" value="${configDirectory}/suppressions.xml"/> + </module> + + <!-- Checks for whitespace --> + <!-- See http://checkstyle.org/config_whitespace.html --> + <module name="FileTabCharacter"> + <property name="eachLine" value="true"/> + </module> + + <module name="LineLength"> + <property name="fileExtensions" value="java"/> + <property name="max" value="155"/> + <property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/> + </module> + + <module name="NewlineAtEndOfFile"/> + + <module name="TreeWalker"> + <module name="MissingOverride"/> + <module name="FinalClass"/> + <module name="RedundantImport"/> + <module name="UnusedImports"/> + <module name="RequireThis"> + <property name="validateOnlyOverlapping" value="false"/> + </module> + + <module name="OuterTypeFilename"/> + <module name="IllegalTokenText"> + <property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/> + <property name="format" + value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/> + <property name="message" + value="Consider using special escape sequence instead of octal value or Unicode escaped value."/> + </module> + <module name="AvoidEscapedUnicodeCharacters"> + <property name="allowEscapesForControlCharacters" value="true"/> + <property name="allowByTailComment" value="true"/> + <property name="allowNonPrintableEscapes" value="true"/> + </module> + <module name="AvoidStarImport"/> + <module name="OneTopLevelClass"/> + <module name="NoLineWrap"> + <property name="tokens" value="PACKAGE_DEF, IMPORT, STATIC_IMPORT"/> + </module> + <module name="EmptyBlock"> + <property name="option" value="TEXT"/> + <property name="tokens" + value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/> + </module> + <module name="NeedBraces"> + <property name="tokens" + value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/> + </module> + <module name="LeftCurly"> + <property name="tokens" + value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_CONSTANT_DEF, ENUM_DEF, + INTERFACE_DEF, LAMBDA, LITERAL_CASE, LITERAL_CATCH, LITERAL_DEFAULT, + LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, + LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, METHOD_DEF, + OBJBLOCK, STATIC_INIT, RECORD_DEF, COMPACT_CTOR_DEF"/> + </module> + <module name="RightCurly"> + <property name="id" value="RightCurlySame"/> + <property name="tokens" + value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, + LITERAL_DO"/> + </module> + <module name="RightCurly"> + <property name="id" value="RightCurlyAlone"/> + <property name="option" value="alone"/> + <property name="tokens" + value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT, + INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF, INTERFACE_DEF, RECORD_DEF, + COMPACT_CTOR_DEF"/> + </module> + <module name="SuppressionXpathSingleFilter"> + <!-- suppresion is required till https://github.com/checkstyle/checkstyle/issues/7541 --> + <property name="id" value="RightCurlyAlone"/> + <property name="query" value="//RCURLY[parent::SLIST[count(./*)=1] + or preceding-sibling::*[last()][self::LCURLY]]"/> + </module> + <module name="WhitespaceAfter"> + <property name="tokens" + value="COMMA, SEMI, TYPECAST, LITERAL_IF, LITERAL_ELSE, + LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, DO_WHILE"/> + </module> + <module name="WhitespaceAround"> + <property name="allowEmptyConstructors" value="true"/> + <property name="allowEmptyLambdas" value="true"/> + <property name="allowEmptyMethods" value="true"/> + <property name="allowEmptyTypes" value="true"/> + <property name="allowEmptyLoops" value="true"/> + <property name="ignoreEnhancedForColon" value="false"/> + <property name="tokens" + value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, + BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, DO_WHILE, EQUAL, GE, GT, LAMBDA, LAND, + LCURLY, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, + LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SWITCH, LITERAL_SYNCHRONIZED, + LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, + NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, + SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/> + <message key="ws.notFollowed" + value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/> + <message key="ws.notPreceded" + value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/> + </module> + <module name="OneStatementPerLine"/> + <module name="MultipleVariableDeclarations"/> + <module name="ArrayTypeStyle"/> + <module name="MissingSwitchDefault"/> + <module name="FallThrough"/> + <module name="UpperEll"/> + <module name="ModifierOrder"/> + <module name="EmptyLineSeparator"> + <property name="tokens" + value="PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, + STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF, + COMPACT_CTOR_DEF"/> + <property name="allowNoEmptyLineBetweenFields" value="true"/> + </module> + <module name="SeparatorWrap"> + <property name="id" value="SeparatorWrapDot"/> + <property name="tokens" value="DOT"/> + <property name="option" value="nl"/> + </module> + <module name="SeparatorWrap"> + <property name="id" value="SeparatorWrapComma"/> + <property name="tokens" value="COMMA"/> + <property name="option" value="EOL"/> + </module> + <module name="SeparatorWrap"> + <!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/259 --> + <property name="id" value="SeparatorWrapEllipsis"/> + <property name="tokens" value="ELLIPSIS"/> + <property name="option" value="EOL"/> + </module> + <module name="SeparatorWrap"> + <!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/258 --> + <property name="id" value="SeparatorWrapArrayDeclarator"/> + <property name="tokens" value="ARRAY_DECLARATOR"/> + <property name="option" value="EOL"/> + </module> + <module name="SeparatorWrap"> + <property name="id" value="SeparatorWrapMethodRef"/> + <property name="tokens" value="METHOD_REF"/> + <property name="option" value="nl"/> + </module> + <module name="PackageName"> + <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/> + <message key="name.invalidPattern" + value="Package name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="TypeName"> + <property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, + ANNOTATION_DEF, RECORD_DEF"/> + <message key="name.invalidPattern" + value="Type name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="MemberName"> + <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/> + <message key="name.invalidPattern" + value="Member name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="ParameterName"> + <property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/> + <message key="name.invalidPattern" + value="Parameter name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="LambdaParameterName"> + <property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/> + <message key="name.invalidPattern" + value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="CatchParameterName"> + <property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/> + <message key="name.invalidPattern" + value="Catch parameter name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="LocalVariableName"> + <property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/> + <message key="name.invalidPattern" + value="Local variable name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="PatternVariableName"> + <property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/> + <message key="name.invalidPattern" + value="Pattern variable name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="ClassTypeParameterName"> + <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/> + <message key="name.invalidPattern" + value="Class type name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="RecordComponentName"> + <property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/> + <message key="name.invalidPattern" + value="Record component name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="RecordTypeParameterName"> + <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/> + <message key="name.invalidPattern" + value="Record type name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="MethodTypeParameterName"> + <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/> + <message key="name.invalidPattern" + value="Method type name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="InterfaceTypeParameterName"> + <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/> + <message key="name.invalidPattern" + value="Interface type name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="NoFinalizer"/> + <module name="GenericWhitespace"> + <message key="ws.followed" + value="GenericWhitespace ''{0}'' is followed by whitespace."/> + <message key="ws.preceded" + value="GenericWhitespace ''{0}'' is preceded with whitespace."/> + <message key="ws.illegalFollow" + value="GenericWhitespace ''{0}'' should followed by whitespace."/> + <message key="ws.notPreceded" + value="GenericWhitespace ''{0}'' is not preceded with whitespace."/> + </module> + <module name="Indentation"> + <property name="basicOffset" value="2"/> + <property name="braceAdjustment" value="2"/> + <property name="caseIndent" value="2"/> + <property name="throwsIndent" value="4"/> + <property name="lineWrappingIndentation" value="4"/> + <property name="arrayInitIndent" value="2"/> + </module> + <module name="AbbreviationAsWordInName"> + <property name="ignoreFinal" value="false"/> + <property name="allowedAbbreviationLength" value="2"/> + <property name="tokens" + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF, ANNOTATION_FIELD_DEF, + PARAMETER_DEF, VARIABLE_DEF, METHOD_DEF, PATTERN_VARIABLE_DEF, RECORD_DEF, + RECORD_COMPONENT_DEF"/> + </module> + <module name="NoWhitespaceBeforeCaseDefaultColon"/> + <module name="OverloadMethodsDeclarationOrder"/> + <module name="VariableDeclarationUsageDistance"/> + <module name="CustomImportOrder"> + <property name="sortImportsInGroupAlphabetically" value="true"/> + <property name="separateLineBetweenGroups" value="true"/> + <property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/> + <property name="tokens" value="IMPORT, STATIC_IMPORT, PACKAGE_DEF"/> + </module> + <module name="MethodParamPad"> + <property name="tokens" + value="CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF, + SUPER_CTOR_CALL, ENUM_CONSTANT_DEF, RECORD_DEF"/> + </module> + <module name="NoWhitespaceBefore"> + <property name="tokens" + value="COMMA, SEMI, POST_INC, POST_DEC, DOT, + LABELED_STAT, METHOD_REF"/> + <property name="allowLineBreaks" value="true"/> + </module> + <module name="ParenPad"> + <property name="tokens" + value="ANNOTATION, ANNOTATION_FIELD_DEF, CTOR_CALL, CTOR_DEF, DOT, ENUM_CONSTANT_DEF, + EXPR, LITERAL_CATCH, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_NEW, + LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_WHILE, METHOD_CALL, + METHOD_DEF, QUESTION, RESOURCE_SPECIFICATION, SUPER_CTOR_CALL, LAMBDA, + RECORD_DEF"/> + </module> + <module name="OperatorWrap"> + <property name="option" value="NL"/> + <property name="tokens" + value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, + LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF, + TYPE_EXTENSION_AND "/> + </module> + <module name="AnnotationLocation"> + <property name="id" value="AnnotationLocationMostCases"/> + <property name="tokens" + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, + RECORD_DEF, COMPACT_CTOR_DEF"/> + </module> + <module name="AnnotationLocation"> + <property name="id" value="AnnotationLocationVariables"/> + <property name="tokens" value="VARIABLE_DEF"/> + <property name="allowSamelineMultipleAnnotations" value="true"/> + </module> + <module name="NonEmptyAtclauseDescription"/> + <module name="InvalidJavadocPosition"/> + <module name="JavadocTagContinuationIndentation"/> + <module name="SummaryJavadoc"> + <property name="forbiddenSummaryFragments" + value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/> + </module> + <module name="JavadocParagraph"/> + <module name="RequireEmptyLineBeforeBlockTagGroup"/> + <module name="AtclauseOrder"> + <property name="tagOrder" value="@param, @return, @throws, @deprecated"/> + <property name="target" + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/> + </module> + <module name="JavadocMethod"> + <property name="accessModifiers" value="public"/> + <property name="allowMissingParamTags" value="true"/> + <property name="allowMissingReturnTag" value="true"/> + <property name="allowedAnnotations" value="Override, Test"/> + <property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, COMPACT_CTOR_DEF"/> + </module> + <module name="MissingJavadocMethod"> + <property name="scope" value="public"/> + <property name="minLineCount" value="2"/> + <property name="allowedAnnotations" value="Override, Test"/> + <property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, + COMPACT_CTOR_DEF"/> + </module> + <module name="MissingJavadocType"> + <property name="scope" value="protected"/> + <property name="tokens" + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, + RECORD_DEF, ANNOTATION_DEF"/> + <property name="excludeScope" value="nothing"/> + </module> + <module name="MethodName"> + <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/> + <message key="name.invalidPattern" + value="Method name ''{0}'' must match pattern ''{1}''."/> + </module> + <module name="SingleLineJavadoc"/> + <module name="EmptyCatchBlock"> + <property name="exceptionVariableName" value="expected"/> + </module> + <module name="CommentsIndentation"> + <property name="tokens" value="SINGLE_LINE_COMMENT, BLOCK_COMMENT_BEGIN"/> + </module> + <!-- https://checkstyle.org/config_filters.html#SuppressionXpathFilter --> + <module name="SuppressionXpathFilter"> + <property name="file" value="${org.checkstyle.google.suppressionxpathfilter.config}" + default="checkstyle-xpath-suppressions.xml"/> + <property name="optional" value="true"/> + </module> + </module> +</module> 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 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE suppressions PUBLIC + "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" + "http://checkstyle.org/dtds/suppressions_1_2.dtd"> + +<suppressions> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*" checks="SummaryJavadoc"/> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*" checks="MissingJavadocType"/> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*" checks="MissingJavadocMethod"/> + + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*[\\/]Settings.java" checks="TypeName"/> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*[\\/]Settings.java" checks="LineLength"/> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*[\\/]Settings.java" checks="MemberName"/> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*[\\/]Settings.java" checks="RequireThis"/> + <suppress files=".*[\\/]net[\\/]elytrium[\\/].*[\\/]Settings.java" checks="AbbreviationAsWordInName"/> +</suppressions> 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 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<FindBugsFilter> + <Match> + <Bug pattern="EI_EXPOSE_REP2"/> + </Match> +</FindBugsFilter> diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..7454180 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar 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 @@ -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 <http://www.gnu.org/licenses/>. + */ + +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<RegisteredPlayer, String> playerDao; + private Limbo authServer; + private Map<String, CachedUser> 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<RegisteredPlayer, String> playerDao) { + Set<FieldType> 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<String> 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<String> 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<String, CachedUser> 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 <http://www.gnu.org/licenses/>. + */ + +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 ALLOWED_NICKNAME_REGEX = "^[A-Za-z0-9_]{3,16}$"; + + public boolean LOAD_WORLD = false; + @Comment("World file type: schematic") + public String WORLD_FILE_TYPE = "schematic"; + public String WORLD_FILE_PATH = "world.schematic"; + @Comment({ + "Custom isPremium URL", + "You can use Mojang one's API (set by default)", + "Or CloudFlare one's: https://api.ashcon.app/mojang/v1/user/%s", + "Or use this code to make your own API: https://blog.cloudflare.com/minecraft-api-with-workers-coffeescript/", + "Or implement your own API, it should just respond with HTTP code 200 only if the player is premium" + }) + public String ISPREMIUM_AUTH_URL = "https://api.mojang.com/users/profiles/minecraft/%s"; + + @Create + public Settings.MAIN.WORLD_COORDS WORLD_COORDS; + + public static class WORLD_COORDS { + + public int X = 0; + public int Y = 0; + public int Z = 0; + } + + @Create + public MAIN.STRINGS STRINGS; + + //@Comment("Leave empty to disable.") + public static class STRINGS { + + public String RELOAD = "{PRFX} &aReloaded successfully!"; + public String RELOAD_FAILED = "{PRFX} &cReload failed, check console for details."; + public String ERROR_OCCURRED = "{PRFX} &cAn internal error has occurred!"; + + public String NOT_PLAYER = "{PRFX} &cСonsole is not allowed to execute this command!"; + public String NOT_REGISTERED = "{PRFX} &cYou are not registered!"; + public String WRONG_PASSWORD = "{PRFX} &cPassword is wrong!"; + + public String NICKNAME_INVALID = "{NL}{NL}&cYour nickname contains forbidden characters. Please, change your nickname!"; + @Comment("6 hours by default in ip-limit-valid-time") + public String IP_LIMIT = "{PRFX} &cYour IP has reached max registered accounts. If this is an error, restart your router, or wait about 6 hours."; + public String WRONG_NICKNAME_CASE = "{NL}{NL}&cThe case of your nickname is wrong. Nickname is CaSe SeNsItIvE."; + + public String LOGIN = "{PRFX} Please, login using &6/login &6<password>. You have &6{0} &cattempts."; + public String LOGIN_SUCCESS = "{PRFX} &aSuccessfully logged in!"; + public String LOGIN_WRONG_PASSWORD = "{PRFX} &cYou've entered the wrong password. You have &6{0} &cattempts left."; + public String LOGIN_TITLE = ""; + public String LOGIN_SUBTITLE = ""; + public String LOGIN_SUCCESS_TITLE = ""; + public String LOGIN_SUCCESS_SUBTITLE = ""; + + @Comment("Or if register-need-repeat-password set to false remove the \"<repeat password>\" part.") + public String REGISTER = "{PRFX} Please, register using &6/register <password> <repeat password>"; + public String REGISTER_TITLE = ""; + public String REGISTER_SUBTITLE = ""; + public String DIFFERENT_PASSWORDS = "{PRFX} The entered passwords differ from each other."; + public String KICK_PASSWORD_WRONG = "{NL}{NL}&cYou've entered the wrong password numerous times!"; + + public String UNREGISTER_SUCCESSFUL = "{PRFX}{NL}{NL}&aSuccessfully unregistered!"; + public String UNREGISTER_USAGE = "{PRFX} Usage: &6/unregister <current password> confirm"; + + public String FORCE_UNREGISTER_SUCCESSFUL = "{PRFX} &a{0} successfully unregistered!"; + public String FORCE_UNREGISTER_SUCCESSFUL_PLAYER = "{PRFX}{NL}{NL}&aYou have been unregistered by administrator!"; + public String FORCE_UNREGISTER_NOT_SUCCESSFUL = "{PRFX} &cUnable to unregister {0}. Most likely this player has never been on this server."; + public String FORCE_UNREGISTER_USAGE = "{PRFX} Usage: &6/forceunregister <nickname>"; + + public String CHANGE_PASSWORD_SUCCESSFUL = "{PRFX} &aSuccessfully changed password!"; + @Comment("Or if change-password-need-old-pass set to false remove the \"<old password>\" part.") + public String CHANGE_PASSWORD_USAGE = "{PRFX} Usage: &6/changepassword <old password> <new password>"; + + public String TOTP = "{PRFX} Please, enter your 2FA key using &6/2fa <key>"; + public String TOTP_SUCCESSFUL = "{PRFX} &aSuccessfully enabled 2FA!"; + public String TOTP_DISABLED = "{PRFX} &aSuccessfully disabled 2FA!"; + @Comment("Or if totp-need-pass set to false remove the \"<current password>\" part.") + public String TOTP_USAGE = "{PRFX} Usage: &6/2fa enable <current password>&f or &6/2fa disable <totp key>&f."; + public String TOTP_WRONG = "{PRFX} &cWrong 2FA key!"; + public String TOTP_ALREADY_ENABLED = "{PRFX} &c2FA is already enabled. Disable it using &6/2fa disable <key>&c."; + public String TOTP_QR = "{PRFX} Click here to open 2FA QR code in browser."; + public String TOTP_TOKEN = "{PRFX} &aYour 2FA token &7(Click to copy)&a: &6{0}"; + public String TOTP_RECOVERY = "{PRFX} &aYour recovery codes &7(Click to copy)&a: &6{0}"; + + public String DESTROY_SESSION_SUCCESSFUL = "{PRFX} &eYour session is now destroyed, you'll need to log in again after reconnecting."; + } + + @Create + public MAIN.AUTH_COORDS AUTH_COORDS; + + public static class AUTH_COORDS { + + public double X = 0; + public double Y = 0; + public double Z = 0; + public double YAW = 0; + public double PITCH = 0; + } + } + + @Create + public DATABASE DATABASE; + + @Comment("Database settings") + public static class DATABASE { + + @Comment("Database type: mysql, postgresql or h2.") + public String STORAGE_TYPE = "h2"; + + @Comment("Settings for Network-based database (like MySQL, PostgreSQL): ") + public String HOSTNAME = "127.0.0.1:3306"; + public String USER = "user"; + public String PASSWORD = "password"; + public String DATABASE = "limboauth"; + public String CONNECTION_PARAMETERS = "?autoReconnect=true&initialTimeout=1&useSSL=false"; + } + + public void reload(File file) { + if (this.load(file, this.PREFIX)) { + this.save(file); + } else { + this.save(file); + this.load(file, this.PREFIX); + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java b/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java new file mode 100644 index 0000000..2373938 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java @@ -0,0 +1,101 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import java.sql.SQLException; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class ChangePasswordCommand implements SimpleCommand { + + private final Dao<RegisteredPlayer, String> playerDao; + + private final Component notPlayer; + private final boolean needOldPass; + private final Component notRegistered; + private final Component wrongPassword; + private final Component successful; + private final Component errorOccurred; + private final Component usage; + + public ChangePasswordCommand(Dao<RegisteredPlayer, String> playerDao) { + this.playerDao = playerDao; + + this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); + this.needOldPass = Settings.IMP.MAIN.CHANGE_PASSWORD_NEED_OLD_PASSWORD; + this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); + this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); + this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.CHANGE_PASSWORD_SUCCESSFUL); + this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); + this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.CHANGE_PASSWORD_USAGE); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (!(source instanceof Player)) { + source.sendMessage(this.notPlayer); + return; + } + + if (this.needOldPass ? args.length == 2 : args.length == 1) { + if (this.needOldPass) { + RegisteredPlayer player = AuthSessionHandler.fetchInfo(this.playerDao, ((Player) source).getUsername()); + if (player == null) { + source.sendMessage(this.notRegistered); + return; + } else if (!AuthSessionHandler.checkPassword(args[0], player, this.playerDao)) { + source.sendMessage(this.wrongPassword); + return; + } + } + + try { + UpdateBuilder<RegisteredPlayer, String> updateBuilder = this.playerDao.updateBuilder(); + updateBuilder.where().eq("nickname", ((Player) source).getUsername()); + updateBuilder.updateColumnValue("hash", AuthSessionHandler.genHash(this.needOldPass ? args[1] : args[0])); + updateBuilder.update(); + + source.sendMessage(this.successful); + } catch (SQLException e) { + source.sendMessage(this.errorOccurred); + e.printStackTrace(); + } + + return; + } + + source.sendMessage(this.usage); + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().getPermissionValue("limboauth.commands.changepassword") != Tristate.FALSE; + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java b/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java new file mode 100644 index 0000000..27dff72 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java @@ -0,0 +1,60 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class DestroySessionCommand implements SimpleCommand { + + private final LimboAuth plugin; + + private final Component notPlayer; + private final Component successful; + + public DestroySessionCommand(LimboAuth plugin) { + this.plugin = plugin; + + this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); + this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.DESTROY_SESSION_SUCCESSFUL); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + + if (!(source instanceof Player)) { + source.sendMessage(this.notPlayer); + return; + } + + this.plugin.removePlayerFromCache((Player) source); + source.sendMessage(this.successful); + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().getPermissionValue("limboauth.commands.destroysession") != Tristate.FALSE; + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java b/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java new file mode 100644 index 0000000..d45eae9 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java @@ -0,0 +1,106 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.google.common.collect.ImmutableList; +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class ForceUnregisterCommand implements SimpleCommand { + + private final LimboAuth plugin; + private final ProxyServer server; + private final Dao<RegisteredPlayer, String> playerDao; + + private final Component successfulPlayer; + private final String successful; + private final String notSuccessful; + private final Component usage; + + public ForceUnregisterCommand(LimboAuth plugin, ProxyServer server, Dao<RegisteredPlayer, String> playerDao) { + this.plugin = plugin; + this.server = server; + this.playerDao = playerDao; + + this.successfulPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_SUCCESSFUL_PLAYER); + this.successful = Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_SUCCESSFUL; + this.notSuccessful = Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_NOT_SUCCESSFUL; + this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_USAGE); + } + + @Override + public List<String> suggest(SimpleCommand.Invocation invocation) { + String[] args = invocation.arguments(); + + if (args.length == 0) { + return this.server.getAllPlayers().stream() + .map(Player::getUsername) + .collect(Collectors.toList()); + } else if (args.length == 1) { + return this.server.getAllPlayers().stream() + .map(Player::getUsername) + .filter(str -> str.regionMatches(true, 0, args[0], 0, args[0].length())) + .collect(Collectors.toList()); + } + + return ImmutableList.of(); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (args.length == 1) { + String playerNick = args[0]; + try { + this.playerDao.deleteById(playerNick.toLowerCase(Locale.ROOT)); + this.server.getPlayer(playerNick).ifPresent(player -> { + this.plugin.removePlayerFromCache(player); + player.disconnect(this.successfulPlayer); + }); + source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(MessageFormat.format(this.successful, playerNick))); + } catch (SQLException e) { + source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(MessageFormat.format(this.notSuccessful, playerNick))); + e.printStackTrace(); + } + + return; + } + + source.sendMessage(this.usage); + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().hasPermission("limboauth.admin.forceunregister"); + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java b/src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java new file mode 100644 index 0000000..611b1c3 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java @@ -0,0 +1,95 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.google.common.collect.ImmutableList; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class LimboAuthCommand implements SimpleCommand { + + @Override + public List<String> suggest(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (args.length == 0) { + return this.getSubCommands() + .filter(cmd -> source.hasPermission("limboauth.admin." + cmd)) + .collect(Collectors.toList()); + } else if (args.length == 1) { + return this.getSubCommands() + .filter(cmd -> source.hasPermission("limboauth.admin." + cmd)) + .filter(str -> str.regionMatches(true, 0, args[0], 0, args[0].length())) + .collect(Collectors.toList()); + } + + return ImmutableList.of(); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (args.length == 1) { + if (args[0].equalsIgnoreCase("reload") && source.hasPermission("limboauth.admin.reload")) { + try { + LimboAuth.getInstance().reload(); + source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.RELOAD)); + } catch (Exception e) { + source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.RELOAD_FAILED)); + e.printStackTrace(); + } + } else { + this.showHelp(source); + } + + return; + } + + this.showHelp(source); + } + + private void showHelp(CommandSource source) { + source.sendMessage(Component.text("§eThis server is using LimboAuth and LimboAPI")); + source.sendMessage(Component.text("§e(c) 2021 Elytrium")); + source.sendMessage(Component.text("§ahttps://ely.su/github/")); + source.sendMessage(Component.text("§r")); + source.sendMessage(Component.text("§fAvailable subcommands:")); + // Java moment + this.getSubCommands() + .filter(cmd -> source.hasPermission("limboauth.admin." + cmd)) + .forEach(cmd -> { + if (cmd.equals("reload")) { + source.sendMessage(Component.text(" §a/limboauth reload §8- §eReload config")); + } + }); + } + + private Stream<String> getSubCommands() { + return Stream.of("reload"); + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/TotpCommand.java b/src/main/java/net/elytrium/limboauth/command/TotpCommand.java new file mode 100644 index 0000000..d51da7d --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/TotpCommand.java @@ -0,0 +1,204 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import dev.samstevens.totp.qr.QrData; +import dev.samstevens.totp.recovery.RecoveryCodeGenerator; +import dev.samstevens.totp.secret.DefaultSecretGenerator; +import dev.samstevens.totp.secret.SecretGenerator; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.text.MessageFormat; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class TotpCommand implements SimpleCommand { + + private final SecretGenerator secretGenerator = new DefaultSecretGenerator(); + private final RecoveryCodeGenerator codesGenerator = new RecoveryCodeGenerator(); + private final Dao<RegisteredPlayer, String> playerDao; + + private final Component notPlayer; + private final Component usage; + private final boolean needPassword; + private final Component notRegistered; + private final Component wrongPassword; + private final Component alreadyEnabled; + private final Component errorOccurred; + private final Component successful; + private final String issuer; + private final String qrGeneratorUrl; + private final Component qr; + private final String token; + private final int recoveryCodesAmount; + private final String recovery; + private final Component disabled; + private final Component wrong; + + public TotpCommand(Dao<RegisteredPlayer, String> playerDao) { + this.playerDao = playerDao; + + this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); + this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_USAGE); + this.needPassword = Settings.IMP.MAIN.TOTP_NEED_PASSWORD; + this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); + this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); + this.alreadyEnabled = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_ALREADY_ENABLED); + this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); + this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_SUCCESSFUL); + this.issuer = Settings.IMP.MAIN.TOTP_ISSUER; + this.qrGeneratorUrl = Settings.IMP.MAIN.QR_GENERATOR_URL; + this.qr = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_QR); + this.token = Settings.IMP.MAIN.STRINGS.TOTP_TOKEN; + this.recoveryCodesAmount = Settings.IMP.MAIN.TOTP_RECOVERY_CODES_AMOUNT; + this.recovery = Settings.IMP.MAIN.STRINGS.TOTP_RECOVERY; + this.disabled = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_DISABLED); + this.wrong = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_WRONG); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (!(source instanceof Player)) { + source.sendMessage(this.notPlayer); + return; + } + + if (args.length == 0) { + source.sendMessage(this.usage); + } else { + String username = ((Player) source).getUsername(); + + RegisteredPlayer playerInfo; + UpdateBuilder<RegisteredPlayer, String> updateBuilder; + switch (args[0]) { + case "enable": { + if (this.needPassword ? args.length == 2 : args.length == 1) { + playerInfo = AuthSessionHandler.fetchInfo(this.playerDao, username); + + if (playerInfo == null) { + source.sendMessage(this.notRegistered); + return; + } else if (this.needPassword && !AuthSessionHandler.checkPassword(args[1], playerInfo, this.playerDao)) { + source.sendMessage(this.wrongPassword); + return; + } + + if (!playerInfo.getTotpToken().isEmpty()) { + source.sendMessage(this.alreadyEnabled); + return; + } + + String secret = this.secretGenerator.generate(); + + try { + updateBuilder = this.playerDao.updateBuilder(); + updateBuilder.where().eq("nickname", username); + updateBuilder.updateColumnValue("totpToken", secret); + updateBuilder.update(); + } catch (SQLException e) { + source.sendMessage(this.errorOccurred); + e.printStackTrace(); + } + + source.sendMessage(this.successful); + + QrData data = new QrData.Builder() + .label(username) + .secret(secret) + .issuer(this.issuer) + .build(); + + String qrUrl = this.qrGeneratorUrl.replace("{data}", URLEncoder.encode(data.getUri(), StandardCharsets.UTF_8)); + + source.sendMessage(this.qr.clickEvent(ClickEvent.openUrl(qrUrl))); + + source.sendMessage( + LegacyComponentSerializer.legacyAmpersand().deserialize( + MessageFormat.format(this.token, secret) + ).clickEvent(ClickEvent.copyToClipboard(secret)) + ); + + String codes = String.join(", ", this.codesGenerator.generateCodes(this.recoveryCodesAmount)); + + source.sendMessage( + LegacyComponentSerializer.legacyAmpersand().deserialize( + MessageFormat.format(this.recovery, codes) + ).clickEvent(ClickEvent.copyToClipboard(codes)) + ); + } else { + source.sendMessage(this.usage); + } + break; + } + case "disable": { + if (args.length != 2) { + source.sendMessage(this.usage); + return; + } + + playerInfo = AuthSessionHandler.fetchInfo(this.playerDao, username); + + if (playerInfo == null) { + source.sendMessage(this.notRegistered); + return; + } + + if (AuthSessionHandler.getVerifier().isValidCode(playerInfo.getTotpToken(), args[1])) { + try { + updateBuilder = this.playerDao.updateBuilder(); + updateBuilder.where().eq("nickname", username); + updateBuilder.updateColumnValue("totpToken", ""); + updateBuilder.update(); + + source.sendMessage(this.disabled); + } catch (SQLException e) { + source.sendMessage(this.errorOccurred); + e.printStackTrace(); + } + } else { + source.sendMessage(this.wrong); + } + break; + } + default: { + source.sendMessage(this.usage); + break; + } + } + } + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().getPermissionValue("limboauth.commands.totp") != Tristate.FALSE; + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java b/src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java new file mode 100644 index 0000000..aeab6ec --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java @@ -0,0 +1,97 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import java.sql.SQLException; +import java.util.Locale; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class UnregisterCommand implements SimpleCommand { + + private final LimboAuth plugin; + private final Dao<RegisteredPlayer, String> playerDao; + + private final Component notPlayer; + private final Component notRegistered; + private final Component successful; + private final Component errorOccurred; + private final Component wrongPassword; + private final Component usage; + + public UnregisterCommand(LimboAuth plugin, Dao<RegisteredPlayer, String> playerDao) { + this.plugin = plugin; + this.playerDao = playerDao; + + this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); + this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); + this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.UNREGISTER_SUCCESSFUL); + this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); + this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); + this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.UNREGISTER_USAGE); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (!(source instanceof Player)) { + source.sendMessage(this.notPlayer); + return; + } + + if (args.length == 2) { + if (args[1].equalsIgnoreCase("confirm")) { + RegisteredPlayer player = AuthSessionHandler.fetchInfo(this.playerDao, ((Player) source).getUsername()); + if (player == null) { + source.sendMessage(this.notRegistered); + } else if (AuthSessionHandler.checkPassword(args[0], player, this.playerDao)) { + try { + this.playerDao.deleteById(((Player) source).getUsername().toLowerCase(Locale.ROOT)); + this.plugin.removePlayerFromCache((Player) source); + ((Player) source).disconnect(this.successful); + } catch (SQLException e) { + source.sendMessage(this.errorOccurred); + e.printStackTrace(); + } + } else { + source.sendMessage(this.wrongPassword); + } + + return; + } + } + + source.sendMessage(this.usage); + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().getPermissionValue("limboauth.commands.unregister") != Tristate.FALSE; + } +} diff --git a/src/main/java/net/elytrium/limboauth/config/Config.java b/src/main/java/net/elytrium/limboauth/config/Config.java new file mode 100644 index 0000000..ed5b007 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/config/Config.java @@ -0,0 +1,392 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import net.elytrium.limboauth.LimboAuth; +import org.slf4j.Logger; +import org.yaml.snakeyaml.Yaml; + +public class Config { + + private static final Logger LOGGER = LimboAuth.getInstance().getLogger(); + private String oldPrefix = ""; + private String currentPrefix = ""; + + /** + * Set the value of a specific node. Probably throws some error if you supply non-existing keys or invalid values. + * + * @param key config node + * @param value value + */ + private void set(String key, Object value, Class<?> root) { + String[] split = key.split("\\."); + Object instance = this.getInstance(split, root); + if (instance != null) { + Field field = this.getField(split, instance); + if (field != null) { + try { + if (field.getAnnotation(Final.class) != null) { + return; + } + if (field.getType() == String.class && !(value instanceof String)) { + value = value + ""; + } + field.set(instance, value); + return; + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + LOGGER.debug("Failed to set config option: " + key + ": " + value + " | " + instance + " | " + root.getSimpleName() + ".yml"); + } + + @SuppressWarnings("unchecked") + public void set(Map<String, Object> input, String oldPath) { + for (Map.Entry<String, Object> entry : input.entrySet()) { + String key = oldPath + (oldPath.isEmpty() ? "" : ".") + entry.getKey(); + Object value = entry.getValue(); + + if (value instanceof Map) { + this.set((Map<String, Object>) value, key); + } else if (value instanceof String) { + if (key.equalsIgnoreCase("prefix") && !this.currentPrefix.equals(value)) { + this.currentPrefix = (String) value; + } + + this.set(key, ((String) value).replace("{NL}", "\n").replace("{PRFX}", this.currentPrefix), this.getClass()); + } else { + this.set(key, value, this.getClass()); + } + } + } + + public boolean load(File file, String prefix) { + this.oldPrefix = this.currentPrefix.isEmpty() ? prefix : this.currentPrefix; + this.currentPrefix = prefix; + if (!file.exists()) { + return false; + } + + try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) { + this.set(new Yaml().load(reader), ""); + } catch (IOException e) { + LOGGER.warn("Unable to load config ", e); + return false; + } + + return true; + } + + /** + * Indicates that a field should be instantiated / created. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD}) + public @interface Create { + + } + + /** + * Indicates that a field cannot be modified. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD}) + public @interface Final { + + } + + /** + * Creates a comment. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + public @interface Comment { + + String[] value(); + } + + /** + * Any field or class with is not part of the config. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + public @interface Ignore { + + } + + private String toYamlString(Object value, String spacing, String fieldName) { + if (value instanceof List) { + Collection<?> listValue = (Collection<?>) value; + if (listValue.isEmpty()) { + return "[]"; + } + StringBuilder m = new StringBuilder(); + for (Object obj : listValue) { + m.append(System.lineSeparator()).append(spacing).append("- ").append(this.toYamlString(obj, spacing, fieldName)); + } + + return m.toString(); + } + + if (value instanceof String) { + String stringValue = (String) value; + if (stringValue.isEmpty()) { + return "\"\""; + } + + String quoted = "\"" + stringValue + "\""; + if (fieldName.equalsIgnoreCase("prefix")) { + return quoted; + } else { + return quoted.replace("\n", "{NL}").replace(this.currentPrefix.equals(this.oldPrefix) ? this.oldPrefix : this.currentPrefix, "{PRFX}"); + } + } + + return value != null ? value.toString() : "null"; + } + + /** + * Set all values in the file (load first to avoid overwriting). + */ + @SuppressWarnings("ResultOfMethodCallIgnored") + @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") + public void save(File file) { + try { + if (!file.exists()) { + File parent = file.getParentFile(); + if (parent != null) { + file.getParentFile().mkdirs(); + } + file.createNewFile(); + } + + PrintWriter writer = new PrintWriter(file, StandardCharsets.UTF_8); + Object instance = this; + this.save(writer, this.getClass(), instance, 0); + writer.close(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + + private void save(PrintWriter writer, Class<?> clazz, final Object instance, int indent) { + try { + String lineSeparator = System.lineSeparator(); + String spacing = this.repeat(" ", indent); + + for (Field field : clazz.getFields()) { + if (field.getAnnotation(Ignore.class) != null) { + continue; + } + Class<?> current = field.getType(); + if (field.getAnnotation(Ignore.class) != null) { + continue; + } + + Comment comment = field.getAnnotation(Comment.class); + if (comment != null) { + for (String commentLine : comment.value()) { + writer.write(spacing + "# " + commentLine + lineSeparator); + } + } + + Create create = field.getAnnotation(Create.class); + if (create != null) { + Object value = field.get(instance); + this.setAccessible(field); + if (indent == 0) { + writer.write(lineSeparator); + } + comment = current.getAnnotation(Comment.class); + if (comment != null) { + for (String commentLine : comment.value()) { + writer.write(spacing + "# " + commentLine + lineSeparator); + } + } + writer.write(spacing + this.toNodeName(current.getSimpleName()) + ":" + lineSeparator); + if (value == null) { + field.set(instance, value = current.getDeclaredConstructor().newInstance()); + } + this.save(writer, current, value, indent + 2); + } else { + String value = this.toYamlString(field.get(instance), spacing, field.getName()); + writer.write(spacing + this.toNodeName(field.getName() + ": ") + value + lineSeparator); + } + } + } catch (Throwable e) { + e.printStackTrace(); + } + } + + /** + * Get the field for a specific config node and instance. + * + * <p>As expiry can have multiple blocks there will be multiple instances + * + * @param split the node (split by period) + * @param instance the instance + */ + private Field getField(String[] split, Object instance) { + try { + Field field = instance.getClass().getField(this.toFieldName(split[split.length - 1])); + this.setAccessible(field); + return field; + } catch (Throwable ignored) { + LOGGER.debug("Invalid config field: " + this.join(split, ".") + " for " + this.toNodeName(instance.getClass().getSimpleName())); + return null; + } + } + + /** + * Get the instance for a specific config node. + * + * @param split the node (split by period) + * @return The instance or null + */ + private Object getInstance(String[] split, Class<?> root) { + try { + Class<?> clazz = root == null ? MethodHandles.lookup().lookupClass() : root; + Object instance = this; + while (split.length > 0) { + if (split.length == 1) { + return instance; + } else { + Class<?> found = null; + if (clazz == null) { + return null; + } + + Class<?>[] classes = clazz.getDeclaredClasses(); + for (Class<?> current : classes) { + if (Objects.equals(current.getSimpleName(), this.toFieldName(split[0]))) { + found = current; + break; + } + } + + if (found == null) { + return null; + } + + try { + Field instanceField = clazz.getDeclaredField(this.toFieldName(split[0])); + this.setAccessible(instanceField); + Object value = instanceField.get(instance); + if (value == null) { + value = found.getDeclaredConstructor().newInstance(); + instanceField.set(instance, value); + } + + clazz = found; + instance = value; + split = Arrays.copyOfRange(split, 1, split.length); + continue; + } catch (NoSuchFieldException e) { + // + } + + split = Arrays.copyOfRange(split, 1, split.length); + clazz = found; + instance = clazz.getDeclaredConstructor().newInstance(); + } + } + } catch (Throwable e) { + e.printStackTrace(); + } + + return null; + } + + /** + * Translate a node to a java field name. + */ + private String toFieldName(String node) { + return node.toUpperCase(Locale.ROOT).replaceAll("-", "_"); + } + + /** + * Translate a field to a config node. + */ + private String toNodeName(String field) { + return field.toLowerCase(Locale.ROOT).replace("_", "-"); + } + + /** + * Set some field to be accessible. + */ + private void setAccessible(Field field) throws NoSuchFieldException, IllegalAccessException { + field.setAccessible(true); + if (Modifier.isFinal(field.getModifiers())) { + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + } + } + + @SuppressWarnings("SameParameterValue") + private String repeat(String s, int n) { + return IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining()); + } + + @SuppressWarnings("SameParameterValue") + private String join(Object[] array, String delimiter) { + switch (array.length) { + case 0: { + return ""; + } + case 1: { + return array[0].toString(); + } + default: { + final StringBuilder result = new StringBuilder(); + for (int i = 0, j = array.length; i < j; ++i) { + if (i > 0) { + result.append(delimiter); + } + result.append(array[i]); + } + + return result.toString(); + } + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java b/src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java new file mode 100644 index 0000000..38a464d --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java @@ -0,0 +1,297 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.handler; + +import at.favre.lib.crypto.bcrypt.BCrypt; +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.proxy.Player; +import dev.samstevens.totp.code.CodeVerifier; +import dev.samstevens.totp.code.DefaultCodeGenerator; +import dev.samstevens.totp.code.DefaultCodeVerifier; +import dev.samstevens.totp.time.SystemTimeProvider; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.elytrium.limboapi.api.Limbo; +import net.elytrium.limboapi.api.LimboSessionHandler; +import net.elytrium.limboapi.api.player.LimboPlayer; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.migration.MigrationHash; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class AuthSessionHandler implements LimboSessionHandler { + + private static final CodeVerifier verifier = new DefaultCodeVerifier(new DefaultCodeGenerator(), new SystemTimeProvider()); + + private final Dao<RegisteredPlayer, String> playerDao; + private final Player proxyPlayer; + private final RegisteredPlayer playerInfo; + + private LimboPlayer player; + private String ip; + private int attempts = Settings.IMP.MAIN.LOGIN_ATTEMPTS; + private boolean totp = false; + + public AuthSessionHandler(Dao<RegisteredPlayer, String> playerDao, Player proxyPlayer, String lowercaseNickname) { + this.playerDao = playerDao; + this.proxyPlayer = proxyPlayer; + this.playerInfo = this.fetchInfo(lowercaseNickname); + } + + @Override + public void onSpawn(Limbo server, LimboPlayer player) { + this.player = player; + this.player.disableFalling(); + this.ip = this.proxyPlayer.getRemoteAddress().getAddress().getHostAddress(); + + if (this.playerInfo == null) { + this.checkIp(); + } else { + this.checkCase(); + } + + this.sendMessage(); + } + + @Override + public void onChat(String message) { + String[] args = message.split(" "); + if (args.length != 0 && this.checkArgsLength(args.length)) { + switch (args[0]) { + case "/reg": + case "/register": + case "/r": { + if (!this.totp && this.playerInfo == null && this.checkPasswordsRepeat(args)) { + this.register(args[1]); + this.finishAuth(); + } else { + this.sendMessage(); + } + break; + } + case "/log": + case "/login": + case "/l": { + if (!this.totp && this.playerInfo != null) { + if (this.checkPassword(args[1])) { + this.finishOrTotp(); + } else if (--this.attempts != 0) { + this.proxyPlayer.sendMessage( + LegacyComponentSerializer.legacyAmpersand().deserialize( + MessageFormat.format(Settings.IMP.MAIN.STRINGS.LOGIN_WRONG_PASSWORD, this.attempts) + ) + ); + } else { + this.proxyPlayer.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.KICK_PASSWORD_WRONG)); + } + } else { + this.sendMessage(); + } + break; + } + case "/totp": + case "/2fa": { + if (this.totp) { + if (verifier.isValidCode(this.playerInfo.getTotpToken(), args[1])) { + this.finishAuth(); + } else { + this.sendMessage(); + } + } else { + this.sendMessage(); + } + break; + } + default: { + this.sendMessage(); + break; + } + } + } else { + this.sendMessage(); + } + } + + public static RegisteredPlayer fetchInfo(Dao<RegisteredPlayer, String> playerDao, String nickname) { + List<RegisteredPlayer> playerList = null; + try { + playerList = playerDao.queryForEq("LOWERCASENICKNAME", nickname.toLowerCase(Locale.ROOT)); + } catch (SQLException e) { + e.printStackTrace(); + } + + return (playerList != null ? playerList.size() : 0) == 0 ? null : playerList.get(0); + } + + public static RegisteredPlayer fetchInfo(Dao<RegisteredPlayer, String> playerDao, UUID uuid) { + List<RegisteredPlayer> playerList = null; + try { + playerList = playerDao.queryForEq("PREMIUMUUID", uuid.toString()); + } catch (SQLException e) { + e.printStackTrace(); + } + + return (playerList != null ? playerList.size() : 0) == 0 ? null : playerList.get(0); + } + + private RegisteredPlayer fetchInfo(String nickname) { + return fetchInfo(this.playerDao, nickname); + } + + public static CodeVerifier getVerifier() { + return verifier; + } + + public static boolean checkPassword(String password, RegisteredPlayer player, Dao<RegisteredPlayer, String> playerDao) { + boolean isCorrect = BCrypt.verifyer().verify( + password.getBytes(StandardCharsets.UTF_8), player.getHash().getBytes(StandardCharsets.UTF_8) + ).verified; + + if (!isCorrect && !Settings.IMP.MAIN.MIGRATION_HASH.isEmpty()) { + isCorrect = MigrationHash.valueOf(Settings.IMP.MAIN.MIGRATION_HASH).checkPassword(player.getHash(), password); + + if (isCorrect) { + player.setHash(genHash(password)); + try { + playerDao.update(player); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + + return isCorrect; + } + + private boolean checkPassword(String password) { + return checkPassword(password, this.playerInfo, this.playerDao); + } + + private void checkIp() { + try { + List<RegisteredPlayer> alreadyRegistered = this.playerDao.queryForEq("IP", this.ip); + + if (alreadyRegistered == null) { + return; + } + + AtomicInteger sizeOfValid = new AtomicInteger(alreadyRegistered.size()); + + if (Settings.IMP.MAIN.IP_LIMIT_VALID_TIME != 0) { + long checkDate = System.currentTimeMillis() - Settings.IMP.MAIN.IP_LIMIT_VALID_TIME; + + alreadyRegistered.stream() + .filter(e -> e.getRegDate() < checkDate) + .forEach(e -> { + try { + e.setIP(""); + this.playerDao.update(e); + sizeOfValid.decrementAndGet(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + }); + } + + if (sizeOfValid.get() >= Settings.IMP.MAIN.IP_LIMIT_REGISTRATIONS) { + this.proxyPlayer.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.IP_LIMIT)); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + private void checkCase() { + if (!this.proxyPlayer.getUsername().equals(this.playerInfo.getNickname())) { + this.proxyPlayer.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_NICKNAME_CASE)); + } + } + + private void register(String password) { + RegisteredPlayer registeredPlayer = new RegisteredPlayer( + this.proxyPlayer.getUsername(), + this.proxyPlayer.getUsername().toLowerCase(Locale.ROOT), + genHash(password), + this.ip, + "", + System.currentTimeMillis(), + this.proxyPlayer.getUniqueId().toString(), + "" + ); + + try { + this.playerDao.create(registeredPlayer); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + private void finishOrTotp() { + if (this.playerInfo.getTotpToken().isEmpty()) { + this.finishAuth(); + } else { + this.totp = true; + this.sendMessage(); + } + } + + private void finishAuth() { + this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.LOGIN_SUCCESS)); + LimboAuth.getInstance().cacheAuthUser(this.proxyPlayer); + this.player.disconnect(); + } + + private void sendMessage() { + if (this.totp) { + this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP)); + } else if (this.playerInfo == null) { + this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.REGISTER)); + } else { + this.proxyPlayer.sendMessage( + LegacyComponentSerializer.legacyAmpersand().deserialize(MessageFormat.format(Settings.IMP.MAIN.STRINGS.LOGIN, this.attempts)) + ); + } + } + + private boolean checkPasswordsRepeat(String[] args) { + if (Settings.IMP.MAIN.REGISTER_NEED_REPEAT_PASSWORD && !args[1].equals(args[2])) { + this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.DIFFERENT_PASSWORDS)); + return false; + } + + return true; + } + + private boolean checkArgsLength(int argsLength) { + if (this.playerInfo == null && Settings.IMP.MAIN.REGISTER_NEED_REPEAT_PASSWORD) { + return argsLength == 3; + } else { + return argsLength == 2; + } + } + + public static String genHash(String password) { + return BCrypt.withDefaults().hashToString(Settings.IMP.MAIN.BCRYPT_COST, password.toCharArray()); + } +} diff --git a/src/main/java/net/elytrium/limboauth/listener/AuthListener.java b/src/main/java/net/elytrium/limboauth/listener/AuthListener.java new file mode 100644 index 0000000..2892d79 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/listener/AuthListener.java @@ -0,0 +1,114 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.listener; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.connection.PreLoginEvent; +import com.velocitypowered.api.util.UuidUtils; +import java.sql.SQLException; +import java.util.UUID; +import net.elytrium.limboapi.api.event.LoginLimboRegisterEvent; +import net.elytrium.limboapi.api.event.SafeGameProfileRequestEvent; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; + +public class AuthListener { + + private final Dao<RegisteredPlayer, String> playerDao; + + public AuthListener(Dao<RegisteredPlayer, String> playerDao) { + this.playerDao = playerDao; + } + + @Subscribe + public void onProxyConnect(PreLoginEvent event) { + if (!event.getResult().isForceOfflineMode()) { + if (Settings.IMP.MAIN.ONLINE_MODE_NEED_AUTH || !LimboAuth.getInstance().isPremium(event.getUsername())) { + event.setResult(PreLoginEvent.PreLoginComponentResult.forceOfflineMode()); + } else { + event.setResult(PreLoginEvent.PreLoginComponentResult.forceOnlineMode()); + } + } + } + + @Subscribe + public void onLogin(LoginLimboRegisterEvent event) { + if (LimboAuth.getInstance().needAuth(event.getPlayer())) { + event.addCallback(() -> LimboAuth.getInstance().authPlayer(event.getPlayer())); + } + } + + @Subscribe + public void onProfile(SafeGameProfileRequestEvent event) { + if (Settings.IMP.MAIN.SAVE_UUID) { + RegisteredPlayer registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, event.getOriginalProfile().getId()); + + if (registeredPlayer != null) { + event.setGameProfile(event.getOriginalProfile().withId(UUID.fromString(registeredPlayer.getUuid()))); + return; + } + + registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, event.getUsername()); + + if (registeredPlayer != null) { + String currentUuid = registeredPlayer.getUuid(); + + if (event.isOnlineMode()) { + try { + registeredPlayer.setPremiumUuid(event.getOriginalProfile().getId().toString()); + registeredPlayer.setHash(""); + + if (currentUuid.isEmpty()) { + registeredPlayer.setUuid(UuidUtils.generateOfflinePlayerUuid(event.getUsername()).toString()); + } + + this.playerDao.update(registeredPlayer); + } catch (SQLException e) { + e.printStackTrace(); + } + + event.setGameProfile(event.getOriginalProfile().withId(UUID.fromString(currentUuid))); + } else if (currentUuid.isEmpty()) { + try { + registeredPlayer.setUuid(event.getGameProfile().getId().toString()); + this.playerDao.update(registeredPlayer); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + } + } else if (event.isOnlineMode()) { + try { + UpdateBuilder<RegisteredPlayer, String> updateBuilder = this.playerDao.updateBuilder(); + updateBuilder.where().eq("nickname", event.getUsername()); + updateBuilder.updateColumnValue("hash", ""); + updateBuilder.update(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + if (!Settings.IMP.MAIN.FORCE_OFFLINE_UUID) { + event.setGameProfile(event.getOriginalProfile().withId(UuidUtils.generateOfflinePlayerUuid(event.getUsername()))); + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/migration/MigrationHash.java b/src/main/java/net/elytrium/limboauth/migration/MigrationHash.java new file mode 100644 index 0000000..5296534 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/migration/MigrationHash.java @@ -0,0 +1,54 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.migration; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public enum MigrationHash { + + @SuppressWarnings("unused") + AUTHME((hash, password) -> { + String[] arr = hash.split("\\$"); // $SHA$salt$hash + return arr.length == 4 && arr[3].equals(MigrationHash.getSHA256(MigrationHash.getSHA256(password) + arr[2])); + }); + + final MigrationHashVerifier verifier; + + MigrationHash(MigrationHashVerifier verifier) { + this.verifier = verifier; + } + + public boolean checkPassword(String hash, String password) { + return this.verifier.checkPassword(hash, password); + } + + private static String getSHA256(String string) { + try { + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.reset(); + messageDigest.update(string.getBytes(StandardCharsets.UTF_8)); + byte[] array = messageDigest.digest(); + return String.format("%0" + (array.length << 1) + "x", new BigInteger(1, array)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException(e); + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java b/src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java new file mode 100644 index 0000000..cbe5135 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java @@ -0,0 +1,23 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.migration; + +public interface MigrationHashVerifier { + + boolean checkPassword(String hash, String password); +} diff --git a/src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java b/src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java new file mode 100644 index 0000000..55a2e3c --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java @@ -0,0 +1,130 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.model; + +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; + +@SuppressWarnings("unused") +@DatabaseTable(tableName = "AUTH") +public class RegisteredPlayer { + + @DatabaseField(canBeNull = false, columnName = "NICKNAME") + private String nickname; + + @DatabaseField(id = true, columnName = "LOWERCASENICKNAME") + private String lowercaseNickname; + + @DatabaseField(canBeNull = false, columnName = "HASH") + private String hash; + + @DatabaseField(columnName = "IP") + private String ip; + + @DatabaseField(columnName = "TOTPTOKEN") + private String totpToken; + + @DatabaseField(columnName = "REGDATE") + private Long regDate; + + @DatabaseField(columnName = "UUID") + private String uuid; + + @DatabaseField(columnName = "PREMIUMUUID") + private String premiumUuid; + + public RegisteredPlayer(String nickname, String lowercaseNickname, + String hash, String ip, String totpToken, Long regDate, String uuid, String premiumUuid) { + this.nickname = nickname; + this.lowercaseNickname = lowercaseNickname; + this.hash = hash; + this.ip = ip; + this.totpToken = totpToken; + this.regDate = regDate; + this.uuid = uuid; + this.premiumUuid = premiumUuid; + } + + public RegisteredPlayer() { + + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getNickname() { + return this.nickname; + } + + public void setLowercaseNickname(String lowercaseNickname) { + this.lowercaseNickname = lowercaseNickname; + } + + public String getLowercaseNickname() { + return this.lowercaseNickname; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public String getHash() { + return this.hash; + } + + public void setIP(String ip) { + this.ip = ip; + } + + public String getIP() { + return this.ip; + } + + public void setTotpToken(String totpToken) { + this.totpToken = totpToken; + } + + public String getTotpToken() { + return this.totpToken; + } + + public void setRegDate(Long regDate) { + this.regDate = regDate; + } + + public Long getRegDate() { + return this.regDate; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getUuid() { + return this.uuid; + } + + public void setPremiumUuid(String premiumUuid) { + this.premiumUuid = premiumUuid; + } + + public String getPremiumUuid() { + return this.premiumUuid; + } +} diff --git a/src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java b/src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java new file mode 100644 index 0000000..71af1bb --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java @@ -0,0 +1,75 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; +import net.elytrium.limboauth.Settings; +import org.slf4j.Logger; + +public class UpdatesChecker { + + public static void checkForUpdates(Logger logger) { + try { + URLConnection conn = new URL("https://raw.githubusercontent.com/Elytrium/LimboAuth/master/VERSION").openConnection(); + int timeout = (int) TimeUnit.SECONDS.toMillis(5); + conn.setConnectTimeout(timeout); + conn.setReadTimeout(timeout); + try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + String latestVersion = in.readLine(); + if (latestVersion == null) { + logger.warn("Unable to check for updates."); + return; + } + String latestVersion0 = getCleanVersion(latestVersion.trim()); + String currentVersion0 = getCleanVersion(Settings.IMP.VERSION); + int latestVersionId = Integer.parseInt(latestVersion0.replace(".", "").replace("$", "")); + int currentVersionId = Integer.parseInt(currentVersion0.replace(".", "").replace("$", "")); + if (latestVersion0.endsWith("$")) { + --latestVersionId; + } + if (currentVersion0.endsWith("$")) { + --currentVersionId; + } + + if (currentVersionId < latestVersionId) { + logger.error("****************************************"); + logger.warn("The new LimboAuth update was found, please update."); + logger.error("https://github.com/Elytrium/LimboAuth/releases/"); + logger.error("****************************************"); + } + } + } catch (IOException e) { + logger.warn("Unable to check for updates.", e); + } + } + + private static String getCleanVersion(String version) { + int indexOf = version.indexOf("-"); + if (indexOf > 0) { + return version.substring(0, indexOf) + "$"; // "$" - Indicates that the version is snapshot + } else { + return version; + } + } +} diff --git a/src/main/templates/net/elytrium/limboauth/BuildConstants.java b/src/main/templates/net/elytrium/limboauth/BuildConstants.java new file mode 100644 index 0000000..b8d7966 --- /dev/null +++ b/src/main/templates/net/elytrium/limboauth/BuildConstants.java @@ -0,0 +1,24 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth; + +// The constants are replaced before compilation +public class BuildConstants { + + public static final String AUTH_VERSION = "${version}"; +} |