import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HexFormat; import java.util.List; import java.util.regex.Pattern; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * v0.1 DRAFT. Borrou webhook signature verification, JDK only (Java 17+). * *
Every delivery carries {@code Borrou-Signature: t= Verify the raw bytes exactly as received, before any JSON parsing; reject a timestamp more
* than five minutes from your clock; then de-duplicate on the event's {@code id} (also
* {@code Borrou-Event-Id}).
*/
public final class BorrouWebhooks {
public static final String SIGNATURE_HEADER = "Borrou-Signature";
public static final long DEFAULT_TOLERANCE_SECONDS = 300;
private static final Pattern TIMESTAMP = Pattern.compile("[0-9]{1,12}");
private static final Pattern SIGNATURE = Pattern.compile("[0-9a-f]{64}");
public enum Result {
OK,
MISSING,
MALFORMED,
STALE,
MISMATCH
}
private BorrouWebhooks() {}
/** With your clock and the default tolerance. */
public static Result verify(String header, byte[] rawBody, String secret) {
return verify(header, rawBody, secret, DEFAULT_TOLERANCE_SECONDS, System.currentTimeMillis() / 1000);
}
public static Result verify(String header, byte[] rawBody, String secret, long toleranceSeconds, long nowSeconds) {
if (header == null || header.isEmpty()) return Result.MISSING;
Long timestamp = null;
List