first commit

This commit is contained in:
usbharu 2023-03-24 12:58:12 +09:00
commit 2bdbfc2b13
45 changed files with 1527 additions and 0 deletions

37
.gitignore vendored Normal file
View File

@ -0,0 +1,37 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
*.db

52
build.gradle.kts Normal file
View File

@ -0,0 +1,52 @@
val ktor_version: String by project
val kotlin_version: String by project
val logback_version: String by project
val exposed_version: String by project
val h2_version: String by project
val koin_version: String by project
plugins {
kotlin("jvm") version "1.8.10"
id("io.ktor.plugin") version "2.2.4"
// id("org.jetbrains.kotlin.plugin.serialization") version "1.8.10"
}
group = "dev.usbharu"
version = "0.0.1"
application {
mainClass.set("io.ktor.server.netty.EngineMain")
val isDevelopment: Boolean = project.ext.has("development")
applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment")
}
repositories {
mavenCentral()
}
dependencies {
implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
implementation("io.ktor:ktor-server-auth-jvm:$ktor_version")
implementation("io.ktor:ktor-server-sessions-jvm:$ktor_version")
implementation("io.ktor:ktor-server-auto-head-response-jvm:$ktor_version")
implementation("io.ktor:ktor-server-cors-jvm:$ktor_version")
implementation("io.ktor:ktor-server-default-headers-jvm:$ktor_version")
implementation("io.ktor:ktor-server-forwarded-header-jvm:$ktor_version")
implementation("io.ktor:ktor-server-call-logging-jvm:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
implementation("io.ktor:ktor-serialization-jackson:$ktor_version")
implementation("org.jetbrains.exposed:exposed-core:$exposed_version")
implementation("org.jetbrains.exposed:exposed-jdbc:$exposed_version")
implementation("com.h2database:h2:$h2_version")
implementation("org.xerial:sqlite-jdbc:3.40.1.0")
implementation("io.ktor:ktor-server-websockets-jvm:$ktor_version")
implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.insert-koin:koin-core:$koin_version")
implementation("io.insert-koin:koin-ktor:$koin_version")
implementation("io.insert-koin:koin-logger-slf4j:$koin_version")
testImplementation("io.ktor:ktor-server-tests-jvm:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")
}

7
gradle.properties Normal file
View File

@ -0,0 +1,7 @@
ktor_version=2.2.4
kotlin_version=1.8.10
logback_version=1.2.11
kotlin.code.style=official
exposed_version=0.41.1
h2_version=2.1.214
koin_version=3.3.1

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -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" "$@"

89
gradlew.bat vendored Normal file
View File

@ -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

1
settings.gradle.kts Normal file
View File

@ -0,0 +1 @@
rootProject.name = "hideout"

View File

@ -0,0 +1,67 @@
package dev.usbharu.hideout
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.config.ConfigData
import dev.usbharu.hideout.plugins.*
import dev.usbharu.hideout.repository.IUserAuthRepository
import dev.usbharu.hideout.repository.IUserRepository
import dev.usbharu.hideout.repository.UserAuthRepository
import dev.usbharu.hideout.repository.UserRepository
import dev.usbharu.hideout.routing.login
import dev.usbharu.hideout.routing.register
import dev.usbharu.hideout.routing.user
import dev.usbharu.hideout.routing.wellKnown
import dev.usbharu.hideout.service.ActivityPubUserService
import dev.usbharu.hideout.service.IUserAuthService
import dev.usbharu.hideout.service.UserAuthService
import dev.usbharu.hideout.service.UserService
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.util.*
import org.jetbrains.exposed.sql.Database
import org.koin.ktor.ext.inject
import java.util.Base64
fun main(args: Array<String>): Unit =
io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
fun Application.module() {
val module = org.koin.dsl.module {
single<Database>{ Database.connect(
url = "jdbc:h2:./test;MODE=POSTGRESQL",
driver = "org.h2.Driver",
) }
single<ConfigData>{ ConfigData(
environment.config.property("hideout.hostname").getString(),
jacksonObjectMapper()
) }
single<IUserRepository>{UserRepository(get())}
single<IUserAuthRepository>{UserAuthRepository(get())}
single<IUserAuthService>{ UserAuthService(get(),get()) }
single<UserService> { UserService(get()) }
single<ActivityPubUserService> { ActivityPubUserService(get())}
}
configureKoin(module)
val configData by inject<ConfigData>()
Config.configData = configData
val decode = Base64.getDecoder().decode("76pc9N9hspQqapj30kCaLJA14O/50ptCg50zCA1oxjA=")
val pair = "admin" to decode
println(pair)
val userAuthService by inject<IUserAuthService>()
val userService by inject<UserService>()
configureSecurity(userAuthService)
configureHTTP()
configureMonitoring()
configureSerialization()
configureSockets()
configureRouting()
val activityPubUserService by inject<ActivityPubUserService>()
user(userService,activityPubUserService)
login()
register(userAuthService)
wellKnown(userService)
}

View File

@ -0,0 +1,16 @@
package dev.usbharu.hideout.ap
open class Image : Object {
private var mediaType: String? = null
private var url: String? = null
protected constructor() : super()
constructor(type: List<String> = emptyList(), name: String, mediaType: String?, url: String?) : super(
type,
name
) {
this.mediaType = mediaType
this.url = url
}
}

View File

@ -0,0 +1,18 @@
package dev.usbharu.hideout.ap
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
open class JsonLd {
@JsonProperty("@context")
var context:List<String> = emptyList()
@JsonCreator
constructor(context:List<String>){
this.context = context
}
protected constructor()
}

View File

@ -0,0 +1,20 @@
package dev.usbharu.hideout.ap
open class Object : JsonLd {
private var type: List<String> = emptyList()
private var name: String? = null
protected constructor()
constructor(type: List<String>, name: String) : super() {
this.type = type
this.name = name
}
companion object {
@JvmStatic
protected fun add(list:List<String>,type:String):List<String> {
list.toMutableList().add(type)
return list.distinct()
}
}
}

View File

@ -0,0 +1,32 @@
package dev.usbharu.hideout.ap
open class Person : Object {
private var id:String? = null
private var preferredUsername:String? = null
private var summary:String? = null
private var inbox:String? = null
private var outbox:String? = null
private var url:String? = null
private var icon:Image? = null
protected constructor() : super()
constructor(
type: List<String> = emptyList(),
name: String,
id: String?,
preferredUsername: String?,
summary: String?,
inbox: String?,
outbox: String?,
url: String?,
icon: Image?
) : super(add(type,"Person"), name) {
this.id = id
this.preferredUsername = preferredUsername
this.summary = summary
this.inbox = inbox
this.outbox = outbox
this.url = url
this.icon = icon
}
}

View File

@ -0,0 +1,10 @@
package dev.usbharu.hideout.config
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
object Config {
var configData:ConfigData = ConfigData("", jacksonObjectMapper())
}
data class ConfigData(val hostname:String,val objectMapper: ObjectMapper)

View File

@ -0,0 +1,20 @@
package dev.usbharu.hideout.domain.model
import org.jetbrains.exposed.dao.id.LongIdTable
data class User(val name: String, val screenName: String, val description: String)
data class UserEntity(
val id: Long,
val name: String,
val screenName: String,
val description: String
) {
constructor(id: Long, user: User) : this(id, user.name, user.screenName, user.description)
}
object Users : LongIdTable("users") {
val name = varchar("name", length = 64).uniqueIndex()
val screenName = varchar("screen_name", length = 64)
val description = varchar("description", length = 600)
}

View File

@ -0,0 +1,34 @@
package dev.usbharu.hideout.domain.model
import org.jetbrains.exposed.dao.id.LongIdTable
import org.jetbrains.exposed.sql.ReferenceOption
data class UserAuthentication(
val userId: Long,
val hash: String,
val publicKey: String,
val privateKey: String
)
data class UserAuthenticationEntity(
val id: Long,
val userId: Long,
val hash: String,
val publicKey: String,
val privateKey: String
) {
constructor(id: Long, userAuthentication: UserAuthentication) : this(
id,
userAuthentication.userId,
userAuthentication.hash,
userAuthentication.publicKey,
userAuthentication.privateKey
)
}
object UsersAuthentication : LongIdTable("users_auth") {
val userId = long("user_id").references(Users.id, onUpdate = ReferenceOption.CASCADE)
val hash = varchar("hash", length = 64)
val publicKey = varchar("public_key", length = 1000_000)
val privateKey = varchar("private_key", length = 1000_000)
}

View File

@ -0,0 +1,14 @@
package dev.usbharu.hideout.exception
class UserNotFoundException : Exception {
constructor() : super()
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
constructor(cause: Throwable?) : super(cause)
constructor(
message: String?,
cause: Throwable?,
enableSuppression: Boolean,
writableStackTrace: Boolean
) : super(message, cause, enableSuppression, writableStackTrace)
}

View File

@ -0,0 +1,14 @@
package dev.usbharu.hideout.plugins
import dev.usbharu.hideout.ap.JsonLd
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.util.HttpUtil.Activity
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
suspend fun <T : JsonLd> ApplicationCall.respondAp(message: T, status: HttpStatusCode = HttpStatusCode.OK) {
message.context += "https://www.w3.org/activitystreams"
val activityJson = Config.configData.objectMapper.writeValueAsString(message)
respondText(activityJson, ContentType.Application.Activity, status)
}

View File

@ -0,0 +1,24 @@
package dev.usbharu.hideout.plugins
import io.ktor.http.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.forwardedheaders.*
import io.ktor.server.application.*
fun Application.configureHTTP() {
install(CORS) {
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Delete)
allowMethod(HttpMethod.Patch)
allowHeader(HttpHeaders.Authorization)
allowHeader("MyCustomHeader")
anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
}
install(DefaultHeaders) {
header("X-Engine", "Ktor") // will send this header with each response
}
install(ForwardedHeaders) // WARNING: for security, do not include this if not behind a reverse proxy
install(XForwardedHeaders) // WARNING: for security, do not include this if not behind a reverse proxy
}

