package p.studio.app.mcp; import com.fasterxml.jackson.databind.*; import java.io.IOException; import java.net.URI; import java.nio.file.*; import java.nio.file.attribute.PosixFilePermissions; import java.util.Set; import java.util.concurrent.TimeUnit; import static java.nio.file.LinkOption.NOFOLLOW_LINKS; /** Local discovery data is untrusted until paths, permissions and live identity are verified. */ public final class ProjectConnectionFiles { public static final String RELATIVE = ".studio/mcp/connection.json"; private static final Set FILE_MODE = PosixFilePermissions.fromString("rw-------"); private ProjectConnectionFiles() { } public static Path directory(Path root) throws IOException { Path studio = root.resolve(".studio"), directory = studio.resolve("mcp"); safeDirectory(studio, false); safeDirectory(directory, true); return directory; } private static void safeDirectory(Path path, boolean privateDirectory) throws IOException { if (!Files.exists(path, NOFOLLOW_LINKS)) Files.createDirectory(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); if (Files.isSymbolicLink(path) || !Files.isDirectory(path, NOFOLLOW_LINKS)) throw new IOException("Unsafe connection directory"); if (privateDirectory) requirePrivate(path, true); } public static void requirePrivate(Path path, boolean directory) throws IOException { if (Files.isSymbolicLink(path) || !(directory ? Files.isDirectory(path, NOFOLLOW_LINKS) : Files.isRegularFile(path, NOFOLLOW_LINKS))) throw new IOException("Unsafe connection file"); var expected = directory ? PosixFilePermissions.fromString("rwx------") : FILE_MODE; if (!Files.getPosixFilePermissions(path, NOFOLLOW_LINKS).equals(expected) || !Files.getOwner(path, NOFOLLOW_LINKS).equals(Files.getOwner(Path.of(System.getProperty("user.home"))))) throw new IOException("Connection permissions must be restricted to the current user"); } public static void atomicPrivateWrite(Path target, byte[] bytes) throws IOException { if (Files.exists(target, NOFOLLOW_LINKS)) requirePrivate(target, false); var temp = Files.createTempFile(target.getParent(), ".connection-", ".tmp", PosixFilePermissions.asFileAttribute(FILE_MODE)); try { Files.write(temp, bytes); Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } finally { Files.deleteIfExists(temp); } } public static boolean tracked(Path root, String relative) throws IOException { try { var process = new ProcessBuilder("git", "-C", root.toString(), "ls-files", "-z", "--", relative).redirectError(ProcessBuilder.Redirect.DISCARD).start(); if (!process.waitFor(5, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Git check timed out"); } if (process.exitValue() != 0 && process.exitValue() != 128) throw new IOException("Cannot verify file tracking"); return process.getInputStream().read() != -1; } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Git check interrupted"); } } public static void ignore(Path root, String relative) throws IOException { Path path = root.resolve(".gitignore"); if (Files.isSymbolicLink(path)) throw new IOException("Unsafe ignore file"); String old = Files.exists(path) ? Files.readString(path) : ""; String rule = "/" + relative; if (old.lines().anyMatch(rule::equals)) return; Files.writeString(path, old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + rule + "\n"); } public static Descriptor read(Path root, ObjectMapper mapper) throws IOException { Path path = root.resolve(RELATIVE); if (Files.isSymbolicLink(root.resolve(".studio"))) throw new IOException("Unsafe discovery path"); requirePrivate(path.getParent(), true); requirePrivate(path, false); byte[] bytes; try (var input = Files.newInputStream(path, NOFOLLOW_LINKS)) { bytes = input.readNBytes(16 * 1024 + 1); } if (bytes.length > 16 * 1024) throw new IOException("Connection descriptor too large"); var json = mapper.readTree(bytes); if (json == null || !json.path("schemaVersion").isIntegralNumber() || !json.path("schemaVersion").canConvertToInt() || json.path("schemaVersion").asInt(-1) != 1) throw new IOException("Unsupported connection schema"); for (String field : Set.of("instanceId", "projectRoot", "endpoint", "credential", "catalogFingerprint")) if (!json.path(field).isTextual() || json.path(field).asText().isBlank()) throw new IOException("Invalid connection descriptor"); try { if (!Path.of(json.path("projectRoot").asText()).equals(root)) throw new IOException("Connection project mismatch"); URI endpoint = URI.create(json.path("endpoint").asText()); if (!"http".equals(endpoint.getScheme()) || !"127.0.0.1".equals(endpoint.getHost()) || endpoint.getPort() < 1 || endpoint.getPort() > 65535 || !"/mcp".equals(endpoint.getRawPath()) || endpoint.getRawQuery() != null || endpoint.getRawFragment() != null || endpoint.getUserInfo() != null) throw new IOException("Invalid loopback endpoint"); return new Descriptor(endpoint, json.path("instanceId").asText(), json.path("credential").asText(), json.path("catalogFingerprint").asText()); } catch (IllegalArgumentException invalid) { throw new IOException("Invalid connection descriptor"); } } public record Descriptor(URI endpoint, String instanceId, String credential, String catalogFingerprint) { @Override public String toString() { return "ProjectConnectionDescriptor[REDACTED]"; } } }