Skip to content

Commit

Permalink
initial mixin
Browse files Browse the repository at this point in the history
  • Loading branch information
iczero committed Dec 31, 2024
1 parent e428bac commit 214e047
Show file tree
Hide file tree
Showing 9 changed files with 210 additions and 64 deletions.
132 changes: 74 additions & 58 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
plugins {
id 'java-library'
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.neoforged.gradle.userdev' version '7.0.145'
id 'net.neoforged.moddev' version '1.0.21'
}

tasks.named('wrapper', Wrapper).configure {
Expand All @@ -29,52 +27,76 @@ base {
// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)

//minecraft.accessTransformers.file rootProject.file('src/main/resources/META-INF/accesstransformer.cfg')
//minecraft.accessTransformers.entry public net.minecraft.client.Minecraft textureManager # textureManager

// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
// applies to all the run configs below
configureEach {
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'

// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
systemProperty 'forge.logging.console.level', 'debug'

modSource project.sourceSets.main
}
neoForge {
// Specify the version of NeoForge to use.
version = project.neo_version

client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
parchment {
mappingsVersion = project.parchment_mappings_version
minecraftVersion = project.parchment_minecraft_version
}

server {
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
programArgument '--nogui'
}
// This line is optional. Access Transformers are automatically detected
// accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg')

// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
}
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
client()

// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}

server {
server()
programArgument '--nogui'
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}

// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
type = "gameTestServer"
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}

data {
data()

data {
// example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
// workingDirectory project.file('run-data')
// example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
// gameDirectory = project.file('run-data')

// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}

// applies to all the run configs above
configureEach {
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'

// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
logLevel = org.slf4j.event.Level.DEBUG
}
}

mods {
// define mod <-> source bindings
// these are used to tell the game which sources are for which mod
// mostly optional in a single mod project
// but multi mod projects should define one per mod
"${mod_id}" {
sourceSet(sourceSets.main)
}
}
}

Expand All @@ -90,14 +112,6 @@ configurations {
}

dependencies {
// Specify the version of Minecraft to use.
// Depending on the plugin applied there are several options. We will assume you applied the userdev plugin as shown above.
// The group for userdev is net.neoforged, the module name is neoforge, and the version is the same as the neoforge version.
// You can however also use the vanilla plugin (net.neoforged.gradle.vanilla) to use a version of Minecraft without the neoforge loader.
// And its provides the option to then use net.minecraft as the group, and one of; client, server or joined as the module name, plus the game version as version.
// For all intends and purposes: You can treat this dependency as if it is a normal library you would use.
implementation "net.neoforged:neoforge:${neo_version}"

// Example optional mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
Expand All @@ -123,9 +137,7 @@ dependencies {

// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.withType(ProcessResources).configureEach {
var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) {
var replaceProperties = [
minecraft_version : minecraft_version,
minecraft_version_range: minecraft_version_range,
Expand All @@ -140,11 +152,15 @@ tasks.withType(ProcessResources).configureEach {
mod_description : mod_description
]
inputs.properties replaceProperties

filesMatching(['META-INF/neoforge.mods.toml']) {
expand replaceProperties
}
expand replaceProperties
from "src/main/templates"
into "build/generated/sources/modMetadata"
}
// Include the output of "generateModMetadata" as an input directory for the build
// this works with both building through Gradle and the IDE.
sourceSets.main.resources.srcDir generateModMetadata
// To avoid having to run "generateModMetadata" manually, make it run on every project reload
neoForge.ideSyncTask generateModMetadata

// Example configuration to allow publishing using the maven-publish plugin
publishing {
Expand Down
9 changes: 6 additions & 3 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
org.gradle.jvmargs=-Xmx4G
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
org.gradle.debug=false

#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings
#read more on this at https://github.com/neoforged/ModDevGradle?tab=readme-ov-file#better-minecraft-parameter-names--javadoc-parchment
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
neogradle.subsystems.parchment.minecraftVersion=1.21.1
neogradle.subsystems.parchment.mappingsVersion=2024.11.17
parchment_minecraft_version=1.21.1
parchment_mappings_version=2024.11.17
# Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact
Expand Down
17 changes: 17 additions & 0 deletions src/main/java/net/hellomouse/authmemes/AuthMemes.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package net.hellomouse.authmemes;

import com.mojang.logging.LogUtils;
import net.minecraft.server.MinecraftServer;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import org.slf4j.Logger;

// The value here should match an entry in the META-INF/neoforge.mods.toml file
Expand Down Expand Up @@ -39,4 +43,17 @@ private void commonSetup(final FMLCommonSetupEvent event)
// Some common setup code
LOGGER.info("Hello, world!");
}

@SubscribeEvent
public void registerCommands(RegisterCommandsEvent event) {
// TODO
}

@SubscribeEvent
public void onServerStarted(ServerStartedEvent event) {
if (Config.enable && !event.getServer().usesAuthentication()) {
LOGGER.warn("{} is enabled but server is running in offline mode", MODID);
LOGGER.warn("This is most likely not what you want!");
}
}
}
28 changes: 25 additions & 3 deletions src/main/java/net/hellomouse/authmemes/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import com.mojang.logging.LogUtils;
import net.neoforged.bus.api.SubscribeEvent;
Expand Down Expand Up @@ -34,8 +35,8 @@ public class Config {

static final ModConfigSpec SPEC = BUILDER.build();

public static boolean enable;
public static HashMap<String, OfflinePlayer> offlinePlayers;
public static boolean enable = false;
public static HashMap<String, OfflinePlayer> offlinePlayers = new HashMap<>();

private static boolean validateOfflinePlayerEntry(final Object obj) {
if (obj instanceof String entry) {
Expand All @@ -51,18 +52,39 @@ private static boolean validateOfflinePlayerEntry(final Object obj) {
}

@SubscribeEvent
static void onLoad(final ModConfigEvent event)
static synchronized void onLoad(final ModConfigEvent event)
{
enable = ENABLED.get();
offlinePlayers.clear();
for (var entryStr : OFFLINE_PLAYERS.get()) {
try {
var entry = OfflinePlayer.parseConfigLine(entryStr);
var key = entry.username().toLowerCase();
if (offlinePlayers.containsKey(key)) {
LOGGER.warn("duplicate username {}, ignoring", entry.username());
continue;
}
offlinePlayers.put(key, entry);
// TODO: might need to update the profile cache
} catch (IllegalArgumentException e) {
LOGGER.warn("invalid entry in offline_players, ignoring", e);
}
}

LOGGER.info("configuration reloaded");
}

public static synchronized Optional<OfflinePlayer> lookupUsername(String username) {
if (!enable) {
return Optional.empty();
}

var key = username.toLowerCase();
var entry = offlinePlayers.get(key);
if (entry == null) {
return Optional.empty();
} else {
return Optional.of(entry);
}
}
}
5 changes: 5 additions & 0 deletions src/main/java/net/hellomouse/authmemes/OfflinePlayer.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package net.hellomouse.authmemes;

import net.minecraft.util.StringUtil;

import java.util.ArrayList;

public record OfflinePlayer(String username, ArrayList<SubnetInfo> allowedIps) {
Expand All @@ -10,6 +12,9 @@ public static OfflinePlayer parseConfigLine(String entry) throws IllegalArgument
}

String username = split1[0];
if (!StringUtil.isValidPlayerName(username)) {
throw new IllegalArgumentException("invalid username");
}
String addresses_str = split1[1];

var subnetsStr = addresses_str.split(",");
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/net/hellomouse/authmemes/SubnetInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ public static SubnetInfo parseSubnet(String what) throws IllegalArgumentExceptio
return new SubnetInfo(address, cidr);
}

@Override
public String toString() {
return this.address.toString() + "/" + this.cidr;
}

public boolean matches(SocketAddress saddr) {
Objects.requireNonNull(saddr);
if (saddr instanceof InetSocketAddress saddrInet) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@
package net.hellomouse.authmemes.mixin;

import com.llamalad7.mixinextras.sugar.Cancellable;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.GameProfileRepository;
import net.hellomouse.authmemes.Config;
import net.minecraft.core.UUIDUtil;
import net.minecraft.server.players.GameProfileCache;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.Optional;

@Mixin(GameProfileCache.class)
public class GameProfileCacheMixin {
@Inject(method = "lookupGameProfile", at = @At("HEAD"), cancellable = true)
private static void lookupGameProfileHead(GameProfileRepository pProfileRepo, String pName, CallbackInfoReturnable<Optional<GameProfile>> cir) {
var entry = Config.lookupUsername(pName);
if (entry.isEmpty()) {
return;
}

var offlineEntry = entry.get();
// return offline profile if username exists in config
cir.setReturnValue(Optional.of(UUIDUtil.createOfflineProfile(offlineEntry.username())));
}
}
Loading

0 comments on commit 214e047

Please sign in to comment.