View File

@ -0,0 +1,13 @@
package dev.usbharu.hideout.plugins
import io.ktor.server.application.*
import org.koin.core.module.Module
import org.koin.ktor.plugin.Koin
import org.koin.logger.slf4jLogger
fun Application.configureKoin(module: Module) {
install(Koin) {
slf4jLogger()
modules(module)
}
}

View File

@ -0,0 +1,13 @@
package dev.usbharu.hideout.plugins
import io.ktor.server.plugins.callloging.*
import org.slf4j.event.*
import io.ktor.server.request.*
import io.ktor.server.application.*
fun Application.configureMonitoring() {
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
}

View File

@ -0,0 +1,15 @@
package dev.usbharu.hideout.plugins
import io.ktor.server.routing.*
import io.ktor.server.response.*
import io.ktor.server.plugins.autohead.*
import io.ktor.server.application.*
fun Application.configureRouting() {
install(AutoHeadResponse)
routing {
get("/") {
call.respondText("Hello World!")
}
}
}

View File

@ -0,0 +1,24 @@
package dev.usbharu.hideout.plugins
import dev.usbharu.hideout.service.IUserAuthService
import dev.usbharu.hideout.service.UserService
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.sessions.*
import kotlin.time.Duration.Companion.days
data class UserSession(val username: String) : Principal
const val tokenAuth = "token-auth"
fun Application.configureSecurity(userAuthService: IUserAuthService) {
install(Authentication){
bearer(tokenAuth) {
authenticate {
bearerTokenCredential ->
UserIdPrincipal(bearerTokenCredential.token)
}
skipWhen { true }
}
}
}

