Replace Paper pack bridge with server-only NeoForge resource-pack core

This commit is contained in:
2026-09-06 18:22:00 +03:00
parent 70b10180d8
commit 09d002987f
31 changed files with 1645 additions and 864 deletions
@@ -0,0 +1,143 @@
package online.astradev.packs;
import com.google.gson.*;
import java.io.*;
import java.net.http.*;
import java.time.Duration;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import java.util.zip.*;
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
public final class PackBuilder {
public record Pack(Path path, String sha1, int files, long bytes) {}
private record Asset(byte[] data, String owner) {}
private final PackConfig config;
private final SortedMap<String, Asset> assets = new TreeMap<>();
private long total;
public PackBuilder(PackConfig config) { this.config = config; }
public Pack build(Path root, String resourceVersion) throws IOException {
for (String source : config.build.sources) {
Path path = root.resolve(source).toAbsolutePath().normalize();
if (!Files.exists(path)) throw new IOException("Source does not exist: " + path);
if (Files.isDirectory(path)) directory(path); else archive(path, false);
}
if (config.build.scanModJars && Files.isDirectory(root.resolve("mods"))) {
try (var files = Files.list(root.resolve("mods"))) {
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList()) archive(jar, true);
}
}
JsonObject pack = new JsonObject();
// 26.2 uses major/minor resource-pack versions.
JsonElement version = JsonParser.parseString(resourceVersion);
pack.add("min_format", version); pack.add("max_format", version.deepCopy());
pack.addProperty("description", config.build.description);
JsonObject meta = new JsonObject(); meta.add("pack", pack);
assets.put("pack.mcmeta", new Asset(PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8), "AstraPacks"));
Path output = config.storage(root).resolve("output");
Files.createDirectories(output);
Path temp = Files.createTempFile(output, "build-", ".tmp");
try {
try (var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)))) {
for (var item : assets.entrySet()) {
ZipEntry entry = new ZipEntry(item.getKey()); entry.setTime(0);
zip.putNextEntry(entry); zip.write(item.getValue().data()); zip.closeEntry();
}
}
String hash = hash(temp, "SHA-1");
Path destination = output.resolve(hash + ".zip");
if (!Files.exists(destination)) Files.move(temp, destination, StandardCopyOption.ATOMIC_MOVE);
else if (!hash(destination, "SHA-1").equals(hash))
throw new IOException("Published ZIP was modified: " + destination);
PackFiles.atomicWrite(output.resolve("current.json"), PackConfig.JSON.toJson(Map.of("sha1", hash, "files", assets.size())).getBytes(StandardCharsets.UTF_8));
return new Pack(destination, hash, assets.size(), Files.size(destination));
} finally { Files.deleteIfExists(temp); }
}
public static Pack previous(Path root, PackConfig config) throws IOException {
Path output = config.storage(root).resolve("output");
try {
JsonObject info = JsonParser.parseString(Files.readString(output.resolve("current.json"))).getAsJsonObject();
String sha1 = info.get("sha1").getAsString();
if (!sha1.matches("[a-f0-9]{40}")) throw new IOException("Invalid pack hash");
Path path = output.resolve(sha1 + ".zip");
if (!hash(path, "SHA-1").equals(sha1)) throw new IOException("Stored resource pack hash mismatch");
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
} catch (RuntimeException e) { throw new IOException("Invalid previous build", e); }
}
private void directory(Path root) throws IOException {
if (Files.isSymbolicLink(root)) throw new IOException("Symlink source: " + root);
try (var walk = Files.walk(root)) {
for (Path p : walk.sorted().toList()) {
if (Files.isSymbolicLink(p)) throw new IOException("Symlink resource: " + p);
if (!Files.isRegularFile(p)) continue;
String name = root.relativize(p).toString().replace('\\', '/');
// A source is a pack root, or a directory of named pack roots.
if (!isResource(name)) {
int slash = name.indexOf('/');
if (slash >= 0 && isResource(name.substring(slash + 1))) name = name.substring(slash + 1);
else if (name.endsWith(".zip")) { archive(p, false); continue; }
else continue;
}
try (var in = Files.newInputStream(p)) { add(name, in, p.toString()); }
}
}
}
private void archive(Path path, boolean mod) throws IOException {
try (var zip = new ZipFile(path.toFile())) {
String prefix = "";
if (mod) {
var descriptor = zip.getEntry("astra-pack.properties");
if (descriptor == null) return;
Properties props = new Properties();
try (var in = zip.getInputStream(descriptor)) { props.load(in); }
String schema = props.getProperty("schema", "");
if (schema.equals("2")) prefix = "astra-resourcepack/";
else throw new IOException("Invalid AstraPacks bundle descriptor: " + path);
}
for (var entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) continue;
String name = entry.getName().substring(prefix.length());
if (!isResource(name)) continue;
try (var in = zip.getInputStream(entry)) { add(name, in, path + "!/" + entry.getName()); }
}
}
}
private static boolean isResource(String name) { return name.startsWith("assets/") || name.equals("pack.png"); }
private void add(String name, InputStream in, String owner) throws IOException {
PackFiles.safe(Path.of("."), name);
int limit = config.build.maxFileMiB * 1024 * 1024;
byte[] bytes = in.readNBytes(limit + 1);
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
total += bytes.length;
if (total > config.build.maxTotalMiB * 1024L * 1024L) throw new IOException("Sources exceed maxTotalMiB");
Asset old = assets.get(name);
if (old != null && !Arrays.equals(bytes, old.data()) && config.build.conflictPolicy.equals("error"))
throw new IOException("Conflicting resource " + name + " from " + old.owner() + " and " + owner);
assets.put(name, new Asset(bytes, owner));
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
}
public static String hash(Path file, String algorithm) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) { in.transferTo(OutputStream.nullOutputStream()); }
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException e) { throw new AssertionError(e); }
}
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
Path tmp = Files.createTempFile(pack.path().getParent(), "external-", ".tmp");
try (HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).followRedirects(HttpClient.Redirect.NORMAL).build()) {
HttpRequest request = HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl)).timeout(Duration.ofSeconds(30)).GET().build();
// A bounded subscriber prevents an external host from consuming arbitrary memory/disk.
HttpResponse<byte[]> response = client.send(request, info -> HttpResponse.BodySubscribers.limiting(HttpResponse.BodySubscribers.ofByteArray(), pack.bytes() + 1));
if (response.statusCode() != 200) throw new IOException("External pack HTTP " + response.statusCode());
Files.write(tmp, response.body());
if (!PackBuilder.hash(tmp, "SHA-1").equals(pack.sha1())) throw new IOException("External ZIP differs from built ZIP. Upload " + pack.path() + ", then /astrapacks publish");
} catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); }
finally { Files.deleteIfExists(tmp); }
}
}