Skip to content
18 changes: 17 additions & 1 deletion SimpleAPI/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.release>21</maven.compiler.release>
<bouncycastle.version>1.85</bouncycastle.version>
</properties>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
Expand Down Expand Up @@ -71,6 +72,11 @@
<finalName>${project.name}</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
Expand Down Expand Up @@ -155,6 +161,16 @@
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
Expand Down Expand Up @@ -407,4 +423,4 @@
</build>
</profile>
</profiles>
</project>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.bencodez.simpleapi.file;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Locale;

/** Cross-platform helpers for forcing file contents and published directory entries. */
public final class DurableFiles {
private DurableFiles() { }

public static void forceFile(Path file) throws IOException {
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
channel.force(true);
}
}

public static void forceDirectory(Path directory) throws IOException {
if (directory == null) return;
try {
try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) {
channel.force(true);
}
} catch (AccessDeniedException unsupportedDirectoryHandle) {
// The Windows NIO provider cannot open directory handles. File contents are
// still forced before atomic publication; do not make persistence unusable.
if (!isWindowsName(System.getProperty("os.name", ""))) throw unsupportedDirectoryHandle;
} catch (UnsupportedOperationException unsupportedDirectoryForce) {
// Some providers support atomic moves but expose no directory-force operation.
}
}

public static boolean deleteIfExists(Path target) throws IOException {
boolean deleted = Files.deleteIfExists(target);
if (deleted) forceDirectory(target.toAbsolutePath().normalize().getParent());
return deleted;
}

public static void forceMoveDirectories(Path source, Path target) throws IOException {
try {
Path sourceParent = source.toAbsolutePath().normalize().getParent();
Path targetParent = target.toAbsolutePath().normalize().getParent();
forceDirectory(targetParent);
if (sourceParent != null && !sourceParent.equals(targetParent)) forceDirectory(sourceParent);
} catch (IOException failure) {
throw new PublishedException(failure);
}
}

public static boolean isWindowsName(String name) {
return name != null && name.trim().toLowerCase(Locale.ROOT).startsWith("windows");
}

/** Indicates that an atomic rename completed before metadata writeback failed. */
@SuppressWarnings("serial")
public static final class PublishedException extends IOException {
public PublishedException(IOException cause) {
super("File was published but its directory metadata could not be forced", cause);
}
}
}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.bencodez.simpleapi.servercomm.http;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.util.Base64;
import java.util.Locale;