View File

@ -0,0 +1,18 @@
package dev.usbharu.hideout.plugins
import io.ktor.serialization.jackson.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureSerialization() {
install(ContentNegotiation) {
jackson()
}
routing {
get("/json/kotlinx-serialization") {
call.respond(mapOf("hello" to "world"))
}
}
}

View File

@ -0,0 +1,29 @@
package dev.usbharu.hideout.plugins
import io.ktor.server.websocket.*
import io.ktor.websocket.*
import java.time.Duration
import io.ktor.server.application.*
import io.ktor.server.routing.*
fun Application.configureSockets() {
install(WebSockets) {
pingPeriod = Duration.ofSeconds(15)
timeout = Duration.ofSeconds(15)
maxFrameSize = Long.MAX_VALUE
masking = false
}
routing {
webSocket("/ws") { // websocketSession
for (frame in incoming) {
if (frame is Frame.Text) {
val text = frame.readText()
outgoing.send(Frame.Text("YOU SAID: $text"))
if (text.equals("bye", ignoreCase = true)) {
close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
}
}
}
}
}
}

View File

@ -0,0 +1,15 @@
package dev.usbharu.hideout.repository
import dev.usbharu.hideout.domain.model.UserAuthentication
import dev.usbharu.hideout.domain.model.UserAuthenticationEntity
interface IUserAuthRepository {
suspend fun create(userAuthentication: UserAuthentication):UserAuthenticationEntity
suspend fun findById(id:Long):UserAuthenticationEntity?
suspend fun update(userAuthenticationEntity: UserAuthenticationEntity)
suspend fun delete(id:Long)
suspend fun findByUserId(id: Long): UserAuthenticationEntity?
}

