Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .pnlibrary/releases.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"schema": 1,
"product": "pnauth",
"releases": []
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,55 @@ package ru.privatenull.pnauth.bungee
import net.md_5.bungee.api.plugin.Plugin
import ru.privatenull.pnauth.api.AuthApi
import ru.privatenull.pnauth.bungee.proxy.BungeeProxyAdapter
import org.pnfolder.pnlibrary.bungee.bootstrap.PnLibraryBootstrap
import ru.privatenull.pnauth.integration.PnLibraryRuntime
import ru.privatenull.pnauth.kernel.ExtensionKernel
import ru.privatenull.pnauth.platform.Platform
import java.util.logging.Level

class PnAuthBungeePlugin : Plugin() {
private var runtime: PnAuthBungeeRuntime? = null
private var pnLibraryReady = false
private var pnLibrary: PnLibraryRuntime? = null

override fun onLoad() {
// A missing pnLibrary is downloaded for the next start; pnAuth itself keeps working without it.
pnLibraryReady = try {
PnLibraryBootstrap.ensureInstalled(this, PnLibraryRuntime.MINIMUM_VERSION)
} catch (failure: Throwable) {
logger.log(Level.WARNING, "Не удалось подготовить pnLibrary; pnAuth работает без обновлений и диагностики.", failure)
false
}
val created = PnAuthBungeeRuntime.builder().plugin(this).build()
runtime = if (created.onLoad()) created else null
}

override fun onEnable() {
runtime?.onEnable()
if (runtime != null) connectPnLibrary()
}

private fun connectPnLibrary() {
if (!pnLibraryReady) return
try {
val connected = PnLibraryRuntime.connect(this)
pnLibrary = connected
connected.register(dataFolder.toPath(), "BungeeCord") { mapOf("version" to description.version) }
connected.enabled("BungeeCord")
} catch (failure: Throwable) {
logger.log(Level.WARNING, "pnLibrary не подключена к pnAuth; плагин работает без неё.", failure)
closePnLibrary()
}
}

private fun closePnLibrary() {
val closing = pnLibrary ?: return
pnLibrary = null
runCatching { closing.close() }
}

override fun onDisable() {
closePnLibrary()
runtime?.close()
}

Expand Down
2 changes: 2 additions & 0 deletions bungeecord/src/main/resources/bungee.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ author: privatenull
description: Extensible authentication and player API for BungeeCord, Velocity, Paper, and Folia.
depends:
- packetevents
softDepends:
- pnLibrary
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,26 @@ import org.bukkit.plugin.java.JavaPlugin
import ru.privatenull.pnauth.api.AuthApi
import ru.privatenull.pnauth.kernel.ExtensionKernel
import ru.privatenull.pnauth.platform.Platform
import org.pnfolder.pnlibrary.bukkit.bootstrap.PnLibraryBootstrap
import ru.privatenull.pnauth.dependency.PacketEventsBootstrap
import ru.privatenull.pnauth.integration.PnLibraryRuntime
import java.util.logging.Level

/** Paper/Folia bootstrap. All reusable behavior remains in the shared module. */
class PnAuthPaperPlugin : JavaPlugin() {
private var runtime: PnAuthPaperRuntime? = null
private var dependencyReady = false
private var pnLibraryReady = false
private var pnLibrary: PnLibraryRuntime? = null

override fun onLoad() {
// pnAuth keeps protecting the server even when pnLibrary cannot be prepared; only the shared services go missing.
pnLibraryReady = try {
PnLibraryBootstrap.ensureInstalled(this, PnLibraryRuntime.MINIMUM_VERSION)
} catch (failure: Throwable) {
logger.log(Level.WARNING, "Не удалось подготовить pnLibrary; pnAuth работает без обновлений и диагностики.", failure)
false
}
val result = PacketEventsBootstrap.ensure(
PacketEventsBootstrap.Platform.PAPER,
dataFolder.toPath(),
Expand All @@ -36,9 +48,37 @@ class PnAuthPaperPlugin : JavaPlugin() {
val created = PnAuthPaperRuntime.builder().plugin(this).build()
runtime = created
created.onEnable()
connectPnLibrary()
}

private fun connectPnLibrary() {
if (!pnLibraryReady) return
try {
val connected = PnLibraryRuntime.connect(this)
pnLibrary = connected
connected.register(dataFolder.toPath(), "Paper") {
mapOf("version" to description.version, "folia" to isFolia())
}
connected.enabled("Paper")
server.pluginManager.registerEvents(PnLibraryLifecycleListener(this), this)
} catch (failure: Throwable) {
logger.log(Level.WARNING, "pnLibrary не подключена к pnAuth; плагин работает без неё.", failure)
closePnLibrary()
}
}

internal fun closePnLibrary() {
val closing = pnLibrary ?: return
pnLibrary = null
runCatching { closing.close() }
}

private fun isFolia(): Boolean = runCatching {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer")
}.isSuccess

override fun onDisable() {
closePnLibrary()
runtime?.close()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ru.privatenull.pnauth.paper

import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.server.PluginDisableEvent

/** Releases pnAuth's pnLibrary registration before the shared runtime shuts down or is unloaded by hand. */
class PnLibraryLifecycleListener(private val plugin: PnAuthPaperPlugin) : Listener {

@EventHandler(priority = EventPriority.MONITOR)
fun onPluginDisable(event: PluginDisableEvent) {
if (!event.plugin.name.equals("pnLibrary", ignoreCase = true)) return
plugin.closePnLibrary()
}
}
23 changes: 22 additions & 1 deletion paper/src/main/resources/plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ api-version: '1.20'
folia-supported: true
author: privatenull
description: Extensible authentication and player API for Paper and Folia.
softdepend: [packetevents]
softdepend: [packetevents, pnLibrary]
commands:
_pnauthui:
description: Internal pnAuth UI action dispatcher.
Expand All @@ -27,3 +27,24 @@ permissions:
pnauth.admin.reload:
description: Allows reloading the pnAuth configuration.
default: op
pnauth.admin.commands.unregister:
description: Allows /auth unregister.
default: op
pnauth.admin.commands.changepassword:
description: Allows /auth changepassword.
default: op
pnauth.admin.commands.forcelogin:
description: Allows /auth forcelogin.
default: op
pnauth.admin.commands.forceregister:
description: Allows /auth forceregister.
default: op
pnauth.admin.commands.forcepremium:
description: Allows /auth forcepremium.
default: op
pnauth.admin.commands.broadcast:
description: Allows /auth broadcast.
default: op
pnauth.admin.commands.migrate:
description: Allows /auth migrate.
default: op
12 changes: 12 additions & 0 deletions plugin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ plugins {
}

def pluginVersion = version.toString()
def pnLibraryVersion = '0.0.1-dev.6'
def generatedSources = layout.buildDirectory.dir('generated/sources/pnauth')
configurations.runtimeClasspath {
// PacketEvents is a required external plugin and owns Adventure on BungeeCord.
Expand Down Expand Up @@ -74,6 +75,12 @@ dependencies {
compileOnly 'com.github.retrooper:packetevents-bungeecord:2.13.1-SNAPSHOT'
compileOnly 'com.github.retrooper:packetevents-spigot:2.13.0'
kapt 'com.velocitypowered:velocity-api:3.3.0-SNAPSHOT'
// The shared runtime plugin is installed by the pnLibrary bootstrap that is shaded into the jar;
// only its public API is needed to compile.
implementation "io.github.pnfolder:pnlibrary-bootstrap-bukkit:${pnLibraryVersion}"
implementation "io.github.pnfolder:pnlibrary-bootstrap-bungee:${pnLibraryVersion}"
implementation "io.github.pnfolder:pnlibrary-bootstrap-velocity:${pnLibraryVersion}"
compileOnly "io.github.pnfolder:pnlibrary-api:${pnLibraryVersion}"
implementation project(':shared')
implementation 'net.kyori:adventure-text-minimessage:4.26.1'
implementation 'net.kyori:adventure-text-serializer-gson:4.26.1'
Expand Down Expand Up @@ -109,6 +116,11 @@ tasks.named('shadowJar') {
relocate 'org.yaml.snakeyaml', 'ru.privatenull.pnauth.libs.snakeyaml'
relocate 'net.elytrium.serializer', 'ru.privatenull.pnauth.libs.serializer'
relocate 'com.fasterxml.jackson', 'ru.privatenull.pnauth.libs.jackson'
relocate 'org.pnfolder.pnlibrary.bootstrap', 'ru.privatenull.pnauth.libs.pnbootstrap'
relocate 'org.pnfolder.pnlibrary.bukkit.bootstrap', 'ru.privatenull.pnauth.libs.pnbootstrap.bukkit'
relocate 'org.pnfolder.pnlibrary.bungee.bootstrap', 'ru.privatenull.pnauth.libs.pnbootstrap.bungee'
relocate 'org.pnfolder.pnlibrary.velocity.bootstrap', 'ru.privatenull.pnauth.libs.pnbootstrap.velocity'
relocate 'org.pnfolder.pnlibrary.console', 'ru.privatenull.pnauth.libs.pnbootstrap.console'
manifest {
attributes(
'Implementation-Title': 'pnAuth',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package ru.privatenull.pnauth.integration

import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration
import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer
import org.pnfolder.pnlibrary.api.plugin.ModuleContext
import org.pnfolder.pnlibrary.api.plugin.PluginRegistration
import org.pnfolder.pnlibrary.api.remote.PolicyErrorAction
import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings
import org.pnfolder.pnlibrary.api.runtime.PnLibrary
import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity
import org.pnfolder.pnlibrary.api.runtime.PnLibraryProvider
import org.pnfolder.pnlibrary.api.updates.UpdateChannel
import java.nio.file.Path
import java.util.function.Supplier

/**
* pnLibrary integration shared by BungeeCord, Velocity and Paper. Loaded only after the pnLibrary bootstrap
* confirmed that a suitable runtime is installed; any failure here must never stop pnAuth itself.
*/
class PnLibraryRuntime private constructor(
private val owner: Any,
private val runtime: PnLibrary
) : AutoCloseable {
private var registration: PluginRegistration? = null
private var module: ModuleContext? = null

/** Registers pnAuth with the policy, diagnostics and update services. */
fun register(dataFolder: Path, platform: String, snapshot: Supplier<Map<String, Any?>>) {
check(registration == null) { "pnAuth уже зарегистрирован в pnLibrary" }
val created = runtime.plugins.register(owner)
registration = created
try {
module = created.registerModule(MODULE_ID) { builder ->
// bStats держит отдельный проект на каждую платформу; без ID платформы метрики не включаются.
BSTATS_PROJECT_IDS[platform]?.let { id -> builder.metrics { metrics -> metrics.bStats(id) } }
builder
// A policy that cannot be checked (offline, JRE without a compiler) never stops pnAuth;
// only an explicit denial from the policy does.
.remotePolicy(
RemotePolicySettings.builder()
.source(POLICY_SOURCE)
.onError(PolicyErrorAction.KEEP_RUNNING)
.support(PnLibraryIdentity.SUPPORT_URL)
.build()
)
.diagnostics(
dataFolder,
DiagnosticContainer.builder(MODULE_ID)
.value("platform", platform)
.snapshot(snapshot)
.configuration(
DiagnosticConfiguration.builder("config.yml")
.secretKeyRegex(SECRET_KEYS)
.build()
)
.build()
)
.updates("pnFolder", "pnAuth") { updater ->
updater
.channel(UpdateChannel.STABLE)
.automaticDownload(false)
.artifact(ARTIFACT_PATTERN, 17)
}
}
} catch (failure: RuntimeException) {
closeRegistration()
throw failure
}
}

/** Prints the "enabled" card in the console. */
fun enabled(platform: String) {
module?.lifecycle?.enabled()
?.ok("Платформа", platform)
?.show()
}

override fun close() {
val closing = module
module = null
if (closing != null && !closing.isClosed) {
runCatching { closing.lifecycle.disabled().show() }
}
closeRegistration()
}

private fun closeRegistration() {
val closing = registration
registration = null
if (closing != null && !closing.isClosed) closing.close()
}

companion object {
const val MINIMUM_VERSION = "0.0.1-dev.6"
private const val MODULE_ID = "pnauth"
// Ключ - название платформы, которое передаёт плагин. Для BungeeCord и Velocity нужны свои проекты в bStats.
private val BSTATS_PROJECT_IDS: Map<String, Int> = mapOf("Paper" to 35046)
private const val POLICY_SOURCE =
"https://raw.githubusercontent.com/pnFolder/pnlibrary-policy/main/.pnlibrary/policies/PnAuthPolicy.java"
private const val ARTIFACT_PATTERN = "(?i)^pnAuth-[0-9].*[.]jar$"
private const val SECRET_KEYS =
"(?i).*(password|passwd|secret|token|key|salt|uri|url|user(name)?|webhook|api)$"

@JvmStatic
fun connect(owner: Any): PnLibraryRuntime {
val runtime = PnLibraryProvider.get()
check(runtime.isAtLeastVersion(MINIMUM_VERSION)) {
"pnAuth требует pnLibrary $MINIMUM_VERSION или новее, установлена ${runtime.version}"
}
return PnLibraryRuntime(owner, runtime)
}
}
}
Loading
Loading