package ar.com.companeros.clientupdate;
import ar.com.companeros.Companeros;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.*;
import java.math.BigInteger;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.*;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.loading.FMLPaths;
/** Canal firmado del cliente. No depende de Rapsodia, PowerShell ni cuentas de API. */
@Mod.EventBusSubscriber(modid = Companeros.ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public final class ClientUpdates {
public static final String ORIGIN = "https://raps-cliente.pages.dev";
private static final AtomicBoolean CHECKING = new AtomicBoolean();
private ClientUpdates() { }
public record Release(long sequence, String hash, long bytes, URI url) { }
// INICIO: una comprobación en segundo plano por arranque; jamás en el hilo de renderizado.
@SubscribeEvent public static void setup(FMLClientSetupEvent event) {
if (CHECKING.compareAndSet(false, true)) CompletableFuture.runAsync(ClientUpdates::prepare);
}
private static void prepare() {
Path state = FMLPaths.GAMEDIR.get().toAbsolutePath().normalize().resolve("config/raps/client-updates");
Path staged = null;
try {
UpdateInstaller.assertPlainPath(state); Files.createDirectories(state);
if (Files.exists(state.resolve("disabled"))) return;
Path target = ModList.get().getModFileById(Companeros.ID).getFile().getFilePath().toAbsolutePath().normalize();
if (!target.getParent().equals(FMLPaths.MODSDIR.get().toAbsolutePath().normalize())
|| !target.getFileName().toString().equals("Raps.jar")) return;
UpdateInstaller.assertPlainPath(target);
String oldHash = UpdateInstaller.hash(target);
long baseline = Long.parseLong(resource("/raps/client-update-build.txt").trim());
Path installed = state.resolve("installed-sequence.txt");
if (Files.exists(installed)) {
if (Files.size(installed) > 64) throw new IOException("Estado de actualización inválido");
baseline = Math.max(baseline, Long.parseLong(Files.readString(installed).trim()));
}
HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER).build();
Release release;
try (var input = download(http, URI.create(ORIGIN + "/release.json"))) {
release = verify(input.readNBytes(32769), resource("/raps/client-update-key.xml"), baseline);
}
if (release.hash().equals(oldHash)) return;
staged = Files.createTempFile(state, "Raps-", ".pending");
try (var input = download(http, release.url()); var output = Files.newOutputStream(staged)) {
byte[] buffer = new byte[65536]; int count; long total = 0;
while ((count = input.read(buffer)) >= 0) {
total += count;
if (total > release.bytes()) throw new IOException("Descarga demasiado grande");
output.write(buffer, 0, count);
}
if (total != release.bytes()) throw new IOException("Descarga incompleta");
}
if (!UpdateInstaller.hash(staged).equals(release.hash())) throw new IOException("Hash de actualización inválido");
UpdateInstaller.assertRapsJar(staged);
Path helper = Files.createTempFile(state, "installer-", ".jar");
try (var archive = new JarOutputStream(Files.newOutputStream(helper))) {
String name = "ar/com/companeros/clientupdate/UpdateInstaller.class";
archive.putNextEntry(new JarEntry(name));
try (var input = ClientUpdates.class.getResourceAsStream("/" + name)) {
if (input == null) throw new IOException("Falta el instalador");
input.transferTo(archive);
}
archive.closeEntry();
}
ProcessHandle parent = ProcessHandle.current();
boolean windows = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win");
Path java = Path.of(System.getProperty("java.home"), "bin", windows ? "javaw.exe" : "java");
new ProcessBuilder(java.toString(), "-Xms8m", "-Xmx32m", "-cp", helper.toString(), UpdateInstaller.class.getName(),
Long.toString(parent.pid()), Long.toString(parent.info().startInstant().orElseThrow().toEpochMilli()),
target.toString(), staged.toString(), oldHash, release.hash(), Long.toString(release.sequence()))
.redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.appendTo(state.resolve("installer.log").toFile())).start();
staged = null;
} catch (Exception failure) {
com.mojang.logging.LogUtils.getLogger().warn("Raps conservó el cliente instalado: actualización no disponible ({})", failure.getClass().getSimpleName());
} finally {
if (staged != null) try { Files.deleteIfExists(staged); } catch (IOException ignored) { }
}
}
// AUTENTICIDAD: firma RSA anclada al JAR, dominio fijo, caducidad y rechazo de versiones antiguas.
public static Release verify(byte[] bytes, String publicXml, long baseline) throws Exception {
if (bytes.length > 32768) throw new IOException("Manifiesto demasiado grande");
JsonObject envelope = JsonParser.parseString(new String(bytes, StandardCharsets.UTF_8)).getAsJsonObject();
byte[] payload = Base64.getDecoder().decode(envelope.get("payload").getAsString());
byte[] signed = Base64.getDecoder().decode(envelope.get("signature").getAsString());
var matcher = java.util.regex.Pattern.compile("([^<]+)([^<]+)").matcher(publicXml);
if (!matcher.find()) throw new IOException("Clave pública inválida");
var key = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(
new BigInteger(1, Base64.getDecoder().decode(matcher.group(1))), new BigInteger(1, Base64.getDecoder().decode(matcher.group(2)))));
Signature verifier = Signature.getInstance("SHA256withRSA"); verifier.initVerify(key); verifier.update(payload);
if (!verifier.verify(signed)) throw new IOException("Firma de actualización inválida");
JsonObject release = JsonParser.parseString(new String(payload, StandardCharsets.UTF_8)).getAsJsonObject();
long sequence = release.get("sequence").getAsLong(), size = release.get("bytes").getAsLong();
String hash = release.get("sha256").getAsString();
Instant expires = Instant.parse(release.get("expiresUtc").getAsString());
URI url = URI.create(release.get("url").getAsString());
if (release.get("schema").getAsInt() != 1 || !release.get("modId").getAsString().equals(Companeros.ID)
|| !release.get("minecraft").getAsString().equals("1.20.1") || sequence < baseline || sequence <= 0
|| size < 1024 || size > 33554432 || !hash.matches("[a-f0-9]{64}") || !expires.isAfter(Instant.now())
|| expires.isAfter(Instant.now().plus(Duration.ofDays(100)))
|| !url.toString().equals(ORIGIN + "/releases/Raps-" + sequence + ".jar"))
throw new IOException("Actualización incompatible, vencida o fuera del canal");
return new Release(sequence, hash, size, url);
}
private static InputStream download(HttpClient client, URI uri) throws Exception {
var response = client.send(HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(30)).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() != 200) { response.body().close(); throw new IOException("Canal no disponible"); }
InputStream input = response.body();
CompletableFuture.delayedExecutor(90, TimeUnit.SECONDS).execute(() -> { try { input.close(); } catch (IOException ignored) { } });
return input;
}
private static String resource(String name) throws IOException {
try (var input = ClientUpdates.class.getResourceAsStream(name)) {
if (input == null) throw new IOException("Falta la configuración de actualización");
return new String(input.readNBytes(16384), StandardCharsets.UTF_8);
}
}
}