Spotless: exclude JOOQ generated code, run spotlessApply and fix task dependencies

This commit is contained in:
fiereu committed 2025-08-25 13:47:32 +02:00
1 parent 545d4321ab
commit 1c08dabd6d
11 files changed
+98 -117

No files matched your search

@@ -1,10 +1,6 @@
package de.fiereu.openmmo.common.enums package de.fiereu.openmmo.common.enums
enum class Language( enum class Language(val code: String, private val english: String, private val display: String) {
val code: String,
private val english: String,
private val display: String
) {
EN("en", "english", "English"), EN("en", "english", "English"),
FR("fr", "french", "Français"), FR("fr", "french", "Français"),
DE("de", "german", "Deutsch"), DE("de", "german", "Deutsch"),
+16 -24
View File
@@ -1,37 +1,27 @@
import org.bouncycastle.util.io.pem.PemObject import java.io.StringWriter
import org.bouncycastle.util.io.pem.PemWriter
import java.security.KeyPairGenerator import java.security.KeyPairGenerator
import java.security.spec.ECGenParameterSpec import java.security.spec.ECGenParameterSpec
import java.io.StringWriter import org.bouncycastle.util.io.pem.PemObject
import org.bouncycastle.util.io.pem.PemWriter
buildscript { buildscript {
repositories { repositories { mavenCentral() }
mavenCentral()
dependencies { classpath(libs.bundles.crypto) }
} }
dependencies { plugins { id("buildsrc.convention.spotless") }
classpath(libs.bundles.crypto)
}
}
plugins { /** Abstract task for generating a certificate. */
id("buildsrc.convention.spotless")
}
/**
* Abstract task for generating a certificate.
*/
abstract class GenerateCertificateTask : DefaultTask() { abstract class GenerateCertificateTask : DefaultTask() {
@get:OutputFile @get:OutputFile val privateKeyOutput: RegularFileProperty = project.objects.fileProperty()
val privateKeyOutput: RegularFileProperty = project.objects.fileProperty()
@get:OutputFile @get:OutputFile val publicKeyOutput: RegularFileProperty = project.objects.fileProperty()
val publicKeyOutput: RegularFileProperty = project.objects.fileProperty()
@get:Input @get:Input
val overwriteCertificates: Property<Boolean> = project.objects.property(Boolean::class.java) val overwriteCertificates: Property<Boolean> =
.convention(false) project.objects.property(Boolean::class.java).convention(false)
init { init {
group = "openmmo" group = "openmmo"
@@ -53,7 +43,8 @@ abstract class GenerateCertificateTask : DefaultTask() {
val keyPair = keyPairGenerator.generateKeyPair() val keyPair = keyPairGenerator.generateKeyPair()
// Write private key as PEM // Write private key as PEM
val privateKeyPem = StringWriter().use { writer -> val privateKeyPem =
StringWriter().use { writer ->
PemWriter(writer).use { pemWriter -> PemWriter(writer).use { pemWriter ->
pemWriter.writeObject(PemObject("EC PRIVATE KEY", keyPair.private.encoded)) pemWriter.writeObject(PemObject("EC PRIVATE KEY", keyPair.private.encoded))
} }
@@ -62,7 +53,8 @@ abstract class GenerateCertificateTask : DefaultTask() {
privateKeyFile.writeText(privateKeyPem) privateKeyFile.writeText(privateKeyPem)
// Write public key as PEM // Write public key as PEM
val publicKeyPem = StringWriter().use { writer -> val publicKeyPem =
StringWriter().use { writer ->
PemWriter(writer).use { pemWriter -> PemWriter(writer).use { pemWriter ->
pemWriter.writeObject(PemObject("PUBLIC KEY", keyPair.public.encoded)) pemWriter.writeObject(PemObject("PUBLIC KEY", keyPair.public.encoded))
} }
@@ -8,8 +8,8 @@ import de.fiereu.openmmo.protocols.tls.packets.LoginRequestPacketDeserializer
import de.fiereu.openmmo.protocols.tls.packets.LoginRequestPacketSerializer import de.fiereu.openmmo.protocols.tls.packets.LoginRequestPacketSerializer
/** /**
* Login Protocol implementation. * Login Protocol implementation. This protocol handles the login process after the TLS handshake is
* This protocol handles the login process after the TLS handshake is complete. * complete.
*/ */
abstract class LoginProtocol() : Protocol() { abstract class LoginProtocol() : Protocol() {
override val async: Boolean override val async: Boolean
@@ -27,4 +27,3 @@ class LoginClientProtocol() : LoginProtocol() {
outgoingPacket(0x11u, LoginRequestPacket::class, LoginRequestPacketSerializer()) outgoingPacket(0x11u, LoginRequestPacket::class, LoginRequestPacketSerializer())
} }
} }
@@ -9,6 +9,7 @@ import de.fiereu.openmmo.protocols.writeUtf16LE
interface LoginMethod interface LoginMethod
data class PasswordLogin(val password: String, val stayLoggedIn: Boolean) : LoginMethod data class PasswordLogin(val password: String, val stayLoggedIn: Boolean) : LoginMethod
data class TokenLogin(val token: ByteArray) : LoginMethod data class TokenLogin(val token: ByteArray) : LoginMethod
data class LoginRequestPacket( data class LoginRequestPacket(
@@ -62,7 +63,8 @@ class LoginRequestPacketDeserializer : PacketDeserializer<LoginRequestPacket> {
buffer.readBytes(hwid) buffer.readBytes(hwid)
val methodType = buffer.readByte().toInt() val methodType = buffer.readByte().toInt()
val method: LoginMethod = when (methodType) { val method: LoginMethod =
when (methodType) {
0 -> { // Password 0 -> { // Password
val password = buffer.readUtf16LE() val password = buffer.readUtf16LE()
val stayLoggedIn = buffer.readBoolean() val stayLoggedIn = buffer.readBoolean()
@@ -99,7 +101,6 @@ class LoginRequestPacketDeserializer : PacketDeserializer<LoginRequestPacket> {
clientRevision, clientRevision,
installationRevision, installationRevision,
os, os,
hardwareInfoCache hardwareInfoCache)
)
} }
} }
@@ -8,30 +8,29 @@ import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey import java.security.interfaces.ECPublicKey
/** /**
* TLS Protocol implementation. * TLS Protocol implementation. This protocol handles the initial TLS handshake before any secure
* This protocol handles the initial TLS handshake before any secure communication can take place. * communication can take place.
* *
* The flow is as follows: * The flow is as follows:
* 1. Client sends a ClientHello packet to initiate the handshake. * 1. Client sends a ClientHello packet to initiate the handshake.
* 2. Server responds with a ServerHello packet. * 2. Server responds with a ServerHello packet. -> The client knows the servers public key and its
* -> The client knows the servers public key and its own private key. And it can derive a shared secret using ECDH. * own private key. And it can derive a shared secret using ECDH. -> Every packet the client now
* -> Every packet the client now would receive is expected to be secured. * would receive is expected to be secured. -> Client switches to next protocol (e.g.
* -> Client switches to next protocol (e.g. LoginProtocol) after the handshake is complete. * LoginProtocol) after the handshake is complete.
* 3. Client sends a ClientReady packet with its public key. * 3. Client sends a ClientReady packet with its public key. -> The server can now secure its
* -> The server can now secure its communication with the client using the shared secret. * communication with the client using the shared secret. -> Server switches to next protocol
* -> Server switches to next protocol (e.g. LoginProtocol) after the handshake is complete. * (e.g. LoginProtocol) after the handshake is complete.
*/ */
abstract class TlsProtocol() : Protocol() { abstract class TlsProtocol() : Protocol() {
override val async: Boolean override val async: Boolean
get() = false get() = false
} }
class TlsServerProtocol( class TlsServerProtocol(serverKeyPair: Pair<ECPrivateKey, ECPublicKey>) : TlsProtocol() {
serverKeyPair: Pair<ECPrivateKey, ECPublicKey>
) : TlsProtocol() {
init { init {
incomingPacket(0x00u, ClientHelloPacketDeserializer()) incomingPacket(0x00u, ClientHelloPacketDeserializer())
outgoingPacket(0x01u, ServerHelloPacket::class, ServerHelloPacketSerializer(serverKeyPair.first)) outgoingPacket(
0x01u, ServerHelloPacket::class, ServerHelloPacketSerializer(serverKeyPair.first))
incomingPacket(0x02u, ClientReadyPacketDeserializer()) incomingPacket(0x02u, ClientReadyPacketDeserializer())
} }
} }
@@ -43,4 +42,3 @@ class TlsClientProtocol() : TlsProtocol() {
outgoingPacket(0x02u, ClientReadyPacket::class, ClientReadyPacketSerializer()) outgoingPacket(0x02u, ClientReadyPacket::class, ClientReadyPacketSerializer())
} }
} }
@@ -7,9 +7,7 @@ import de.fiereu.openmmo.protocols.tls.util.toUncompressedPoint
import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBuf
import java.security.interfaces.ECPublicKey import java.security.interfaces.ECPublicKey
data class ClientReadyPacket( data class ClientReadyPacket(val clientPublicKey: ECPublicKey)
val clientPublicKey: ECPublicKey
)
class ClientReadyPacketSerializer : PacketSerializer<ClientReadyPacket> { class ClientReadyPacketSerializer : PacketSerializer<ClientReadyPacket> {
@@ -16,14 +16,10 @@ import java.security.interfaces.ECPublicKey
* @property publicKey The public key generated for this connection. * @property publicKey The public key generated for this connection.
* @property checksumSize The size of the checksum used for this connection. * @property checksumSize The size of the checksum used for this connection.
*/ */
data class ServerHelloPacket( data class ServerHelloPacket(val publicKey: ECPublicKey, val checksumSize: Int)
val publicKey: ECPublicKey,
val checksumSize: Int
)
class ServerHelloPacketSerializer( class ServerHelloPacketSerializer(private val serverRootPrivateKey: ECPrivateKey) :
private val serverRootPrivateKey: ECPrivateKey PacketSerializer<ServerHelloPacket> {
) : PacketSerializer<ServerHelloPacket> {
override fun serialize(packet: ServerHelloPacket, buffer: ByteBuf) { override fun serialize(packet: ServerHelloPacket, buffer: ByteBuf) {
val publicKeyBytes = packet.publicKey.toUncompressedPoint() val publicKeyBytes = packet.publicKey.toUncompressedPoint()
@@ -39,7 +35,8 @@ class ServerHelloPacketSerializer(
} }
} }
class ServerHelloPacketDeserializer : PacketDeserializer<ServerHelloPacketDeserializer.ServerHelloPacket> { class ServerHelloPacketDeserializer :
PacketDeserializer<ServerHelloPacketDeserializer.ServerHelloPacket> {
data class ServerHelloPacket( data class ServerHelloPacket(
val clientPublicKey: PublicKey, val clientPublicKey: PublicKey,
@@ -3,14 +3,13 @@ package de.fiereu.openmmo.protocols.tls.util
import java.math.BigInteger import java.math.BigInteger
import java.security.AlgorithmParameters import java.security.AlgorithmParameters
import java.security.KeyFactory import java.security.KeyFactory
import java.security.Security import java.security.Signature
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey import java.security.interfaces.ECPublicKey
import java.security.spec.ECGenParameterSpec import java.security.spec.ECGenParameterSpec
import java.security.spec.ECParameterSpec import java.security.spec.ECParameterSpec
import java.security.spec.ECPoint import java.security.spec.ECPoint
import java.security.spec.ECPublicKeySpec import java.security.spec.ECPublicKeySpec
import java.security.Signature
import java.security.interfaces.ECPrivateKey
private const val uncompressedPointIndicator: Byte = 0x04 private const val uncompressedPointIndicator: Byte = 0x04
@@ -4,20 +4,17 @@ import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBuf
import kotlin.reflect.KClass import kotlin.reflect.KClass
/** /** Value class wrapping a UByte to represent an opcode. */
* Value class wrapping a UByte to represent an opcode.
*/
@JvmInline @JvmInline
value class Opcode(val value: UByte) { value class Opcode(val value: UByte) {
override fun toString(): String = "0x${value.toString(16).padStart(2, '0').uppercase()}" override fun toString(): String = "0x${value.toString(16).padStart(2, '0').uppercase()}"
} }
/** /**
* Packet direction enum representing the direction of packet flow. * Packet direction enum representing the direction of packet flow. This is needed because depending
* This is needed because depending on the current side (client or server), * on the current side (client or server), the same opcode can represent different packets. For
* the same opcode can represent different packets. * example, opcode 0x01 might represent a "LoginRequest" packet on the client side, but a
* For example, opcode 0x01 might represent a "LoginRequest" packet on the client side, * "LoginResponse" packet on the server side.
* but a "LoginResponse" packet on the server side.
*/ */
enum class PacketDirection { enum class PacketDirection {
CLIENT_TO_SERVER, CLIENT_TO_SERVER,
@@ -26,9 +23,9 @@ enum class PacketDirection {
interface PacketSerializer<T : Any> { interface PacketSerializer<T : Any> {
fun serializeObject(packet: Any, buffer: ByteBuf) { fun serializeObject(packet: Any, buffer: ByteBuf) {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") serialize(packet as T, buffer)
serialize(packet as T, buffer)
} }
fun serialize(packet: T, buffer: ByteBuf) fun serialize(packet: T, buffer: ByteBuf)
} }
@@ -37,12 +34,12 @@ interface PacketDeserializer<T : Any> {
} }
/** /**
* The base class for all protocols. * The base class for all protocols. A protocol is a collection of packets that can be sent and
* A protocol is a collection of packets that can be sent and received. * received.
* *
* We cant combine Server and Client protocols because they have different dependencies. * We cant combine Server and Client protocols because they have different dependencies. For
* For example, the server protocol needs to know about the server's root private key, * example, the server protocol needs to know about the server's root private key, while the client
* while the client protocol should not have any knowledge about the server's private key. * protocol should not have any knowledge about the server's private key.
*/ */
abstract class Protocol { abstract class Protocol {
private val log = KotlinLogging.logger {} private val log = KotlinLogging.logger {}
@@ -56,11 +53,10 @@ abstract class Protocol {
return dataClassToOpcode[dataClass] return dataClassToOpcode[dataClass]
} }
fun <T : Any> registerIncoming( fun <T : Any> registerIncoming(opcode: Opcode, deserializer: PacketDeserializer<T>) {
opcode: Opcode, log.debug {
deserializer: PacketDeserializer<T> "Registering incoming packet: opcode=$opcode, deserializer=${deserializer::class.simpleName}"
) { }
log.debug { "Registering incoming packet: opcode=$opcode, deserializer=${deserializer::class.simpleName}" }
incomingPacketRegistry.put(opcode, deserializer) incomingPacketRegistry.put(opcode, deserializer)
} }
@@ -70,7 +66,9 @@ abstract class Protocol {
dataClass: KClass<T>, dataClass: KClass<T>,
serializer: PacketSerializer<T>, serializer: PacketSerializer<T>,
) { ) {
log.debug { "Registering outgoing packet: opcode=$opcode, serializer=${serializer::class.simpleName}" } log.debug {
"Registering outgoing packet: opcode=$opcode, serializer=${serializer::class.simpleName}"
}
dataClassToOpcode[dataClass] = opcode dataClassToOpcode[dataClass] = opcode
outgoingPacketRegistry.put(opcode, serializer) outgoingPacketRegistry.put(opcode, serializer)
@@ -89,10 +87,7 @@ fun Protocol.getDeserializer(opcode: UByte): PacketDeserializer<*>? {
return this.getDeserializer(Opcode(opcode)) return this.getDeserializer(Opcode(opcode))
} }
fun <T : Any> Protocol.incomingPacket( fun <T : Any> Protocol.incomingPacket(opcode: UByte, deserializer: PacketDeserializer<T>) {
opcode: UByte,
deserializer: PacketDeserializer<T>
) {
this.registerIncoming(Opcode(opcode), deserializer) this.registerIncoming(Opcode(opcode), deserializer)
} }
@@ -103,4 +98,3 @@ fun <T : Any> Protocol.outgoingPacket(
) { ) {
this.registerOutgoing(Opcode(opcode), dataClass, serializer) this.registerOutgoing(Opcode(opcode), dataClass, serializer)
} }
+28 -20
View File
@@ -1,10 +1,6 @@
import org.flywaydb.gradle.task.AbstractFlywayTask import org.flywaydb.gradle.task.AbstractFlywayTask
buildscript { buildscript { dependencies { classpath(libs.flyway.postgresql) } }
dependencies {
classpath(libs.flyway.postgresql)
}
}
plugins { plugins {
application application
@@ -18,6 +14,7 @@ plugins {
} }
group = "de.fiereu.openmmo" group = "de.fiereu.openmmo"
version = "0.1.0" version = "0.1.0"
dependencies { dependencies {
@@ -39,9 +36,7 @@ dependencies {
testImplementation(libs.mockk) testImplementation(libs.mockk)
} }
application { application { mainClass.set("de.fiereu.openmmo.server.login.LoginServerKt") }
mainClass.set("de.fiereu.openmmo.server.login.LoginServerKt")
}
tasks.classes.get().apply { tasks.classes.get().apply {
dependsOn("copyKeysGame") dependsOn("copyKeysGame")
@@ -49,19 +44,22 @@ tasks.classes.get().apply {
} }
fun env(key: String): Any { fun env(key: String): Any {
val value = property(key) ?: val value =
System.getenv(key) ?: property(key)
throw IllegalArgumentException("Environment variable or system property '$key' is not set.") ?: System.getenv(key)
?: throw IllegalArgumentException(
"Environment variable or system property '$key' is not set.")
fun interpolate(value: String): Any { fun interpolate(value: String): Any {
val PATTERN_WORD = Regex("\\$([a-zA-Z0-9_]+)") val PATTERN_WORD = Regex("\\$([a-zA-Z0-9_]+)")
val PATTERN_MULTI = Regex("\\$\\{([a-zA-Z0-9_]+)\\}") val PATTERN_MULTI = Regex("\\$\\{([a-zA-Z0-9_]+)\\}")
return (PATTERN_WORD.findAll(value) + PATTERN_MULTI.findAll(value)) return (PATTERN_WORD.findAll(value) + PATTERN_MULTI.findAll(value)).distinct().fold(value) {
.distinct() acc,
.fold(value) { acc, match -> match ->
val envName = match.groupValues[1] val envName = match.groupValues[1]
val envValue = System.getProperty(envName) ?: System.getProperty(envName) val envValue = System.getProperty(envName) ?: System.getProperty(envName)
if (envValue == null) { if (envValue == null) {
throw IllegalArgumentException("Environment variable or system property '$envName' is not set.") throw IllegalArgumentException(
"Environment variable or system property '$envName' is not set.")
} }
acc.replace(match.value, envValue) acc.replace(match.value, envValue)
} }
@@ -88,16 +86,15 @@ jooq {
database { database {
name = "org.jooq.meta.postgres.PostgresDatabase" name = "org.jooq.meta.postgres.PostgresDatabase"
includes = ".*" includes = ".*"
excludes = """ excludes =
"""
flyway_schema_history | flyway_schema_history |
pgp_armor_headers pgp_armor_headers
""" """
inputSchema = "public" inputSchema = "public"
} }
generate { generate { name = "org.jooq.codegen.KotlinGenerator" }
name = "org.jooq.codegen.KotlinGenerator"
}
target { target {
packageName = "de.fiereu.openmmo.server.login.jooq" packageName = "de.fiereu.openmmo.server.login.jooq"
directory = "src/main/jooq" directory = "src/main/jooq"
@@ -116,7 +113,8 @@ flyway {
cleanDisabled = false cleanDisabled = false
} }
// Fuck this shit uhh we are not gonna update our gradle plugin bc all our enterprise customers are stuck on Java 1.6 and gradle 5 anyway // Fuck this shit uhh we are not gonna update our gradle plugin bc all our enterprise customers are
// stuck on Java 1.6 and gradle 5 anyway
tasks.withType<AbstractFlywayTask>().configureEach { tasks.withType<AbstractFlywayTask>().configureEach {
notCompatibleWithConfigurationCache("https://github.com/flyway/flyway/issues/3550") notCompatibleWithConfigurationCache("https://github.com/flyway/flyway/issues/3550")
} }
@@ -126,3 +124,13 @@ tasks.register("cleanMigrateAndGenerate") {
description = "Cleans the database, migrates it and generates the jOOQ classes." description = "Cleans the database, migrates it and generates the jOOQ classes."
dependsOn("flywayClean", "flywayMigrate", "jooqCodegen") dependsOn("flywayClean", "flywayMigrate", "jooqCodegen")
} }
spotless { kotlin { targetExclude("src/main/jooq/**") } }
// If someone knows a better way then this please please please help me :(
listOf("spotlessKotlinGradle", "spotlessMisc").forEach { taskName ->
tasks.named(taskName) {
dependsOn("copyPublicKeyGame")
dependsOn("copyPrivateKeyGame")
}
}
@@ -12,20 +12,19 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
fun main() { fun main() {
val serverConfig = ServerConfig( val serverConfig = ServerConfig(port = 2106)
port = 2106 val tlsConfig = TlsConfig(checksumSize = 16)
)
val tlsConfig = TlsConfig(
checksumSize = 16
)
val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val server = ServerBuilder.create() val server =
ServerBuilder.create()
.withCoroutineScope(coroutineScope) .withCoroutineScope(coroutineScope)
.withConfig(serverConfig) .withConfig(serverConfig)
.withTlsConfig(tlsConfig) .withTlsConfig(tlsConfig)
.withPublicKey(KeyLoader.loadPemECPublicKey(resource("game.public.pem"))) .withPublicKey(KeyLoader.loadPemECPublicKey(resource("game.public.pem")))
.withPrivateKey(KeyLoader.loadPemECPrivateKey(resource("game.private.pem"))) .withPrivateKey(KeyLoader.loadPemECPrivateKey(resource("game.private.pem")))
.withChannelHandlerProvider { LoginProtocolHandler(LoginServerProtocol(), coroutineScope) } .withChannelHandlerProvider {
LoginProtocolHandler(LoginServerProtocol(), coroutineScope)
}
.build() .build()
server.start() server.start()
} }