package com.it_screen.edgevision; import android.content.res.AssetManager; import java.io.InputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.json.JSONObject; final class ModelRegistry { private final AssetManager assets; ModelRegistry(AssetManager assets) { this.assets = assets; } List list(String type) throws Exception { List entries = new ArrayList<>(); String[] paths = assets.list("models"); if (paths == null) return entries; for (String path : paths) { if (!path.endsWith(".json")) continue; try (InputStream in = assets.open("models/" + path)) { Entry entry = new Entry(new JSONObject(new String(readBytes(in), java.nio.charset.StandardCharsets.UTF_8))); if (entry.json.getString("type").equals(type) && entry.allowedInBuild()) entries.add(entry); } } entries.sort(java.util.Comparator.comparing(Entry::toString)); return Collections.unmodifiableList(entries); } byte[] verified(Entry entry) throws Exception { String path = entry.json.getString("file"); if (!path.matches("models/[A-Za-z0-9._-]+\\.onnx") || !"ONNX".equals(entry.json.getString("format"))) throw new IllegalArgumentException("Invalid ONNX asset " + path); if (!entry.allowedInBuild()) throw new SecurityException("Model is not approved for this build: " + entry); try (InputStream in = assets.open(path)) { byte[] bytes = readBytes(in); verify(entry.json, bytes); return bytes; } } private void verify(JSONObject manifest, byte[] bytes) throws Exception { byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); StringBuilder hex = new StringBuilder(); for (byte b : digest) hex.append(String.format(java.util.Locale.ROOT, "%02x", b & 255)); if (bytes.length != manifest.getLong("size") || !hex.toString().equalsIgnoreCase(manifest.getString("sha256"))) throw new SecurityException("Model checksum mismatch: " + manifest.getString("id")); } static byte[] readBytes(InputStream stream) throws java.io.IOException { java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); byte[] buffer = new byte[8192]; for (int count; (count = stream.read(buffer)) >= 0;) { if (output.size() > 32 * 1024 * 1024 - count) throw new java.io.IOException("Asset exceeds 32 MiB"); output.write(buffer, 0, count); } return output.toByteArray(); } static final class Entry { final JSONObject json; Entry(JSONObject json) { this.json = json; } boolean allowedInBuild() { boolean allowed = json.optBoolean("productionAllowed") || (FaceReId.CONTROLLED_POC && json.optBoolean("controlledPocAllowed") && "reid".equals(json.optString("type"))); return allowed && json.optBoolean("commercialUse") && json.optBoolean("modificationAllowed") && json.optBoolean("redistributionAllowed") && "verified".equals(json.optString("licenseVerification")); } JSONObject input() throws Exception { return json.getJSONObject("input"); } @Override public String toString() { return json.optString("name") + " " + json.optString("version"); } } }