package p.studio.app.assets; import p.studio.api.assets.AssetBatches.*; import p.studio.app.evidence.PngEvidenceCodec; import java.nio.file.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** Exact human-selected external source grants. Agent supplied strings cannot create grants. */ final class AssetPngSources { record Grant(Path project,Path source,AuthorizedPng value){} private final Map grants=new ConcurrentHashMap<>(); private final PngEvidenceCodec png=new PngEvidenceCodec(); AuthorizedPng authorize(Path root,Path source)throws Exception { Path canonical=source.toRealPath();byte[] bytes=read(canonical);var pixels=png.decode(bytes); var value=new AuthorizedPng(UUID.randomUUID().toString(),AssetWorkspaceFiles.hash(bytes),bytes.length,pixels.width(),pixels.height()); grants.put(value.grantId(),new Grant(root.toRealPath(),canonical,value));return value; } Path resolve(Path root,PngInput input)throws Exception { if(input.projectRelativePath()!=null)return AssetWorkspaceFiles.path(root,input.projectRelativePath()); Grant grant=grants.get(input.externalGrantId()); if(grant==null||!grant.project().equals(root.toRealPath()))throw new IllegalArgumentException("PNG source has no matching project-bound human grant"); if(!grant.source().toRealPath().equals(grant.source()))throw new IllegalArgumentException("Selected PNG source was redirected"); return grant.source(); } byte[] bytes(Path root,PngInput input)throws Exception { byte[] bytes=read(resolve(root,input));png.decode(bytes); if(!AssetWorkspaceFiles.hash(bytes).equals(input.sha256()))throw new IllegalArgumentException("PNG source bytes changed"); return bytes; } private static byte[] read(Path path)throws Exception { if(!Files.isRegularFile(path)||Files.size(path)>32*1024*1024)throw new IllegalArgumentException("PNG source must be a bounded regular file"); try(var stream=Files.newInputStream(path)) { byte[] bytes=stream.readNBytes(32*1024*1024+1); if(bytes.length>32*1024*1024)throw new IllegalArgumentException("PNG source exceeds 32 MiB");return bytes; } } }