package p.studio.app.runtime; import com.fasterxml.jackson.databind.JsonNode; import p.studio.api.automation.*; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.*; /** Validates required v1 fields while permitting compatible minor additions. */ final class HeadlessWire { static final Set CAPABILITIES = Set.of("boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "cancel", "shutdown"); static String text(JsonNode node, String key) { var value = node.path(key); if (!value.isTextual() || value.textValue().isBlank()) throw invalid("Missing " + key); return value.textValue(); } static BigInteger uint(JsonNode value) { if (!value.isIntegralNumber() || value.bigIntegerValue().signum() < 0 || value.bigIntegerValue().bitLength() > 64) throw invalid("Invalid uint64"); return value.bigIntegerValue(); } static long count(JsonNode node, String key) { try { return uint(node.path(key)).longValueExact(); } catch (ArithmeticException overflow) { throw invalid("Counter exceeds requested operation range"); } } static void version(JsonNode value) { if (!value.path("major").isIntegralNumber() || !value.path("major").bigIntegerValue().equals(BigInteger.ONE)) throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Unsupported headless protocol major"); uint(value.path("minor")); } static void capabilities(JsonNode value) { if (!value.isArray()) throw invalid("Missing capabilities"); var actual = new HashSet(); for (var item : value) { if (!item.isTextual()) throw invalid("Invalid capability"); actual.add(item.textValue()); } if (!actual.containsAll(CAPABILITIES)) throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Required headless capability unavailable"); } static void state(JsonNode value) { for (var key : List.of("pc", "logicalFrameIndex", "tickIndex", "appId")) uint(value.path(key)); if (!Set.of("running", "paused", "terminated", "faulted").contains(text(value, "status")) || !value.path("stackTop").isArray()) throw invalid("Invalid state"); for (var item : value.path("stackTop")) { var data = item.path("value"); boolean valid = switch (text(item, "kind")) { case "int32" -> data.isIntegralNumber() && data.canConvertToInt(); case "int64" -> data.isTextual() && signed64(data.textValue()); case "float64", "string" -> data.isTextual(); case "boolean" -> data.isBoolean(); case "null" -> data.isNull(); case "heap_ref" -> { if (data.isObject()) { yield uint(data.path("index")).bitLength() <= 32 && uint(data.path("generation")).bitLength() <= 32; } uint(data); yield true; } default -> false; }; if (!valid) throw invalid("Invalid typed stack value"); } } private static boolean signed64(String text) { try { Long.parseLong(text); return true; } catch (NumberFormatException invalid) { return false; } } static void error(JsonNode value) { text(value, "code"); if (!value.path("message").isTextual() || !value.path("details").isObject()) throw invalid("Invalid structured error"); } static void fault(JsonNode value) { if (value.isNull()) return; if (!value.path("pc").isNull()) uint(value.path("pc")); if (!value.path("summary").isTextual()) throw invalid("Invalid fault summary"); switch (text(value, "kind")) { case "vm_trap" -> { var trap = value.path("trap"); for (var key : List.of("pc", "code", "opcode")) uint(trap.path(key)); if (!trap.path("message").isTextual() || !(trap.path("span").isObject() || trap.path("span").isNull())) throw invalid("Invalid trap"); } case "vm_panic" -> { if (!value.path("message").isTextual()) throw invalid("Invalid panic"); } case "vm_init" -> { text(value.path("initError"), "code"); text(value.path("initError"), "message"); } default -> throw invalid("Invalid fault kind"); } } static CanonicalCapture capture(JsonNode value, String session, String build) { if (!text(value, "mimeType").equals("image/png") || !text(value, "encoding").equals("base64") || !text(value, "pixelFormat").equals("RGBA8888")) throw invalid("Invalid capture encoding"); int width = dimension(value, "width"), height = dimension(value, "height"), stride = dimension(value, "stridePixels"); if (stride < width || (long) width * height > 16_777_216) throw invalid("Invalid or oversized framebuffer layout"); final byte[] png; try { png = Base64.getDecoder().decode(text(value, "data")); } catch (IllegalArgumentException malformed) { throw invalid("Invalid capture base64"); } byte[] signature = {(byte)137,80,78,71,13,10,26,10}; if (png.length < 33 || !Arrays.equals(signature, Arrays.copyOf(png, 8))) throw invalid("Invalid PNG"); var header = ByteBuffer.wrap(png); if (header.getInt(8) != 13 || header.getInt(12) != 0x49484452 || header.getInt(16) != width || header.getInt(20) != height || png[24] != 8 || png[25] != 6) throw invalid("PNG does not match RGBA8888 metadata"); try (var encoded = new javax.imageio.stream.MemoryCacheImageInputStream(new java.io.ByteArrayInputStream(png))) { var readers = javax.imageio.ImageIO.getImageReaders(encoded); if (!readers.hasNext()) throw invalid("Undecodable PNG"); var reader = readers.next(); try { reader.setInput(encoded); var decoded = reader.read(0); if (decoded == null || decoded.getWidth() != width || decoded.getHeight() != height) throw invalid("Undecodable PNG"); } finally { reader.dispose(); } } catch (java.io.IOException malformed) { throw invalid("Undecodable PNG"); } return new CanonicalCapture(session, build, uint(value.path("logicalFrameIndex")), uint(value.path("frameId")), width, height, stride, png); } private static int dimension(JsonNode value, String key) { long number = count(value, key); if (number < 1 || number > Integer.MAX_VALUE) throw invalid("Invalid dimension"); return (int) number; } static AutomationException invalid(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Invalid headless response: " + message); } }