View File

@ -0,0 +1,3 @@
package dev.usbharu.hideout.repository
interface IUserKeyRepository

View File

@ -0,0 +1,20 @@
package dev.usbharu.hideout.repository
import dev.usbharu.hideout.domain.model.User
import dev.usbharu.hideout.domain.model.UserEntity
interface IUserRepository {
suspend fun create(user: User): UserEntity
suspend fun findById(id: Long): UserEntity?
suspend fun findByName(name:String): UserEntity?
suspend fun update(userEntity: UserEntity)
suspend fun delete(id: Long)
suspend fun findAll():List<User>
suspend fun findAllByLimitAndByOffset(limit:Int,offset:Long = 0):List<UserEntity>
}

View File

@ -0,0 +1,62 @@
package dev.usbharu.hideout.repository
import dev.usbharu.hideout.domain.model.UserAuthentication
import dev.usbharu.hideout.domain.model.UserAuthenticationEntity
import dev.usbharu.hideout.domain.model.UsersAuthentication
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.transaction
class UserAuthRepository(private val database: Database) : IUserAuthRepository {
init {
transaction(database) {
SchemaUtils.create(UsersAuthentication)
}
}
private fun ResultRow.toUserAuth():UserAuthenticationEntity{
return UserAuthenticationEntity(
id = this[UsersAuthentication.id].value,
userId = this[UsersAuthentication.userId],
hash = this[UsersAuthentication.hash],
publicKey = this[UsersAuthentication.publicKey],
privateKey = this[UsersAuthentication.privateKey]
)
}
suspend fun <T> query(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) {block()}
override suspend fun create(userAuthentication: UserAuthentication): UserAuthenticationEntity {
return query {
UserAuthenticationEntity(
UsersAuthentication.insert {
it[userId] = userAuthentication.userId
it[hash] = userAuthentication.hash
it[publicKey] = userAuthentication.publicKey
it[privateKey] = userAuthentication.privateKey
}[UsersAuthentication.id].value,userAuthentication
)
}
}
override suspend fun findById(id: Long): UserAuthenticationEntity? {
TODO("Not yet implemented")
}
override suspend fun findByUserId(id:Long):UserAuthenticationEntity? {
return query {
UsersAuthentication.select { UsersAuthentication.userId eq id }.map { it.toUserAuth() }.singleOrNull()
}
}
override suspend fun update(userAuthenticationEntity: UserAuthenticationEntity) {
TODO("Not yet implemented")
}
override suspend fun delete(id: Long) {
TODO("Not yet implemented")
}
}

View File

@ -0,0 +1,4 @@
package dev.usbharu.hideout.repository
class UserKeyRepository {
}

View File