/**
* A copy/paste connection code. It deliberately includes no long-lived credential:
* its only secret is a short-lived, single-use enrollment token. The trailing MAC is a
* corruption check keyed by that included token; it is not a proxy signature and cannot stop
* someone who can replace the whole code from replacing it with another valid code.
*/
public record HttpConnectionCode(String serverId, URI endpoint, String serverCertificatePin, String caCertificatePin,
Instant expiresAt, String enrollmentToken) {
private static final String LEGACY_VERSION = "VPH1";
private static final String VERSION = "VPH2";
private static final int MAX_CODE_LENGTH = 4096;

public HttpConnectionCode {
serverId = HttpTlsIdentity.canonicalServerId(serverId);
endpoint = validateEndpoint(endpoint);
serverCertificatePin = validatePin(serverCertificatePin, "server certificate pin");
caCertificatePin = validatePin(caCertificatePin, "CA certificate pin");
if (expiresAt == null) throw new IllegalArgumentException("Expiry is required");
enrollmentToken = validateToken(enrollmentToken);
}

public String encode() {
String serverPart = Base64.getUrlEncoder().withoutPadding()
.encodeToString(serverId.getBytes(StandardCharsets.UTF_8));
return encode(VERSION, serverPart);
}

String encodeLegacy() {
return encode(LEGACY_VERSION, serverId);
}

private String encode(String version, String serverPart) {
String endpointPart = Base64.getUrlEncoder().withoutPadding()
.encodeToString(endpoint.toASCIIString().getBytes(StandardCharsets.UTF_8));
String unsigned = String.join(".", version, serverPart, endpointPart, serverCertificatePin, caCertificatePin,
Long.toString(expiresAt.getEpochSecond()), enrollmentToken);
byte[] token = Base64.getUrlDecoder().decode(enrollmentToken);
return unsigned + "." + HttpTransportSecrets.hmacSha256Url(token, unsigned);
}

public boolean isActive(Clock clock) {
return expiresAt.isAfter(clock.instant());
}

public void requireActive(Clock clock) {
if (!isActive(clock)) throw new IllegalArgumentException("Connection code has expired");
}

public static HttpConnectionCode parse(String code) {
if (code == null || code.length() > MAX_CODE_LENGTH || code.indexOf('\n') >= 0 || code.indexOf('\r') >= 0)
throw new IllegalArgumentException("Connection code is invalid");
String[] parts = code.split("\\.", -1);
if (parts.length != 8 || (!VERSION.equals(parts[0]) && !LEGACY_VERSION.equals(parts[0])))
throw new IllegalArgumentException("Connection code is invalid");
try {
String serverId = LEGACY_VERSION.equals(parts[0]) ? parts[1]
: new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
String endpoint = new String(Base64.getUrlDecoder().decode(parts[2]), StandardCharsets.UTF_8);
String unsigned = String.join(".", parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]);
byte[] token = Base64.getUrlDecoder().decode(parts[6]);
String expected = HttpTransportSecrets.hmacSha256Url(token, unsigned);
if (!HttpTransportSecrets.constantTimeEquals(expected.getBytes(StandardCharsets.US_ASCII),
parts[7].getBytes(StandardCharsets.US_ASCII))) throw new IllegalArgumentException("Connection code is invalid");
return new HttpConnectionCode(serverId, new URI(endpoint), parts[3], parts[4], Instant.ofEpochSecond(Long.parseLong(parts[5])),
parts[6]);
} catch (IllegalArgumentException | URISyntaxException failure) {
throw new IllegalArgumentException("Connection code is invalid", failure);
}
}

private static URI validateEndpoint(URI value) {
if (value == null || !"https".equalsIgnoreCase(value.getScheme()) || value.getHost() == null
|| value.getUserInfo() != null || value.getFragment() != null || value.getRawQuery() != null)
throw new IllegalArgumentException("Endpoint must be an absolute HTTPS URL without credentials or query");
if (value.getPort() == 0 || value.getPort() > 65535 || value.getPort() < -1)
throw new IllegalArgumentException("Endpoint port is invalid");
String path = value.getRawPath();
if (path == null || path.isEmpty()) path = "/";
if (!path.endsWith("/")) path += "/";
try {
return new URI("https", null, value.getHost().toLowerCase(Locale.ROOT), value.getPort(), path, null, null);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve escaped endpoint paths during normalization

When an HTTPS endpoint uses a percent-escaped base path, such as https://example.com/api%20root/, getRawPath() returns /api%20root/ but this component constructor escapes the percent sign again, producing /api%2520root/. Encoding and parsing a connection code repeats the corruption, so enrollment and transport requests target the wrong reverse-proxy route; preserve the already-escaped raw path when rebuilding the URI.

Useful? React with 👍 / 👎.

} catch (URISyntaxException failure) {
throw new IllegalArgumentException("Endpoint is invalid", failure);
}
}

private static String validatePin(String pin, String name) {
if (pin == null || !pin.matches("[0-9a-fA-F]{64}")) throw new IllegalArgumentException(name + " is invalid");
return pin.toLowerCase(Locale.ROOT);
}

private static String validateToken(String token) {
if (token == null || token.length() < 43 || token.length() > 128 || !token.matches("[A-Za-z0-9_-]+"))
throw new IllegalArgumentException("Enrollment token is invalid");
try {
if (Base64.getUrlDecoder().decode(token).length < 32) throw new IllegalArgumentException("Enrollment token is invalid");
return token;
} catch (IllegalArgumentException failure) {
throw new IllegalArgumentException("Enrollment token is invalid", failure);
}
}
}
Loading
Loading