0.4.14: log http request as debug

This commit is contained in:
creeper123123321 2021-10-10 13:22:09 -03:00
parent 45f380c9dd
commit 886cabafe9
4 changed files with 72 additions and 58 deletions

View File

@ -38,7 +38,7 @@ compileKotlin.kotlinOptions.jvmTarget = "11"
val gitVersion: groovy.lang.Closure<String> by extra
group = "com.github.creeper123123321.viaaas"
version = "0.4.13+" + try {
version = "0.4.14+" + try {
gitVersion()
} catch (e: Exception) {
"unknown"

View File

@ -26,7 +26,7 @@ class ViaWebApp(val viaWebServer: WebDashboardServer) {
}
}
install(CallLogging) {
level = Level.INFO
level = Level.DEBUG
this.format {
"${it.request.local.method.value} ${it.response.status()?.value} ${it.request.local.remoteHost} (O: ${it.request.origin.remoteHost}) " +
"${it.request.local.scheme}://${it.request.local.host}:${it.request.local.port}${it.request.local.uri}"
@ -45,8 +45,14 @@ class ViaWebApp(val viaWebServer: WebDashboardServer) {
install(PartialContent)
routing {
routeStatic()
routeWs()
}
}
private fun Route.routeStatic() {
static {
get("{path...}") {
// todo if-modified-since
val relativePath = Path.of(call.parameters.getAll("path")?.joinToString("/") ?: "")
val index = Path.of("index.html")
@ -65,22 +71,24 @@ class ViaWebApp(val viaWebServer: WebDashboardServer) {
resource != null -> call.respond(resource)
}
}
}
}
webSocket("/ws") {
try {
viaWebServer.connected(this)
incoming.consumeEach { frame ->
if (frame is Frame.Text) {
viaWebServer.onMessage(this, frame.readText())
}
private fun Route.routeWs() {
webSocket("/ws") {
try {
viaWebServer.connected(this)
incoming.consumeEach { frame ->
if (frame is Frame.Text) {
viaWebServer.onMessage(this, frame.readText())
}
} catch (ignored: ClosedChannelException) {
} catch (e: Exception) {
viaWebServer.onException(this, e)
this.close(CloseReason(CloseReason.Codes.INTERNAL_ERROR, "INTERNAL ERROR"))
} finally {
viaWebServer.disconnected(this)
}
} catch (ignored: ClosedChannelException) {
} catch (e: Exception) {
viaWebServer.onException(this, e)
this.close(CloseReason(CloseReason.Codes.INTERNAL_ERROR, "INTERNAL ERROR"))
} finally {
viaWebServer.disconnected(this)
}
}
}

View File

@ -18,7 +18,11 @@ data class WebClient(
fun next() = atInt.getAndAdd(1)
}
val id = "${ws.call.request.local.remoteHost}(${ws.call.request.origin.remoteHost})-${IdGen.next()}"
val id = run {
val local = ws.call.request.local.remoteHost
val remote = ws.call.request.origin.remoteHost
"$local${if (local != remote) "|$remote" else ""}-${IdGen.next()}"
}
val listenedIds: MutableSet<UUID> = Sets.newConcurrentHashSet()
val rateLimiter = RateLimiter.create(VIAaaSConfig.rateLimitWs)

View File

@ -15,10 +15,34 @@ import kotlin.math.absoluteValue
class WebLogin : WebState {
override suspend fun start(webClient: WebClient) {
webClient.ws.send("""{"action": "ad_minecraft_id_login"}""")
webClient.ws.send(JsonObject().also {
it.addProperty("action", "ad_minecraft_id_login")
}.toString())
webClient.ws.flush()
}
override suspend fun onMessage(webClient: WebClient, msg: String) {
val obj = JsonParser.parseString(msg) as JsonObject
when (obj.getAsJsonPrimitive("action").asString) {
"offline_login" -> handleOfflineLogin(webClient, msg, obj)
"minecraft_id_login" -> handleMcIdLogin(webClient, msg, obj)
"listen_login_requests" -> handleListenLogins(webClient, msg, obj)
"unlisten_login_requests" -> handleUnlisten(webClient, msg, obj)
"session_hash_response" -> handleSessionResponse(webClient, msg, obj)
else -> throw StacklessException("invalid action!")
}
webClient.ws.flush()
}
override suspend fun disconnected(webClient: WebClient) {
webClient.listenedIds.forEach { webClient.unlistenId(it) }
}
override suspend fun onException(webClient: WebClient, exception: java.lang.Exception) {
}
private fun loginSuccessJson(username: String, uuid: UUID, token: String): JsonObject {
return JsonObject().also {
it.addProperty("action", "login_result")
@ -53,28 +77,28 @@ class WebLogin : WebState {
}
private suspend fun handleMcIdLogin(webClient: WebClient, msg: String, obj: JsonObject) {
val username = obj["username"].asString
val code = obj["code"].asString
val username = obj["username"].asString
val code = obj["code"].asString
val check = AspirinServer.httpClient.submitForm<JsonObject>(
"https://api.minecraft.id/gateway/verify/${URLEncoder.encode(username, Charsets.UTF_8)}",
formParameters = parametersOf("code", code),
)
val check = AspirinServer.httpClient.submitForm<JsonObject>(
"https://api.minecraft.id/gateway/verify/${URLEncoder.encode(username, Charsets.UTF_8)}",
formParameters = parametersOf("code", code),
)
if (check.getAsJsonPrimitive("valid").asBoolean) {
val mcIdUser = check["username"].asString
val uuid = check["uuid"]?.asString?.let { parseUndashedId(it.replace("-", "")) }
?: webClient.server.usernameIdCache[mcIdUser].await()
?: throw StacklessException("Failed to get UUID from minecraft.id")
if (check.getAsJsonPrimitive("valid").asBoolean) {
val mcIdUser = check["username"].asString
val uuid = check["uuid"]?.asString?.let { parseUndashedId(it.replace("-", "")) }
?: webClient.server.usernameIdCache[mcIdUser].await()
?: throw StacklessException("Failed to get UUID from minecraft.id")
val token = webClient.server.generateToken(uuid, mcIdUser)
webClient.ws.send(loginSuccessJson(mcIdUser, uuid, token).toString())
val token = webClient.server.generateToken(uuid, mcIdUser)
webClient.ws.send(loginSuccessJson(mcIdUser, uuid, token).toString())
webLogger.info("Token gen: ${webClient.id}: $mcIdUser $uuid")
} else {
webClient.ws.send(loginNotSuccess().toString())
webLogger.info("Token gen fail: ${webClient.id}: $username")
}
webLogger.info("Token gen: ${webClient.id}: $mcIdUser $uuid")
} else {
webClient.ws.send(loginNotSuccess().toString())
webLogger.info("Token gen fail: ${webClient.id}: $username")
}
}
private suspend fun handleListenLogins(webClient: WebClient, msg: String, obj: JsonObject) {
@ -111,26 +135,4 @@ class WebLogin : WebState {
val hash = obj["session_hash"].asString
webClient.server.sessionHashCallbacks.getIfPresent(hash)?.complete(Unit)
}
override suspend fun onMessage(webClient: WebClient, msg: String) {
val obj = JsonParser.parseString(msg) as JsonObject
when (obj.getAsJsonPrimitive("action").asString) {
"offline_login" -> handleOfflineLogin(webClient, msg, obj)
"minecraft_id_login" -> handleMcIdLogin(webClient, msg, obj)
"listen_login_requests" -> handleListenLogins(webClient, msg, obj)
"unlisten_login_requests" -> handleUnlisten(webClient, msg, obj)
"session_hash_response" -> handleSessionResponse(webClient, msg, obj)
else -> throw StacklessException("invalid action!")
}
webClient.ws.flush()
}
override suspend fun disconnected(webClient: WebClient) {
webClient.listenedIds.forEach { webClient.unlistenId(it) }
}
override suspend fun onException(webClient: WebClient, exception: java.lang.Exception) {
}
}