Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main'
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexProgrammerDE committed Feb 1, 2025
2 parents ac54df0 + 5e1187b commit 843c52d
Show file tree
Hide file tree
Showing 20 changed files with 671 additions and 88 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,12 @@ public Integer call() {
? ""
: "`%s`"
.formatted(option.defaultValueString())
.replace("|", "\\|");
.replace("|", "\\|")
.replace("\n", " ");
if (defaultValue.length() > 50) {
defaultValue = defaultValue.substring(0, 50) + "...`";
}

var description =
option.description() == null
? ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.soulfiremc.server.api.Plugin;
import com.soulfiremc.server.api.SoulFireAPI;
import com.soulfiremc.server.brigadier.ServerConsoleCommandSource;
import com.soulfiremc.server.user.AuthSystem;
import com.soulfiremc.server.util.PortHelper;
import com.soulfiremc.server.util.SFPathConstants;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -52,7 +53,9 @@ protected void postMixinMain(String[] args) {
var soulFire =
new SoulFireServer(host, port, pluginManager, START_TIME, getBaseDirectory());

log.info("Tip: The default user is called 'root', you can log into it using the client");
if (soulFire.authSystem().rootUserData().email().equals(AuthSystem.ROOT_DEFAULT_EMAIL)) {
log.info("The root users email is '{}', please change it using the command 'set-email <email>', you can login with the client using that email", AuthSystem.ROOT_DEFAULT_EMAIL);
}

var commandManager = soulFire.injector().getSingleton(ServerCommandManager.class);
var commandSource = new ServerConsoleCommandSource(soulFire.authSystem());
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ org.gradle.cache=true
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.vfs.watch=true
maven_version=1.17.2-SNAPSHOT
maven_version=1.18.0
9 changes: 5 additions & 4 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ graalvm-polyglot = "24.1.2"
[plugins]
blossom = "net.kyori.blossom:2.1.0"
protobuf = "com.google.protobuf:0.9.4"
jmh = "me.champeau.jmh:0.7.2"
jmh = "me.champeau.jmh:0.7.3"
license-report = "com.github.jk1.dependency-license-report:2.9"

[libraries]
Expand All @@ -35,7 +35,7 @@ log4j-core = { module = "org.apache.logging.log4j:log4j-core", version.ref = "lo
log4j-slf4j2-impl = { module = "org.apache.logging.log4j:log4j-slf4j2-impl", version.ref = "log4j" }
log4j-iostreams = { module = "org.apache.logging.log4j:log4j-iostreams", version.ref = "log4j" }
log4j-jul = { module = "org.apache.logging.log4j:log4j-jul", version.ref = "log4j" }
jline = "org.jline:jline-terminal-jansi:3.28.0"
jline = "org.jline:jline-terminal-jansi:3.29.0"
jansi = "org.fusesource.jansi:jansi:2.4.1"
ansi4j-core-api = "com.github.PavelKastornyy.ansi4j:ansi4j-core-api:ansi4j-1.1.0"
ansi4j-core-impl = "com.github.PavelKastornyy.ansi4j:ansi4j-core-impl:ansi4j-1.1.0"
Expand Down Expand Up @@ -63,7 +63,7 @@ commons-validator = "commons-validator:commons-validator:1.9.0"
commons-io = "commons-io:commons-io:2.18.0"
oshi = "com.github.oshi:oshi-core:6.6.6"
guava = "com.google.guava:guava:33.4.0-jre"
gson = "com.google.code.gson:gson:2.11.0"
gson = "com.google.code.gson:gson:2.12.1"
pf4j = "org.pf4j:pf4j:3.13.0"
fastutil = "it.unimi.dsi:fastutil:8.5.15"
caffeine = "com.github.ben-manes.caffeine:caffeine:3.2.0"
Expand All @@ -90,7 +90,7 @@ armeria-prometheus1 = { module = "com.linecorp.armeria:armeria-prometheus1" }
reactor-netty-core = { module = "io.projectreactor.netty:reactor-netty-core", version.ref = "reactor" }
reactor-netty-http = { module = "io.projectreactor.netty:reactor-netty-http", version.ref = "reactor" }
spark = "me.lucko:spark-common:1.10.119-SNAPSHOT"
openai = "com.openai:openai-java:0.16.0"
openai = "com.openai:openai-java:0.20.0"
immutables = "org.immutables:value:2.10.1 "
hibernate-core = "org.hibernate.orm:hibernate-core:7.0.0.Beta3"
hibernate-community-dialects = "org.hibernate.orm:hibernate-community-dialects:7.0.0.Beta3"
Expand All @@ -104,6 +104,7 @@ graalvm-polyglot-polyglot = { module = "org.graalvm.polyglot:polyglot", version.
graalvm-polyglot-js = { module = "org.graalvm.polyglot:js", version.ref = "graalvm-polyglot" }
graalvm-polyglot-ruby = { module = "org.graalvm.polyglot:ruby", version.ref = "graalvm-polyglot" }
graalvm-polyglot-python = { module = "org.graalvm.polyglot:python", version.ref = "graalvm-polyglot" }
angus = "org.eclipse.angus:angus-mail:2.0.3"
javax-annotations = "javax.annotation:javax.annotation-api:1.3.2"
junit = "org.junit.jupiter:junit-jupiter:5.11.4"

Expand Down
14 changes: 9 additions & 5 deletions proto/src/main/proto/soulfire/login.proto
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,26 @@ option java_multiple_files = true;
package soulfire.v1;

message LoginRequest {
string username = 1;
string email = 1;
}

message NextAuthFlowResponse {
message EmailCode {
uint32 digits = 1;
}

message Success {
string token = 1;
}

message Failure {
string message = 1;
enum Reason {
INVALID_CODE = 0;
}

Reason reason = 1;
}

string authFlowToken = 1;
string auth_flow_token = 1;
oneof next {
EmailCode email_code = 2;
Success success = 3;
Expand All @@ -31,7 +34,8 @@ message NextAuthFlowResponse {
}

message EmailCodeRequest {
repeated uint32 code = 1;
string auth_flow_token = 1;
string code = 2;
}

service LoginService {
Expand Down
3 changes: 3 additions & 0 deletions server/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ dependencies {
// For script support
api(libs.bundles.graalvm.polyglot)

// For mail support
api(libs.angus)

// For tls cert provisioning
api(libs.acme4j)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.soulfiremc.server.brigadier.*;
import com.soulfiremc.server.data.BlockTags;
import com.soulfiremc.server.data.BlockType;
import com.soulfiremc.server.database.UserEntity;
import com.soulfiremc.server.pathfinding.SFVec3i;
import com.soulfiremc.server.pathfinding.controller.CollectBlockController;
import com.soulfiremc.server.pathfinding.controller.ExcavateAreaController;
Expand Down Expand Up @@ -167,6 +168,28 @@ public void postConstruct() {

return Command.SINGLE_SUCCESS;
})));
dispatcher.register(
literal("set-email")
.then(argument("email", StringArgumentType.greedyString())
.executes(
help(
"Set the email of the current user",
c -> {
if (!(c.getSource() instanceof SoulFireUser user)) {
c.getSource().sendInfo("Only SoulFire users can set their email.");
return Command.SINGLE_SUCCESS;
}

var email = StringArgumentType.getString(c, "email");
soulFireServer.sessionFactory().inTransaction(s -> {
var userData = s.find(UserEntity.class, user.getUniqueId());
userData.email(email);
s.merge(userData);
});
c.getSource().sendInfo("Email of user {} set to {}", user.getUsername(), email);

return Command.SINGLE_SUCCESS;
}))));
dispatcher.register(
literal("whoami")
.executes(
Expand Down
10 changes: 8 additions & 2 deletions server/src/main/java/com/soulfiremc/server/SoulFireServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@
import com.soulfiremc.server.settings.server.DevSettings;
import com.soulfiremc.server.settings.server.ServerSettings;
import com.soulfiremc.server.spark.SFSparkPlugin;
import com.soulfiremc.server.user.AuthSystem;
import com.soulfiremc.server.user.SoulFireUser;
import com.soulfiremc.server.user.*;
import com.soulfiremc.server.util.SFHelpers;
import com.soulfiremc.server.util.SFPathConstants;
import com.soulfiremc.server.util.SFUpdateChecker;
Expand Down Expand Up @@ -223,6 +222,13 @@ public SoulFireServer(
"Finished loading! (Took {}ms)", Duration.between(startTime, Instant.now()).toMillis());
}

public EmailSender emailSender() {
return switch (settingsSource.get(ServerSettings.EMAIL_TYPE, ServerSettings.EmailType.class)) {
case CONSOLE -> injector.getSingleton(ConsoleEmailSender.class);
case SMTP -> injector.getSingleton(SmtpEmailSender.class);
};
}

public void configUpdateHook() {
setupLoggingAndVia();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,41 +40,49 @@ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
Metadata metadata,
ServerCallHandler<ReqT, RespT> serverCallHandler) {

// Login is not authed
if (Objects.equals(serverCall.getMethodDescriptor().getServiceName(), LoginServiceGrpc.SERVICE_NAME)) {
return Contexts.interceptCall(
Context.current(),
serverCall,
metadata,
serverCallHandler
);
}

var status = Status.OK;
if (!Objects.equals(serverCall.getMethodDescriptor().getServiceName(), LoginServiceGrpc.SERVICE_NAME)) {
var value = metadata.get(RPCConstants.AUTHORIZATION_METADATA_KEY);
if (value == null) {
status = Status.UNAUTHENTICATED.withDescription("Authorization token is missing");
} else if (!value.startsWith(RPCConstants.BEARER_TYPE)) {
status = Status.UNAUTHENTICATED.withDescription("Unknown authorization type");
} else {
Jws<Claims> claims = null;
// remove authorization type prefix
var token = value.substring(RPCConstants.BEARER_TYPE.length()).strip();
try {
// verify token signature and parse claims
claims = parser.parseSignedClaims(token);
} catch (JwtException e) {
status = Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e);
}
if (claims != null) {
var user = authSystem.authenticate(
claims.getPayload().getSubject(), claims.getPayload().getIssuedAt().toInstant());
var value = metadata.get(RPCConstants.AUTHORIZATION_METADATA_KEY);
if (value == null) {
status = Status.UNAUTHENTICATED.withDescription("Authorization token is missing");
} else if (!value.startsWith(RPCConstants.BEARER_TYPE)) {
status = Status.UNAUTHENTICATED.withDescription("Unknown authorization type");
} else {
Jws<Claims> claims = null;
// remove authorization type prefix
var token = value.substring(RPCConstants.BEARER_TYPE.length()).strip();
try {
// verify token signature and parse claims
claims = parser.parseSignedClaims(token);
} catch (JwtException e) {
status = Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e);
}
if (claims != null) {
var user = authSystem.authenticate(
claims.getPayload().getSubject(), claims.getPayload().getIssuedAt().toInstant());

if (user.isPresent()) {
// set client id into current context
return Contexts.interceptCall(
Context.current()
.withValue(
ServerRPCConstants.USER_CONTEXT_KEY,
user.get()),
serverCall,
metadata,
serverCallHandler
);
} else {
status = Status.UNAUTHENTICATED.withDescription("User not found");
}
if (user.isPresent()) {
// set client id into current context
return Contexts.interceptCall(
Context.current()
.withValue(
ServerRPCConstants.USER_CONTEXT_KEY,
user.get()),
serverCall,
metadata,
serverCallHandler
);
} else {
status = Status.UNAUTHENTICATED.withDescription("User not found");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* SoulFire
* Copyright (C) 2024 AlexProgrammerDE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.soulfiremc.server.grpc;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.soulfiremc.grpc.generated.LoginServiceGrpc;
import com.soulfiremc.server.util.RPCConstants;
import io.grpc.*;

import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class LoginRateLimitingInterceptor implements ServerInterceptor {
private final Cache<UUID, Integer> callCache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> serverCall,
Metadata metadata,
ServerCallHandler<ReqT, RespT> serverCallHandler) {

var status = Status.OK;
if (Objects.equals(serverCall.getMethodDescriptor().getServiceName(), LoginServiceGrpc.SERVICE_NAME)) {
var remoteAddr = metadata.get(Metadata.Key.of("origin", Metadata.ASCII_STRING_MARSHALLER));
if (remoteAddr == null) {
status = Status.UNAUTHENTICATED.withDescription("No remote address");
} else {
var key = UUID.nameUUIDFromBytes(remoteAddr.getBytes(StandardCharsets.UTF_8));
var count = callCache.getIfPresent(key);
if (count == null) {
callCache.put(key, 1);
} else if (count < RPCConstants.LOGIN_RATE_LIMIT) {
callCache.put(key, count + 1);
}

if (count != null && count >= RPCConstants.LOGIN_RATE_LIMIT) {
status = Status.RESOURCE_EXHAUSTED.withDescription("Too many login attempts");
} else {
return Contexts.interceptCall(
Context.current(),
serverCall,
metadata,
serverCallHandler
);
}
}

serverCall.close(status, new Metadata());
return new ServerCall.Listener<>() {
// noop
};
} else {
return Contexts.interceptCall(
Context.current(),
serverCall,
metadata,
serverCallHandler
);
}
}
}
Loading

0 comments on commit 843c52d

Please sign in to comment.