package ru.mtusi.messenger; import org.springframework.stereotype.Component; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.SecureRandom; import java.time.Instant; import java.util.Base64; import java.util.UUID; @Component public class CursorCodec { private final byte[] secret = new byte[32]; private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); private static final Base64.Decoder DECODER = Base64.getUrlDecoder(); public CursorCodec() { new SecureRandom().nextBytes(secret); } public record Position(Instant createdAt, UUID id) {} public String encode(String scope, Position position) { String payload = scope + "|" + position.createdAt() + "|" + position.id(); String encoded = ENCODER.encodeToString(payload.getBytes(StandardCharsets.UTF_8)); return encoded + "." + ENCODER.encodeToString(sign(encoded)); } public Position decode(String cursor, String scope) { if (cursor == null) return null; try { if (cursor.length() > 1024) throw new IllegalArgumentException(); String[] parts = cursor.split("\\.", -1); if (parts.length != 2 || !MessageDigest.isEqual(sign(parts[0]), DECODER.decode(parts[1]))) { throw new IllegalArgumentException(); } String[] fields = new String(DECODER.decode(parts[0]), StandardCharsets.UTF_8).split("\\|", -1); if (fields.length != 3 || !scope.equals(fields[0])) throw new IllegalArgumentException(); return new Position(Instant.parse(fields[1]), Input.uuid(fields[2])); } catch (RuntimeException exception) { throw ApiException.invalid("Некорректный cursor или cursor от другого ресурса"); } } private byte[] sign(String payload) { try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret, "HmacSHA256")); return mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)); } catch (java.security.GeneralSecurityException exception) { throw new IllegalStateException("HMAC is unavailable", exception); } } }