@ -0,0 +1,93 @@
package dev.usbharu.hideout.repository
import dev.usbharu.hideout.domain.model.User
import dev.usbharu.hideout.domain.model.UserEntity
import dev.usbharu.hideout.domain.model.Users
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.transaction
class UserRepository(private val database: Database) : IUserRepository {
init {
transaction(database) {
SchemaUtils.create(Users)
}
}
private fun ResultRow.toUser(): User {
return User(
this[Users.name],
this[Users.screenName],
this[Users.description]
)
}
private fun ResultRow.toUserEntity(): UserEntity {
return UserEntity(
this[Users.id].value,
this[Users.name],
this[Users.screenName],
this[Users.description]
)
}
suspend fun <T> query(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
override suspend fun create(user: User): UserEntity {
return query {
UserEntity(Users.insert {
it[name] = user.name
it[screenName] = user.screenName
it[description] = user.description
}[Users.id].value, user)
}
}
override suspend fun findById(id: Long): UserEntity? {
return query {
Users.select { Users.id eq id }.map {
it.toUserEntity()
}.singleOrNull()
}
}
override suspend fun findByName(name: String): UserEntity? {
return query {
Users.select { Users.name eq name }.map {
it.toUserEntity()
}.singleOrNull()
}
}
override suspend fun update(userEntity: UserEntity) {
return query {
Users.update({ Users.id eq userEntity.id }) {
it[name] = userEntity.name
it[screenName] = userEntity.screenName
it[description] = userEntity.description
}
}
}
override suspend fun delete(id: Long) {
query {
Users.deleteWhere { Users.id.eq(id) }
}
}
override suspend fun findAll(): List<User> {
return query {
Users.selectAll().map { it.toUser() }
}
}
override suspend fun findAllByLimitAndByOffset(limit: Int, offset: Long): List<UserEntity> {
return query {
Users.selectAll().limit(limit, offset).map { it.toUserEntity() }
}
}
}

View File

@ -0,0 +1,45 @@
package dev.usbharu.hideout.routing
import dev.usbharu.hideout.plugins.UserSession
import dev.usbharu.hideout.plugins.tokenAuth
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
fun Application.login(){
routing {
authenticate(tokenAuth) {
post("/login") {
println("aaaaaaaaaaaaaaaaaaaaa")
val principal = call.principal<UserIdPrincipal>()
call.sessions.set(UserSession(principal!!.name))
call.respondRedirect("/users/${principal.name}")
}
}
get("/login"){
call.respondText(contentType = ContentType.Text.Html) {
//language=HTML
"""
<html>
<head>
</head>
<body>
<h2>login</h2>
<form method='POST' action=''>
<input type='text' name='username' value=''>
<input type='password' name='password'>
<input type='submit'>
</form>
</body>
</html>
""".trimIndent()
}
}
}
}

View File

@ -0,0 +1,53 @@
package dev.usbharu.hideout.routing
import dev.usbharu.hideout.plugins.UserSession
import dev.usbharu.hideout.service.IUserAuthService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
fun Application.register(userAuthService: IUserAuthService) {
routing {
get("/register") {
val principal = call.principal<UserIdPrincipal>()
if (principal != null) {
call.respondRedirect("/users/${principal.name}")
}
call.respondText(ContentType.Text.Html) {
//language=HTML
"""
<html>
<head>
</head>
<body>
<form method='post' action=''>
<input type='text' name='username' value=''>
<input type='password' name='password'>
<input type="submit">
</form>
</body>
</html>
""".trimIndent()
}
}
post("/register") {
val parameters = call.receiveParameters()
val password = parameters["password"] ?: return@post call.respondRedirect("/register")
val username = parameters["username"] ?: return@post call.respondRedirect("/register")
if (userAuthService.usernameAlreadyUse(username)) {
return@post call.respondRedirect("/register")
}
val hash = userAuthService.hash(password)
userAuthService.registerAccount(username,hash)
call.sessions.set(UserSession(username))
// call.respondRedirect("/login")
call.respondRedirect("/users/$username")
}
}
}

View File

@ -0,0 +1,81 @@
package dev.usbharu.hideout.routing
import dev.usbharu.hideout.domain.model.User
import dev.usbharu.hideout.plugins.UserSession
import dev.usbharu.hideout.plugins.respondAp
import dev.usbharu.hideout.plugins.tokenAuth
import dev.usbharu.hideout.service.ActivityPubUserService
import dev.usbharu.hideout.service.UserService
import dev.usbharu.hideout.util.HttpUtil
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
@Suppress("unused")
fun Application.user(userService: UserService,activityPubUserService: ActivityPubUserService) {
routing {
route("/users") {
authenticate( tokenAuth,optional = true) {
get {
val limit = call.request.queryParameters["limit"]?.toInt()
val offset = call.request.queryParameters["offset"]?.toLong()
val result = userService.findAll(limit, offset)
call.respond(result)
}
post {
val user = call.receive<User>()
userService.create(user)
call.response.header(
HttpHeaders.Location,
call.request.path() + "/${user.name}"
)
call.respond(HttpStatusCode.Created)
}
get("/{name}") {
val contentType = ContentType.parse(call.request.accept()?:"*/*")
val typeOfActivityPub = HttpUtil.isContentTypeOfActivityPub(
contentType.contentType,
contentType.contentSubtype,
contentType.parameter("profile").orEmpty()
)
val name = call.parameters["name"]
if (typeOfActivityPub) {
val userModel = activityPubUserService.generateUserModel(name!!)
return@get call.respondAp(userModel)
}
val principal = call.principal<UserIdPrincipal>()
if (principal != null && name != null) {
// iUserService.findByName(name)
if (principal.name == name) {
call.respondText {
principal.name
}
//todo
}
}
call.respondText {
"hello $name !!"
}
}
}
authenticate(tokenAuth) {
get("/admin"){
println("cccccccccccc "+call.principal<UserIdPrincipal>())
println("cccccccccccc "+call.principal<UserSession>())
return@get call.respondText {
"you alredy in admin !! hello " +
call.principal<UserIdPrincipal>()?.name.toString()
}
}
}
}
}
}

View File

@ -0,0 +1,79 @@
package dev.usbharu.hideout.routing
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.exception.UserNotFoundException
import dev.usbharu.hideout.service.UserService
import dev.usbharu.hideout.util.HttpUtil.Activity
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
import org.intellij.lang.annotations.Language
fun Application.wellKnown(userService: UserService) {
routing {
route("/.well-known") {
get("/host-meta") {
//language=XML
val xml = """
<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><Link rel="lrdd" type="application/xrd+xml" template="${Config.configData.hostname}/.well-known/webfinger?resource={uri}"/></XRD>
""".trimIndent()
return@get call.respondText(
contentType = ContentType("application", "xrd+xml"),
status = HttpStatusCode.OK,
text = xml
)
}
get("/host-meta.json") {
@Language("JSON") val json = """
{
"links": [
{
"rel": "lrdd",
"type": "application/jrd+json",
"template": "${Config.configData.hostname}/.well-known/webfinger?resource={uri}"
}
]
}
""".trimIndent()
return@get call.respondText(
contentType = ContentType("application", "xrd+json"),
status = HttpStatusCode.OK,
text = json
)
}
get("/webfinger") {
val uri = call.request.queryParameters["resource"] ?: return@get call.respond(
HttpStatusCode.BadRequest
)
if (uri.startsWith("acct:")) {
return@get call.respond(HttpStatusCode.BadRequest)
}
val accountName = uri.substringBeforeLast("@")
val userEntity = userService.findByName(accountName)
return@get call.respond(WebFingerResource(
subject = userEntity.name,
listOf(
WebFingerResource.Link(
rel ="self",
type = ContentType.Application.Activity.toString(),
href = "${Config.configData.hostname}/users/${userEntity.name}"
)
)
))
}
}
}
}
@Serializable
data class WebFingerResource(val subject:String,val links:List<Link>){
@Serializable
data class Link(val rel:String,val type:String,val href:String)
}

View File

@ -0,0 +1,27 @@
package dev.usbharu.hideout.routing
import io.ktor.server.application.*
import io.ktor.server.routing.*
fun Application.userActivityPubRouting(){
routing {
route("/users/{name}") {
route("/inbox"){
get {
}
post {
}
}
route("/outbox") {
get {
}
post {
}
}
}
}
}

View File

@ -0,0 +1,5 @@
package dev.usbharu.hideout.service
class ActivityPubService {
}

View File

@ -0,0 +1,28 @@
package dev.usbharu.hideout.service
import dev.usbharu.hideout.ap.Image
import dev.usbharu.hideout.ap.Person
import dev.usbharu.hideout.config.Config
class ActivityPubUserService(private val userService: UserService) {
suspend fun generateUserModel(name:String):Person{
val userEntity = userService.findByName(name)
val userUrl = "${Config.configData.hostname}/$name"
return Person(
emptyList(),
"Icon",
userUrl,
name,
userEntity.description,
"$userUrl/inbox",
"$userUrl/outbox",
userUrl,
Image(
emptyList(),
"$userUrl/icon.png",
"image/png",
"$userUrl/icon.png"
)
)
}
}

View File

@ -0,0 +1,10 @@
package dev.usbharu.hideout.service
interface IUserAuthService {
fun hash(password:String): String
suspend fun usernameAlreadyUse(username: String):Boolean
suspend fun registerAccount(username: String, hash: String)
suspend fun verifyAccount(username: String,password: String): Boolean
}

View File

@ -0,0 +1,86 @@
package dev.usbharu.hideout.service
import dev.usbharu.hideout.domain.model.User
import dev.usbharu.hideout.domain.model.UserAuthentication
import dev.usbharu.hideout.exception.UserNotFoundException
import dev.usbharu.hideout.repository.IUserAuthRepository
import dev.usbharu.hideout.repository.IUserRepository
import io.ktor.util.*
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.MessageDigest
import java.security.interfaces.RSAPrivateCrtKey
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.util.*
class UserAuthService(
val userRepository: IUserRepository,
val userAuthRepository: IUserAuthRepository
) : IUserAuthService {
override fun hash(password: String): String {
val digest = sha256.digest(password.toByteArray(Charsets.UTF_8))
return hex(digest)
}
override suspend fun usernameAlreadyUse(username: String): Boolean {
userRepository.findByName(username) ?: return false
return true
}
override suspend fun registerAccount(username: String, hash: String) {
val registerUser = User(
name = username,
screenName = username,
description = ""
)
val createdUser = userRepository.create(registerUser)
val keyPair = generateKeyPair()
val privateKey = keyPair.private as RSAPrivateKey
val publicKey = keyPair.public as RSAPublicKey
val userAuthentication = UserAuthentication(
createdUser.id,
hash,
publicKey.toPem(),
privateKey.toPem()
)
userAuthRepository.create(userAuthentication)
}
override suspend fun verifyAccount(username: String, password: String): Boolean {
val userEntity = userRepository.findByName(username)
?: throw UserNotFoundException("$username was not found")
val userAuthEntity = userAuthRepository.findByUserId(userEntity.id)
?: throw UserNotFoundException("$username auth data was not found")
return userAuthEntity.hash == hash(password)
}
private fun generateKeyPair(): KeyPair {
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
keyPairGenerator.initialize(1024)
return keyPairGenerator.generateKeyPair()
}
private fun RSAPublicKey.toPem(): String {
return "-----BEGIN RSA PUBLIC KEY-----\n" +
Base64.getEncoder().encodeToString(encoded) + "\n" +
"-----END RSA PUBLIC KEY-----"
}
private fun RSAPrivateKey.toPem(): String {
return "-----BEGIN RSA PRIVATE KEY-----\n" +
Base64.getEncoder().encodeToString(encoded) + "\n" +
"-----END RSA PRIVATE KEY-----"
}
companion object {
val sha256: MessageDigest = MessageDigest.getInstance("SHA-256")
}
}

View File

@ -0,0 +1,33 @@
package dev.usbharu.hideout.service
import dev.usbharu.hideout.domain.model.User
import dev.usbharu.hideout.domain.model.UserEntity
import dev.usbharu.hideout.exception.UserNotFoundException
import dev.usbharu.hideout.repository.IUserRepository
import dev.usbharu.hideout.repository.UserRepository
import org.jetbrains.exposed.sql.Database
import java.lang.Integer.min
class UserService(private val userRepository: IUserRepository) {
private val maxLimit = 100
suspend fun findAll(limit: Int? = maxLimit, offset: Long? = 0): List<UserEntity> {
return userRepository.findAllByLimitAndByOffset(
min(limit ?: maxLimit, maxLimit),
offset ?: 0
)
}
suspend fun findById(id: Long): UserEntity {
return userRepository.findById(id) ?: throw UserNotFoundException("$id was not found.")
}
suspend fun findByName(name:String): UserEntity {
return userRepository.findByName(name) ?: throw UserNotFoundException("$name was not found.")
}
suspend fun create(user: User): UserEntity {
return userRepository.create(user)
}
}

View File

@ -0,0 +1,28 @@
package dev.usbharu.hideout.util
import io.ktor.http.*
object HttpUtil {
fun isContentTypeOfActivityPub(
contentType: String,
subType: String,
parameter: String
): Boolean {
println("$contentType/$subType $parameter")
if (contentType != "application") {
return false
}
if (subType == "activity+json") {
return true
}
if (subType == "ld+json" && parameter == "https://www.w3.org/ns/activitystreams") {
return true
}
return false
}
val ContentType.Application.Activity: ContentType
get() = ContentType("application","activity+json")
// fun
}

View File

@ -0,0 +1,15 @@
ktor {
development = true
deployment {
port = 8080
port = ${?PORT}
watch = [classes, resources]
}
application {
modules = [dev.usbharu.hideout.ApplicationKt.module]
}
}
hideout {
hostname = "https://localhost:8080"
}

View File

@ -0,0 +1,12 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
</configuration>

View File

@ -0,0 +1,22 @@
package dev.usbharu
import dev.usbharu.hideout.plugins.configureRouting
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.Test
import kotlin.test.assertEquals
class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
configureRouting()
}
client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("Hello World!", bodyAsText())
}
}
}