├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main ├── kotlin └── work │ └── on_t │ └── w │ └── apub │ ├── ApPlugin.kt │ ├── Federation.kt │ ├── command │ ├── ApFollowCommand.kt │ ├── ApItemizeCommand.kt │ └── ApResolveCommand.kt │ ├── listener │ └── ChatListener.kt │ ├── model │ ├── Activity.kt │ ├── Actor.kt │ ├── Create.kt │ ├── Note.kt │ └── WebfingerResponse.kt │ ├── util │ ├── Chat.kt │ ├── PlayerExt.kt │ └── PublicKeyExt.kt │ └── web │ ├── ActorHandler.kt │ ├── ApHandler.kt │ ├── InboxHandler.kt │ ├── PacksHandler.kt │ └── WebfingerHandler.kt └── resources ├── config.yml ├── plugin.yml └── resourcepack └── pack.mcmeta /.gitignore: -------------------------------------------------------------------------------- 1 | # User-specific stuff 2 | .idea/ 3 | 4 | *.iml 5 | *.ipr 6 | *.iws 7 | 8 | # IntelliJ 9 | out/ 10 | # mpeltonen/sbt-idea plugin 11 | .idea_modules/ 12 | 13 | # JIRA plugin 14 | atlassian-ide-plugin.xml 15 | 16 | # Compiled class file 17 | *.class 18 | 19 | # Log file 20 | *.log 21 | 22 | # BlueJ files 23 | *.ctxt 24 | 25 | # Package Files # 26 | *.jar 27 | *.war 28 | *.nar 29 | *.ear 30 | *.zip 31 | *.tar.gz 32 | *.rar 33 | 34 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 35 | hs_err_pid* 36 | 37 | *~ 38 | 39 | # temporary files which can be created if a process still has a handle open of a deleted file 40 | .fuse_hidden* 41 | 42 | # KDE directory preferences 43 | .directory 44 | 45 | # Linux trash folder which might appear on any partition or disk 46 | .Trash-* 47 | 48 | # .nfs files are created when an open file is removed but is still being accessed 49 | .nfs* 50 | 51 | # General 52 | .DS_Store 53 | .AppleDouble 54 | .LSOverride 55 | 56 | # Icon must end with two \r 57 | Icon 58 | 59 | # Thumbnails 60 | ._* 61 | 62 | # Files that might appear in the root of a volume 63 | .DocumentRevisions-V100 64 | .fseventsd 65 | .Spotlight-V100 66 | .TemporaryItems 67 | .Trashes 68 | .VolumeIcon.icns 69 | .com.apple.timemachine.donotpresent 70 | 71 | # Directories potentially created on remote AFP share 72 | .AppleDB 73 | .AppleDesktop 74 | Network Trash Folder 75 | Temporary Items 76 | .apdisk 77 | 78 | # Windows thumbnail cache files 79 | Thumbs.db 80 | Thumbs.db:encryptable 81 | ehthumbs.db 82 | ehthumbs_vista.db 83 | 84 | # Dump file 85 | *.stackdump 86 | 87 | # Folder config file 88 | [Dd]esktop.ini 89 | 90 | # Recycle Bin used on file shares 91 | $RECYCLE.BIN/ 92 | 93 | # Windows Installer files 94 | *.cab 95 | *.msi 96 | *.msix 97 | *.msm 98 | *.msp 99 | 100 | # Windows shortcuts 101 | *.lnk 102 | 103 | .gradle 104 | build/ 105 | 106 | # Ignore Gradle GUI config 107 | gradle-app.setting 108 | 109 | # Cache of project 110 | .gradletasknamecache 111 | 112 | **/build/ 113 | 114 | # Common working directory 115 | run/ 116 | runs/ 117 | 118 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 119 | !gradle-wrapper.jar 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fuck it. activitypub in minecraft. 2 | 3 | just a quick joke for the fun of it. horribly insecure (literally no validation at all), probably kills tps. would not recommend migrating to it anytime soon 4 | 5 | supported activities: 6 | 7 | - Follow (in/out) 8 | - Accept/Follow (in/out) 9 | - Undo/Follow (in) 10 | - Create (in/out) 11 | - everything public 12 | - outgoing created object is ephemeral / unresolvable 13 | - [Bite](https://ns.mia.jetzt/as/) (in) -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") version "2.1.0" 3 | id("com.github.johnrengelman.shadow") version "8.1.1" 4 | } 5 | 6 | group = "work.on_t.w" 7 | version = "1.0-SNAPSHOT" 8 | 9 | repositories { 10 | mavenCentral() 11 | maven("https://repo.papermc.io/repository/maven-public/") { 12 | name = "papermc-repo" 13 | } 14 | maven("https://oss.sonatype.org/content/groups/public/") { 15 | name = "sonatype" 16 | } 17 | } 18 | 19 | dependencies { 20 | compileOnly("io.papermc.paper:paper-api:1.21.3-R0.1-SNAPSHOT") 21 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 22 | } 23 | 24 | val targetJavaVersion = 21 25 | kotlin { 26 | jvmToolchain(targetJavaVersion) 27 | } 28 | 29 | tasks.build { 30 | dependsOn("shadowJar") 31 | } 32 | 33 | tasks.processResources { 34 | val props = mapOf("version" to version) 35 | inputs.properties(props) 36 | filteringCharset = "UTF-8" 37 | filesMatching("plugin.yml") { 38 | expand(props) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wont-work/mcactivitypub/f96eebc8af7d3e76fbed04f12081670bc91aac11/gradle.properties -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wont-work/mcactivitypub/f96eebc8af7d3e76fbed04f12081670bc91aac11/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "mcactivitypub" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/ApPlugin.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub 2 | 3 | import com.google.common.io.BaseEncoding 4 | import com.google.gson.Gson 5 | import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents 6 | import org.bukkit.persistence.PersistentDataContainer 7 | import org.bukkit.plugin.java.JavaPlugin 8 | import work.on_t.w.apub.command.ApFollowCommand 9 | import work.on_t.w.apub.command.ApItemizeCommand 10 | import work.on_t.w.apub.command.ApResolveCommand 11 | import work.on_t.w.apub.listener.ChatListener 12 | import work.on_t.w.apub.web.ApHandler 13 | import java.io.FileNotFoundException 14 | import java.security.KeyFactory 15 | import java.security.KeyPairGenerator 16 | import java.security.PrivateKey 17 | import java.security.PublicKey 18 | import java.security.interfaces.RSAPrivateCrtKey 19 | import java.security.spec.PKCS8EncodedKeySpec 20 | import java.security.spec.RSAPublicKeySpec 21 | 22 | class ApPlugin : JavaPlugin() { 23 | val base32 = BaseEncoding.base32().omitPadding() 24 | val gson = Gson() 25 | val persistentDataContainer: PersistentDataContainer by lazy { server.worlds.first().persistentDataContainer } 26 | val root: String by lazy { "https://${host}" } 27 | 28 | lateinit var privateKey: PrivateKey 29 | lateinit var publicKey: PublicKey 30 | lateinit var host: String 31 | 32 | private fun loadKeypair() { 33 | val keyFile = dataFolder.resolve("rsa.key") 34 | 35 | try { 36 | val key = PKCS8EncodedKeySpec(keyFile.readBytes()) 37 | val kf = KeyFactory.getInstance("RSA") 38 | val pk = kf.generatePrivate(key) as RSAPrivateCrtKey 39 | 40 | logger.info("Loaded RSA key") 41 | privateKey = pk 42 | publicKey = kf.generatePublic(RSAPublicKeySpec(pk.modulus, pk.publicExponent, pk.params)) 43 | } catch (e: FileNotFoundException) { 44 | val kg = KeyPairGenerator.getInstance("RSA") 45 | kg.initialize(2048) // lowest size accepted by all instance software 46 | val kp = kg.genKeyPair() 47 | keyFile.writeBytes(kp.private.encoded) 48 | 49 | logger.info("Generated RSA key") 50 | privateKey = kp.private 51 | publicKey = kp.public 52 | } 53 | } 54 | 55 | override fun onEnable() { 56 | saveDefaultConfig() 57 | host = config.getString("host")!! 58 | 59 | loadKeypair() 60 | ApHandler.start(this) 61 | 62 | server.pluginManager.registerEvents(ChatListener(this), this) 63 | 64 | lifecycleManager.registerEventHandler(LifecycleEvents.COMMANDS) { 65 | val registrar = it.registrar() 66 | registrar.register("apresolve", "Resolve AP object", ApResolveCommand(this)) 67 | registrar.register("apfolllow", "Follow AP user", ApFollowCommand(this)) 68 | registrar.register("apitemize", "Itemize AP user", ApItemizeCommand(this)) 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/Federation.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub 2 | 3 | import com.google.gson.JsonElement 4 | import com.google.gson.JsonObject 5 | import com.google.gson.JsonParser 6 | import org.bukkit.NamespacedKey 7 | import org.bukkit.entity.Player 8 | import org.bukkit.persistence.PersistentDataType 9 | import work.on_t.w.apub.model.WebfingerResponse 10 | import work.on_t.w.apub.util.getApFollowers 11 | import work.on_t.w.apub.util.getApId 12 | import java.net.HttpURLConnection 13 | import java.net.URI 14 | import java.security.MessageDigest 15 | import java.security.Signature 16 | import java.time.LocalDateTime 17 | import java.time.ZoneId 18 | import java.time.format.DateTimeFormatter 19 | import java.util.* 20 | import kotlin.io.encoding.Base64 21 | import kotlin.io.encoding.ExperimentalEncodingApi 22 | 23 | fun apResolve(plugin: ApPlugin, object_: JsonElement, player: Player? = null): JsonObject { 24 | if (object_.isJsonObject) return object_.asJsonObject 25 | return apResolve(plugin, object_.asString, player) 26 | } 27 | 28 | fun apResolve(plugin: ApPlugin, object_: String, player: Player? = null): JsonObject { 29 | val sha384 = MessageDigest.getInstance("SHA-384") 30 | sha384.update(object_.encodeToByteArray()) 31 | val key = NamespacedKey(plugin, "cache/${plugin.base32.encode(sha384.digest())}") 32 | 33 | var cached = plugin.persistentDataContainer.get(key, PersistentDataType.STRING) 34 | if (cached == null) { 35 | plugin.logger.info("Resolving AP object: ${object_}") 36 | 37 | val req = URI(object_).toURL().openConnection() as HttpURLConnection 38 | req.requestMethod = "GET" 39 | req.setRequestProperty( 40 | "Accept", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"" 41 | ) 42 | 43 | var player = player ?: plugin.server.onlinePlayers.firstOrNull() 44 | if (player != null) httpSign(plugin, req, player) 45 | 46 | cached = req.inputStream.readAllBytes().decodeToString() 47 | plugin.persistentDataContainer.set(key, PersistentDataType.STRING, cached) 48 | } 49 | 50 | return JsonParser.parseString(cached).asJsonObject 51 | } 52 | 53 | fun apPost(plugin: ApPlugin, player: Player, inbox: String, body: ByteArray) { 54 | plugin.logger.info("POSTing to inbox: ${inbox}") 55 | 56 | val req = URI(inbox).toURL().openConnection() as HttpURLConnection 57 | req.requestMethod = "POST" 58 | req.setRequestProperty( 59 | "Content-Type", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"" 60 | ) 61 | 62 | httpSign(plugin, req, player, body) 63 | req.doOutput = true 64 | req.outputStream.write(body) 65 | 66 | if (req.responseCode >= 300) plugin.logger.warning("An error occured: ${req.responseMessage}") 67 | } 68 | 69 | val httpDateFormatter = 70 | DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).withZone(ZoneId.of("GMT"))!! 71 | 72 | @OptIn(ExperimentalEncodingApi::class) 73 | fun httpSign(plugin: ApPlugin, req: HttpURLConnection, player: Player, body: ByteArray? = null) { 74 | val date = LocalDateTime.now().format(httpDateFormatter) 75 | 76 | req.setRequestProperty("Host", req.url.host) 77 | req.setRequestProperty("Date", date) 78 | 79 | val headers = arrayListOf("(request-target)", "host", "date") 80 | if (body != null) headers.add("digest") 81 | 82 | val rsa = Signature.getInstance("SHA256withRSA") 83 | rsa.initSign(plugin.privateKey) 84 | rsa.update("(request-target): ${req.requestMethod.lowercase()} ${req.url.path}\nhost: ${req.url.host}\ndate: ${date}".encodeToByteArray()) 85 | if (headers.contains("digest")) { 86 | val sha256 = MessageDigest.getInstance("SHA-256") 87 | sha256.update(body) 88 | val digest = "SHA-256=${Base64.encode(sha256.digest())}" 89 | 90 | rsa.update("\ndigest: ${digest}".encodeToByteArray()) 91 | req.setRequestProperty("Digest", digest) 92 | } 93 | 94 | // @formatter:off 95 | req.setRequestProperty( 96 | "Signature", 97 | "keyId=\"${player.getApId(plugin)}#rsa-key\"," + 98 | "algorithm=\"rsa-sha256\"," + 99 | "headers=\"${headers.joinToString(" ")}\"," + 100 | "signature=\"${Base64.encode(rsa.sign())}\"" 101 | ) 102 | // @formatter:on 103 | } 104 | 105 | fun apBroadcast(plugin: ApPlugin, player: Player, activity: JsonObject) { 106 | val followers = player.getApFollowers(plugin) 107 | if (followers.isEmpty()) return 108 | 109 | // @formatter:off 110 | val inboxes = followers 111 | .map { apResolve(plugin, it) } 112 | .map { it["endpoints"]?.asJsonObject?.get("sharedInbox")?.asString ?: it["inbox"].asString } 113 | .distinct() 114 | // @formatter:on 115 | 116 | for (inbox in inboxes) { 117 | apPost(plugin, player, inbox, plugin.gson.toJson(activity).encodeToByteArray()) 118 | } 119 | } 120 | 121 | fun webfingerResolve(plugin: ApPlugin, handle: String): String? { 122 | val handle = handle.trimStart('@') 123 | 124 | val sha384 = MessageDigest.getInstance("SHA-384") 125 | sha384.update(handle.encodeToByteArray()) 126 | val key = NamespacedKey(plugin, "cache/webfinger/${plugin.base32.encode(sha384.digest())}") 127 | 128 | var cached = plugin.persistentDataContainer.get(key, PersistentDataType.STRING) 129 | if (cached == null) { 130 | plugin.logger.info("Resolving Webfinger handle: ${handle}") 131 | 132 | val (_, host) = handle.split('@', limit = 2) 133 | 134 | val req = URI("https://$host/.well-known/webfinger?resource=acct:$handle").toURL() 135 | .openConnection() as HttpURLConnection 136 | req.requestMethod = "GET" 137 | req.setRequestProperty("Accept", "application/jrd+json") 138 | 139 | val response = plugin.gson.fromJson(req.inputStream.bufferedReader(), WebfingerResponse::class.java) 140 | cached = response.links.firstOrNull { it.rel == "self" && it.type == "application/activity+json" || it.type == "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"" }?.href 141 | 142 | if (cached != null) plugin.persistentDataContainer.set(key, PersistentDataType.STRING, cached) 143 | else plugin.persistentDataContainer.remove(key) 144 | } 145 | 146 | return cached 147 | } 148 | -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/command/ApFollowCommand.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.command 2 | 3 | import io.papermc.paper.command.brigadier.BasicCommand 4 | import io.papermc.paper.command.brigadier.CommandSourceStack 5 | import net.kyori.adventure.text.Component 6 | import org.bukkit.entity.Player 7 | import work.on_t.w.apub.ApPlugin 8 | import work.on_t.w.apub.apPost 9 | import work.on_t.w.apub.apResolve 10 | import work.on_t.w.apub.model.Activity 11 | import work.on_t.w.apub.util.getApId 12 | import work.on_t.w.apub.util.renderHandle 13 | import work.on_t.w.apub.webfingerResolve 14 | 15 | class ApFollowCommand(private val plugin: ApPlugin) : BasicCommand { 16 | override fun execute(source: CommandSourceStack, args: Array) { 17 | val player = source.sender as? Player 18 | if (player == null) { 19 | source.sender.sendMessage("Only players can follow") 20 | return 21 | } 22 | 23 | if (args.size != 1) { 24 | source.sender.sendMessage("/apfollow <@username@server>") 25 | return 26 | } 27 | 28 | val id = webfingerResolve(plugin, args.first()) 29 | if (id == null) { 30 | source.sender.sendMessage("Could not resolve handle") 31 | return 32 | } 33 | 34 | val actor = apResolve(plugin, id, player) 35 | 36 | val playerId = player.getApId(plugin) 37 | val response = plugin.gson.toJson( 38 | Activity( 39 | context = arrayOf("https://www.w3.org/ns/activitystreams"), 40 | id = "${playerId}/follow/${System.currentTimeMillis()}", 41 | to = arrayOf(actor["id"].asString), 42 | type = "Follow", 43 | actor = playerId, 44 | object_ = actor["id"] 45 | ) 46 | ) 47 | 48 | apPost(plugin, player, actor["inbox"].asString, response.encodeToByteArray()) 49 | source.sender.sendMessage(Component.text("Follow request sent to ").append(renderHandle(actor))) 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/command/ApItemizeCommand.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.command 2 | 3 | import io.papermc.paper.command.brigadier.BasicCommand 4 | import io.papermc.paper.command.brigadier.CommandSourceStack 5 | import net.kyori.adventure.resource.ResourcePackInfo 6 | import net.kyori.adventure.resource.ResourcePackRequest 7 | import net.kyori.adventure.text.Component 8 | import org.bukkit.Material 9 | import org.bukkit.NamespacedKey 10 | import org.bukkit.entity.Player 11 | import org.bukkit.inventory.ItemStack 12 | import org.bukkit.persistence.PersistentDataType 13 | import work.on_t.w.apub.ApPlugin 14 | import work.on_t.w.apub.apResolve 15 | import work.on_t.w.apub.util.renderHandle 16 | import work.on_t.w.apub.webfingerResolve 17 | import java.awt.Color 18 | import java.awt.image.BufferedImage 19 | import java.net.URI 20 | import java.nio.file.FileSystems 21 | import java.nio.file.Files 22 | import java.security.MessageDigest 23 | import javax.imageio.ImageIO 24 | import kotlin.io.path.createParentDirectories 25 | import kotlin.io.path.outputStream 26 | import kotlin.random.Random 27 | 28 | 29 | const val ITEM_JSON = """{ 30 | "parent": "minecraft:item/generated", 31 | "textures": { 32 | "layer0": "mcactivitypub:item/{}" 33 | } 34 | }""" 35 | 36 | const val OVERRIDE_JSON = """{ 37 | "parent": "minecraft:item/generated", 38 | "textures": { 39 | "layer0": "minecraft:block/dead_bush" 40 | }, 41 | "overrides": [ 42 | { "predicate": { "custom_model_data": {} }, "model": "mcactivitypub:item/{}" } 43 | ] 44 | }""" 45 | 46 | class ApItemizeCommand(private val plugin: ApPlugin) : BasicCommand { 47 | override fun execute(source: CommandSourceStack, args: Array) { 48 | val player = source.sender as? Player 49 | if (player == null) { 50 | source.sender.sendMessage("Only players can itemize") 51 | return 52 | } 53 | 54 | if (args.size != 1) { 55 | source.sender.sendMessage("/apitemize <@username@server>") 56 | return 57 | } 58 | 59 | val id = webfingerResolve(plugin, args.first()) 60 | if (id == null) { 61 | source.sender.sendMessage("Could not resolve handle") 62 | return 63 | } 64 | 65 | val actor = apResolve(plugin, id, player) 66 | val item = ItemStack.of(Material.DEAD_BUSH, 1) 67 | 68 | val ikey = NamespacedKey(plugin, "item/${actor["preferredUsername"].asString}.${URI(id).authority}") 69 | var customModelData = plugin.persistentDataContainer.get(ikey, PersistentDataType.INTEGER) 70 | if (customModelData == null) { 71 | customModelData = Random.nextInt() 72 | plugin.persistentDataContainer.set(ikey, PersistentDataType.INTEGER, customModelData) 73 | } 74 | 75 | val avatar = actor["icon"].asJsonObject["url"].asString 76 | val pack = generatePack(customModelData, URI(avatar)) 77 | player.sendResourcePacks( 78 | ResourcePackRequest.resourcePackRequest().packs(pack) 79 | .prompt(Component.text("Finish the itemization process")).required(true).build() 80 | ) 81 | 82 | item.itemMeta = item.itemMeta.apply { 83 | itemName(renderHandle(actor)) 84 | setCustomModelData(customModelData) 85 | persistentDataContainer.set(NamespacedKey(plugin, "actor"), PersistentDataType.STRING, id) 86 | } 87 | 88 | player.inventory.addItem(item) 89 | } 90 | 91 | @OptIn(ExperimentalStdlibApi::class) 92 | fun generatePack(id: Int, textureUrl: URI): ResourcePackInfo { 93 | val path = plugin.dataFolder.resolve("./packs/$id.zip") 94 | val pkey = NamespacedKey(plugin, "pack-hash/$id") 95 | 96 | if (!path.exists()) { 97 | plugin.persistentDataContainer.remove(pkey) 98 | path.parentFile.mkdirs() 99 | 100 | plugin.logger.info("Downloading $textureUrl for pack $id") 101 | textureUrl.toURL().openStream().use { texStream -> 102 | val texImage = ImageIO.read(texStream) 103 | 104 | FileSystems.newFileSystem(URI("jar:file:${path.absolutePath}"), hashMapOf(Pair("create", "true"))) 105 | .use { zip -> 106 | Files.copy(plugin.getResource("resourcepack/pack.mcmeta")!!, zip.getPath("pack.mcmeta")) 107 | 108 | val override = zip.getPath("assets/minecraft/models/item/dead_bush.json") 109 | override.createParentDirectories() 110 | Files.writeString(override, OVERRIDE_JSON.replace("{}", id.toString())) 111 | 112 | val model = zip.getPath("assets/mcactivitypub/models/item/$id.json") 113 | model.createParentDirectories() 114 | Files.writeString(model, ITEM_JSON.replace("{}", id.toString())) 115 | 116 | val texture = zip.getPath("assets/mcactivitypub/textures/item/$id.png") 117 | texture.createParentDirectories() 118 | texture.outputStream().use { ImageIO.write(texImage, "png", it) } 119 | } 120 | } 121 | } 122 | 123 | var hash = plugin.persistentDataContainer.get(pkey, PersistentDataType.STRING) 124 | if (hash == null) { 125 | val sha1 = MessageDigest.getInstance("SHA-1") 126 | sha1.update(path.readBytes()) 127 | hash = sha1.digest().toHexString() 128 | plugin.persistentDataContainer.set(pkey, PersistentDataType.STRING, hash) 129 | } 130 | 131 | return ResourcePackInfo.resourcePackInfo().uri(URI("${plugin.root}/packs/$id")).hash(hash).build() 132 | } 133 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/command/ApResolveCommand.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.command 2 | 3 | import io.papermc.paper.command.brigadier.BasicCommand 4 | import io.papermc.paper.command.brigadier.CommandSourceStack 5 | import org.bukkit.entity.Player 6 | import work.on_t.w.apub.ApPlugin 7 | import work.on_t.w.apub.apResolve 8 | 9 | class ApResolveCommand(private val plugin: ApPlugin) : BasicCommand { 10 | override fun execute(source: CommandSourceStack, args: Array) { 11 | if (args.size != 1) { 12 | source.sender.sendMessage("/apresolve ") 13 | return 14 | } 15 | 16 | val obj = apResolve(plugin, args.first(), source.sender as? Player) 17 | source.sender.sendMessage(obj.toString()) 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/listener/ChatListener.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.listener 2 | 3 | import io.papermc.paper.event.player.AsyncChatEvent 4 | import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer 5 | import org.bukkit.event.EventHandler 6 | import org.bukkit.event.EventPriority 7 | import org.bukkit.event.Listener 8 | import work.on_t.w.apub.ApPlugin 9 | import work.on_t.w.apub.apBroadcast 10 | import work.on_t.w.apub.model.Create 11 | import work.on_t.w.apub.model.Note 12 | import work.on_t.w.apub.util.getApId 13 | import java.time.Instant 14 | 15 | class ChatListener(private val plugin: ApPlugin) : Listener { 16 | @EventHandler(priority = EventPriority.MONITOR) 17 | fun onAsyncChat(event: AsyncChatEvent) { 18 | val playerId = event.player.getApId(plugin) 19 | val noteId = "${playerId}/note/${System.currentTimeMillis()}" 20 | val activity = Create( 21 | context = arrayOf("https://www.w3.org/ns/activitystreams"), 22 | id = "$noteId/activity", 23 | type = "Create", 24 | actor = playerId, 25 | object_ = Note( 26 | context = arrayOf("https://www.w3.org/ns/activitystreams"), 27 | id = noteId, 28 | type = "Note", 29 | to = arrayOf("https://www.w3.org/ns/activitystreams#Public"), 30 | attributedTo = playerId, 31 | content = PlainTextComponentSerializer.plainText().serialize(event.message()), 32 | published = Instant.now().toString() 33 | ) 34 | ) 35 | 36 | apBroadcast(plugin, event.player, plugin.gson.toJsonTree(activity).asJsonObject) 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/model/Activity.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.model 2 | 3 | import com.google.gson.JsonElement 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Activity( 7 | @SerializedName("@context") val context: Array, 8 | val id: String, 9 | val to: Array, 10 | val type: String, 11 | val actor: String, 12 | @SerializedName("object") val object_: JsonElement 13 | ) -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/model/Actor.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.model 2 | 3 | import com.google.gson.annotations.SerializedName 4 | 5 | data class Actor( 6 | @SerializedName("@context") val context: Array, 7 | val id: String, 8 | val type: String, 9 | val preferredUsername: String, 10 | val name: String, 11 | val inbox: String, 12 | val publicKey: ActorPublicKey, 13 | val endpoints: ActorEndpoints 14 | ) { 15 | data class ActorPublicKey(val id: String, val owner: String, val publicKeyPem: String) 16 | data class ActorEndpoints(val sharedInbox: String) 17 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/model/Create.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.model 2 | 3 | import com.google.gson.annotations.SerializedName 4 | 5 | data class Create( 6 | @SerializedName("@context") val context: Array, 7 | val id: String, 8 | val type: String, 9 | val actor: String, 10 | @SerializedName("object") val object_: Note 11 | ) -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/model/Note.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.model 2 | 3 | import com.google.gson.annotations.SerializedName 4 | import java.time.Instant 5 | 6 | data class Note( 7 | @SerializedName("@context") val context: Array, 8 | val id: String, 9 | val type: String, 10 | val to: Array, 11 | val attributedTo: String, 12 | val content: String, 13 | val published: String 14 | ) -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/model/WebfingerResponse.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.model 2 | 3 | data class WebfingerResponse(val subject: String, val links: Array) { 4 | data class WebfingerLink(val rel: String, val type: String, val href: String) 5 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/util/Chat.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.util 2 | 3 | import com.google.gson.JsonObject 4 | import net.kyori.adventure.text.Component 5 | import net.kyori.adventure.text.TextComponent 6 | import net.kyori.adventure.text.event.ClickEvent 7 | import net.kyori.adventure.text.format.TextColor 8 | import java.net.URI 9 | 10 | fun renderHandle(actor: JsonObject): TextComponent { 11 | val actorId = actor["id"].asString 12 | val actorUrl = actor["url"]?.asString ?: actorId 13 | 14 | return Component.text(actor["preferredUsername"].asString) 15 | .append( 16 | Component.text("@${URI(actorId).authority}") 17 | .color(TextColor.color(0xBEBEBE))) 18 | .clickEvent(ClickEvent.openUrl(actorUrl)) 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/util/PlayerExt.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.util 2 | 3 | import org.bukkit.NamespacedKey 4 | import org.bukkit.entity.Player 5 | import org.bukkit.persistence.PersistentDataType 6 | import work.on_t.w.apub.ApPlugin 7 | 8 | fun Player.getApId(plugin: ApPlugin) = "${plugin.root}/players/${this.uniqueId}" 9 | 10 | fun Player.updateSavedApFollowerData(plugin: ApPlugin, lambda: (HashSet) -> Unit) { 11 | val key = NamespacedKey(plugin, "followers") 12 | val followers = this.persistentDataContainer.getOrDefault(key, PersistentDataType.STRING, "").split(',').toHashSet() 13 | lambda(followers) 14 | this.persistentDataContainer.set(key, PersistentDataType.STRING, followers.joinToString(",")) 15 | } 16 | 17 | fun Player.updateSavedApFollowingData(plugin: ApPlugin, lambda: (HashSet) -> Unit) { 18 | val key = NamespacedKey(plugin, "following") 19 | val followers = this.persistentDataContainer.getOrDefault(key, PersistentDataType.STRING, "").split(',').toHashSet() 20 | lambda(followers) 21 | this.persistentDataContainer.set(key, PersistentDataType.STRING, followers.joinToString(",")) 22 | } 23 | 24 | // @formatter:off 25 | fun Player.getApFollowers(plugin: ApPlugin) = 26 | this.persistentDataContainer 27 | .getOrDefault(NamespacedKey(plugin, "followers"), PersistentDataType.STRING, "") 28 | .split(',') 29 | .toSet() 30 | // @formatter:on 31 | -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/util/PublicKeyExt.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.util 2 | 3 | import java.security.PublicKey 4 | import kotlin.io.encoding.Base64 5 | import kotlin.io.encoding.ExperimentalEncodingApi 6 | 7 | @OptIn(ExperimentalEncodingApi::class) 8 | fun PublicKey.toPem() = Base64.encode(this.encoded).chunked(64) 9 | .joinToString("\n", "-----BEGIN PUBLIC KEY-----\n", "\n-----END PUBLIC KEY-----\n") 10 | -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/web/ActorHandler.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.web 2 | 3 | import com.sun.net.httpserver.HttpExchange 4 | import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer 5 | import work.on_t.w.apub.ApPlugin 6 | import work.on_t.w.apub.model.Actor 7 | import work.on_t.w.apub.util.getApId 8 | import work.on_t.w.apub.util.toPem 9 | import java.util.* 10 | 11 | class ActorHandler(private val plugin: ApPlugin) { 12 | fun handle(req: HttpExchange) { 13 | val (uuidStr, _) = req.requestURI.path.removePrefix("/players/").split('/', limit = 2) 14 | plugin.logger.info("Received GET for player $uuidStr") 15 | 16 | val uuid = UUID.fromString(uuidStr) 17 | val player = plugin.server.getPlayer(uuid) 18 | if (player == null) { 19 | req.sendResponseHeaders(404, -1) 20 | return 21 | } 22 | 23 | val id = player.getApId(plugin) 24 | val response = plugin.gson.toJson( 25 | Actor( 26 | context = arrayOf("https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"), 27 | id = id, 28 | type = "Person", 29 | preferredUsername = player.name, 30 | name = PlainTextComponentSerializer.plainText().serialize(player.displayName()), 31 | inbox = "${plugin.root}/inbox", 32 | publicKey = Actor.ActorPublicKey( 33 | id = "${id}#rsa-key", owner = id, publicKeyPem = plugin.publicKey.toPem() 34 | ), 35 | endpoints = Actor.ActorEndpoints(sharedInbox = "${plugin.root}/inbox") 36 | ) 37 | ) 38 | 39 | req.responseHeaders.set("content-type", "application/activity+json; charset=utf-8") 40 | req.sendResponseHeaders(200, response.length.toLong()) 41 | req.responseBody.write(response.encodeToByteArray()) 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/web/ApHandler.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.web 2 | 3 | import com.sun.net.httpserver.HttpExchange 4 | import com.sun.net.httpserver.HttpHandler 5 | import com.sun.net.httpserver.HttpServer 6 | import work.on_t.w.apub.ApPlugin 7 | import java.net.InetSocketAddress 8 | 9 | class ApHandler private constructor(plugin: ApPlugin) : HttpHandler { 10 | private val webfingerHandler = WebfingerHandler(plugin) 11 | private val actorHandler = ActorHandler(plugin) 12 | private val inboxHandler = InboxHandler(plugin) 13 | private val packsHandler = PacksHandler(plugin) 14 | 15 | companion object { 16 | fun start(plugin: ApPlugin) { 17 | val port = plugin.config.getInt("port") 18 | val server = HttpServer.create(InetSocketAddress(port), 0) 19 | server.createContext("/", ApHandler(plugin)) 20 | server.executor = null 21 | server.start() 22 | 23 | plugin.logger.info("Started web server on port :${port} (https://${plugin.host})") 24 | } 25 | } 26 | 27 | override fun handle(req: HttpExchange) { 28 | try { 29 | if (req.requestMethod == "GET" && req.requestURI.path == "/.well-known/webfinger") { 30 | webfingerHandler.handle(req) 31 | } else if (req.requestMethod == "GET" && req.requestURI.path.startsWith("/players/")) { 32 | actorHandler.handle(req) 33 | } else if (req.requestMethod == "GET" && req.requestURI.path.startsWith("/packs/")) { 34 | packsHandler.handle(req) 35 | } else if (req.requestMethod == "POST") { 36 | inboxHandler.handle(req) 37 | } else { 38 | req.sendResponseHeaders(404, -1) 39 | } 40 | } catch (exc: Exception) { 41 | exc.printStackTrace() 42 | val trace = exc.stackTraceToString().encodeToByteArray() 43 | 44 | req.responseHeaders.set("content-type", "text/plain; charset=utf-8") 45 | req.sendResponseHeaders(500, trace.size.toLong()) 46 | req.responseBody.write(trace) 47 | } 48 | 49 | req.responseBody.close() 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/web/InboxHandler.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.web 2 | 3 | import com.google.gson.JsonObject 4 | import com.google.gson.JsonParser 5 | import com.sun.net.httpserver.HttpExchange 6 | import net.kyori.adventure.text.Component 7 | import org.bukkit.scheduler.BukkitRunnable 8 | import work.on_t.w.apub.ApPlugin 9 | import work.on_t.w.apub.apPost 10 | import work.on_t.w.apub.apResolve 11 | import work.on_t.w.apub.model.Activity 12 | import work.on_t.w.apub.util.getApId 13 | import work.on_t.w.apub.util.renderHandle 14 | import work.on_t.w.apub.util.updateSavedApFollowerData 15 | import work.on_t.w.apub.util.updateSavedApFollowingData 16 | import java.util.* 17 | 18 | // janky hack to clean up all html tags from content 19 | val htmlTagRegex = Regex("<.*?>") 20 | 21 | class InboxHandler(private val plugin: ApPlugin) { 22 | fun handle(req: HttpExchange) { 23 | handleActivity(JsonParser.parseReader(req.requestBody.bufferedReader()).asJsonObject) 24 | 25 | req.sendResponseHeaders(200, -1) 26 | } 27 | 28 | private fun handleActivity(activity: JsonObject) { 29 | val id = activity["id"].asString 30 | val type = activity["type"].asString 31 | val actor = activity["actor"].asString 32 | 33 | plugin.logger.info("Received $type activity: $id") 34 | if (actor.startsWith(plugin.root)) return 35 | 36 | if (type == "Follow") { 37 | val object_ = activity["object"].asString 38 | 39 | val uuidStr = object_.removePrefix("${plugin.root}/players/") 40 | if (uuidStr == object_) return // prefix didn't exist in string 41 | val uuid = UUID.fromString(uuidStr) 42 | val player = plugin.server.getPlayer(uuid) ?: return 43 | val resolved = apResolve(plugin, actor) 44 | 45 | val playerId = player.getApId(plugin) 46 | val response = plugin.gson.toJson( 47 | Activity( 48 | context = arrayOf("https://www.w3.org/ns/activitystreams"), 49 | id = "${playerId}/accept/${System.currentTimeMillis()}", 50 | to = arrayOf(actor), 51 | type = "Accept", 52 | actor = playerId, 53 | object_ = activity 54 | ) 55 | ) 56 | apPost(plugin, player, resolved["inbox"].asString, response.encodeToByteArray()) 57 | 58 | player.updateSavedApFollowerData(plugin) { it.add(actor) } 59 | player.sendMessage(renderHandle(resolved).append(Component.text(" is now following you"))) 60 | } else if (type == "Accept") { 61 | val inner = activity["object"].asJsonObject 62 | val innerType = inner["type"].asString 63 | 64 | if (innerType == "Follow") { 65 | val object_ = inner["actor"].asString 66 | val uuidStr = object_.removePrefix("${plugin.root}/players/") 67 | if (uuidStr == object_) return // prefix didn't exist in string 68 | val uuid = UUID.fromString(uuidStr) 69 | val player = plugin.server.getPlayer(uuid) ?: return 70 | val resolved = apResolve(plugin, actor) 71 | 72 | player.updateSavedApFollowingData(plugin) { it.add(actor) } 73 | player.sendMessage(renderHandle(resolved).append(Component.text(" accepted your follow request"))) 74 | } 75 | } else if (type == "Undo") { 76 | val inner = activity["object"].asJsonObject 77 | val innerType = inner["type"].asString 78 | 79 | if (innerType == "Follow") { 80 | val object_ = inner["object"].asString 81 | val uuidStr = object_.removePrefix("${plugin.root}/players/") 82 | if (uuidStr == object_) return // prefix didn't exist in string 83 | val uuid = UUID.fromString(uuidStr) 84 | val player = plugin.server.getPlayer(uuid) ?: return 85 | val resolved = apResolve(plugin, actor) 86 | 87 | player.updateSavedApFollowerData(plugin) { it.remove(actor) } 88 | player.sendMessage(renderHandle(resolved).append(Component.text(" is no longer following you"))) 89 | } 90 | } else if (type == "Create") { 91 | val object_ = apResolve(plugin, activity["object"]) 92 | val actor = apResolve(plugin, object_["attributedTo"]) 93 | val content = object_["content"].asString.replace(htmlTagRegex, "") 94 | 95 | // @formatter:off 96 | plugin.server.broadcast( 97 | Component.text("<") 98 | .append(renderHandle(actor)) 99 | .append(Component.text("> ")) 100 | .append(Component.text(content)) 101 | ) 102 | // @formatter:on 103 | } else if (type == "Bite") { 104 | val target = activity["to"].asJsonArray.firstOrNull()?.asString ?: return 105 | 106 | val (uuidStr) = target.removePrefix("${plugin.root}/players/").split('/', limit = 2) 107 | if (uuidStr == target) return // prefix didn't exist in string 108 | val uuid = UUID.fromString(uuidStr) 109 | val player = plugin.server.getPlayer(uuid) ?: return 110 | val resolved = apResolve(plugin, actor) 111 | 112 | object : BukkitRunnable() { 113 | override fun run() { 114 | player.damage(1.0) 115 | player.sendMessage(renderHandle(resolved).append(Component.text(" bit you"))) 116 | } 117 | }.runTask(plugin) 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/web/PacksHandler.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.web 2 | 3 | import com.sun.net.httpserver.HttpExchange 4 | import work.on_t.w.apub.ApPlugin 5 | 6 | class PacksHandler(private val plugin: ApPlugin) { 7 | fun handle(req: HttpExchange) { 8 | val (pack, _) = req.requestURI.path.removePrefix("/packs/").split('/', limit = 2) 9 | plugin.logger.info("Received GET for resource pack $pack") 10 | 11 | val packFile = plugin.dataFolder.resolve("./packs/$pack.zip") 12 | if (!packFile.exists()) { 13 | req.sendResponseHeaders(404, -1) 14 | return 15 | } 16 | 17 | packFile.inputStream().use { packStream -> 18 | req.sendResponseHeaders(200, 0) 19 | req.responseBody.write(packStream.readBytes()) 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/work/on_t/w/apub/web/WebfingerHandler.kt: -------------------------------------------------------------------------------- 1 | package work.on_t.w.apub.web 2 | 3 | import com.sun.net.httpserver.HttpExchange 4 | import work.on_t.w.apub.ApPlugin 5 | import work.on_t.w.apub.model.WebfingerResponse 6 | import work.on_t.w.apub.util.getApId 7 | 8 | 9 | class WebfingerHandler(val plugin: ApPlugin) { 10 | fun handle(req: HttpExchange) { 11 | val resource = req.requestURI.query.removePrefix("resource=") 12 | 13 | val (username, _) = resource.removePrefix("acct:").split('@', limit = 2) 14 | plugin.logger.info("Received webfinger request for $username") 15 | 16 | val player = plugin.server.getPlayerExact(username) 17 | if (player == null) { 18 | req.sendResponseHeaders(404, -1) 19 | return 20 | } 21 | 22 | val response = plugin.gson.toJson( 23 | WebfingerResponse( 24 | subject = "acct:${player.name}@${plugin.host}", links = arrayOf( 25 | WebfingerResponse.WebfingerLink( 26 | rel = "self", type = "application/activity+json", href = player.getApId(plugin) 27 | ) 28 | ) 29 | ) 30 | ) 31 | 32 | req.responseHeaders.set("content-type", "application/jrd+json; charset=utf-8") 33 | req.sendResponseHeaders(200, response.length.toLong()) 34 | req.responseBody.write(response.encodeToByteArray()) 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | host: localhost:8000 2 | port: 8000 -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: mcactivitypub 2 | version: '1.0-SNAPSHOT' 3 | main: work.on_t.w.apub.ApPlugin 4 | api-version: '1.21' -------------------------------------------------------------------------------- /src/main/resources/resourcepack/pack.mcmeta: -------------------------------------------------------------------------------- 1 | { 2 | "pack": { 3 | "description": "dynamically generated", 4 | "pack_format": 42 5 | } 6 | } 7 | --------------------------------------------------------------------------------